This is actually part of a much bigger program, but I cut it down to the problematic area to make it easier to read.

import javax.swing.JButton;

public class test{
	static GameButton[] grid;
	
	static class GameButton extends JButton{
		int value = 0;
		
	}
	public static void main(String[] args){
		grid = new GameButton[1];
		if(grid[0].value == 0){
			System.out.println("It's working");
		}
	}
Exception in thread "main" java.lang.NullPointerException
	at test.main(test.java:11) <===== thats line 11

The problem is for sure the array.... It doesn't actually allocate "int value = 0;" into memory for each of the array elements, which means "value" is still null in memory, not 0..

How can I fix this problem? Also, this is one of the weirdest ones I've come across, so if someone can explain to me what actually happens when I do "grid = new GameButton[1];" with respect to that "int value = 0;" in the GameButton class, maybe I can get some kind of understanding.... Why is value = null and not 0?

Switching from creating a new array with 1 elements:
"grid = new GameButton[1];"

into a new GameButton constructor:
"grid = new GameButton();"

seems to work but why doesn't creating an array with 1 element call the GameButton constructor for each element automatically? It's too confusing.....

You create a new NOT null ARRAY that holds GameButton elements: grid = new GameButton[1]; grid is an ARRAY.

But:
grid[0] is a BUTTON and you never instantiate it.

So the answer to your problem is quite simple:

Example:

int N=5;
grid = new GameButton[N];

for (int i=0;i<grid.length;i++) { //remember grid is an ARRAY
   grid[i] = new JButton();  //grid[i] is a BUTTON
}

I see javaAddict. Thanks..

So, "grid = new GameButton[N];" is just an array of uninitiated GameButtons. I have to:

for (int i=0;i<grid.length;i++) {
grid = new GameButton();
}

after creating the array to initiate each all of them manually.

I actually had this in the program but it was in the wrong place :).. Thnx again.

Yes, but that still doesn't guarantee that value will == 0, unless you explicitly set it to be so.

Yes it does, since primitive member variables are assigned their default values when the instance is created; which in case of integer numeric types is 0.

Yes, but that still doesn't guarantee that value will == 0, unless you explicitly set it to be so.

In your code you say:

static class GameButton extends JButton{
   int value = 0;
}

So why value wouldn't be zero?

In my code? It's not my code. But I did miss that, I thought he didn't post his class for some reason. The Ramen could be to blame :p

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.