NullPointerException Error in Code that Prints Array Elements
I created the ArrayDriver and ArrayClass1 classes to gain some experiences working with arrays and array elements. The code in ArrayDriver is suppose to:
1) Create an array of ArrayClass1 objects.
2) Initialize the two attributes of each array element to 0 and print this information out.
3) Modify each array element's attribute and print out the modified array element's attributes.
I encountered a Nullpointerexception error while compiling the ArrayDriver class with Eclipse. I read that this error occurs when a pointer is dereferenced but has not been instantiated (java - What is a Null Pointer Exception? - Stack Overflow). I created an array and initialized every array element with the first for loop. Still, I cannot correct the problem.
Code Java:
public class ArrayDriver {
public static void main(String[] args){
int ARRAY_LENGTH = 10;
ArrayClass1 [] alpha = new ArrayClass1[ARRAY_LENGTH]; //Declares and instantiates the ArrayClass1 array called alpha
for(int i = ARRAY_LENGTH-1; i-1>=0; i--){ //Initializes the attributes of each alpha array element (both x and y) to 0
alpha[i].x = 0;
alpha[i].y = 0;
}
for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){ //Print out what is initialized
System.out.println("Old Array["+i+"]x: "+alpha[i].x);
System.out.println("Old Array["+i+"]y: "+alpha[i].y);
}
for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){ //Modifies each array element's attributes
alpha[i].x = i;
alpha[i].y = i+1;
}
for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){ //Prints out new attributes
System.out.println("New Array["+i+"]x: "+alpha[i].x);
System.out.println("New Array["+i+"]y: "+alpha[i].y);
}
}
}
Array Class:
Code Java:
public class ArrayClass1 {
public int x = 0;
public int y = 0;
public ArrayClass1(int x, int y){
this.x = x;
this.y = y;
}
}
Re: NullPointerException Error in Code that Prints Array Elements
The NullPointerExpression will occur when you run the program. (Just a nitpick, but it pays to be precise...)
Could you post the stack trace: the long message that you get at the console when an exception occurs? And indicate which line(s) of your code it is referring to?
Re: NullPointerException Error in Code that Prints Array Elements
Quote:
Originally Posted by
Atypically Engineered
I created the ArrayDriver and ArrayClass1 classes to gain some experiences working with arrays and array elements. The code in ArrayDriver is suppose to:
1) Create an array of ArrayClass1 objects.
2) Initialize the two attributes of each array element to 0 and print this information out.
3) Modify each array element's attribute and print out the modified array element's attributes.
I encountered a Nullpointerexception error while compiling the ArrayDriver class with Eclipse. I read that this error occurs when a pointer is dereferenced but has not been instantiated (
java - What is a Null Pointer Exception? - Stack Overflow). I created an array and initialized every array element with the first for loop. Still, I cannot correct the problem.
Code Java:
public class ArrayDriver {
public static void main(String[] args){
int ARRAY_LENGTH = 10;
ArrayClass1 [] alpha = new ArrayClass1[ARRAY_LENGTH]; //Declares and instantiates the ArrayClass1 array called alpha
for(int i = ARRAY_LENGTH-1; i-1>=0; i--){ //Initializes the attributes of each alpha array element (both x and y) to 0
alpha[i].x = 0;
alpha[i].y = 0;
}
for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){ //Print out what is initialized
System.out.println("Old Array["+i+"]x: "+alpha[i].x);
System.out.println("Old Array["+i+"]y: "+alpha[i].y);
}
for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){ //Modifies each array element's attributes
alpha[i].x = i;
alpha[i].y = i+1;
}
for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){ //Prints out new attributes
System.out.println("New Array["+i+"]x: "+alpha[i].x);
System.out.println("New Array["+i+"]y: "+alpha[i].y);
}
}
}
Array Class:
Code Java:
public class ArrayClass1 {
public int x = 0;
public int y = 0;
public ArrayClass1(int x, int y){
this.x = x;
this.y = y;
}
}
Hello Atypically Engineered!
Your first for loop does not initialize your alpha array, you assign values to alpha[i].x and alpha[i].y. You should give values to alpha[i].
Here is a typical example for initializing an int array
Code java:
int[] x = new int [10];
for (int i = 0; i<x.length; i++ )
x[i] = i;
}
Re: NullPointerException Error in Code that Prints Array Elements
Nice link, by the way.
Near the bottom - and garnering zero votes :( - we read:
"In Java every things is in the form of class.
If you want to use any object then you have two phases
Declare
Initialization
Example:
Declaration: int a;
initialization: a=0;
Same for Array concept
Declaration: Item i[]=new Item[5];
Initialization: i[0]=new Item();
If you not given Initialization section then the NullpointerException arise."
Re: NullPointerException Error in Code that Prints Array Elements
Aha! Along the lines with what andreas90 said, I did not initialize the arrays. The full stack trace was:
Exception in thread "main" java.lang.NullPointerException
at ArrayDriver.main(ArrayDriver.java:13)
Line 13 is the alpha[i].x = 0 line. NullPointerException occurred when java executed the code and tried to assign values to the array elements before initializing them. Would this imply that when an array of whatever object is declared, each array element is initialized to null by java? (Or is this true only for arrays of user-defined classes? Or is it true for all declared but user-uninitialized statements?
It seems that I confused declaring and initializing the array with initializing the array elements. But if "alpha[i] = new ArrayClass1(0,0);" initializes each element, then why didn't I get an error when I ran:
Code Java:
public class ArrayDriver {
public static void main(String[] args){
int ARRAY_LENGTH = 10;
ArrayClass1 [] alpha = new ArrayClass1[ARRAY_LENGTH]; //Declares and instantiates the ArrayClass1 array called alpha
for(int i = ARRAY_LENGTH-1; i-1>=0; i--){ //Initializes the attributes of each alpha array element (both x and y) to 0
alpha[i] = new ArrayClass1(0,0);
alpha[i] = new ArrayClass1(0,0);
}
for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){ //Print out what is initialized
System.out.println("Old Array["+i+"]x: "+alpha[i].x);
System.out.println("Old Array["+i+"]y: "+alpha[i].y);
}
for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){ //Modifies each array element's attributes
alpha[i].x = i;
alpha[i].y = i+1;
}
for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){ //Prints out new attributes
System.out.println("New Array["+i+"]x: "+alpha[i].x);
System.out.println("New Array["+i+"]y: "+alpha[i].y);
}
}
}
since I initialized alpha[i] = new ArrayClass1(0,0); multiple times?
Re: NullPointerException Error in Code that Prints Array Elements
Quote:
Would this imply that when an array of whatever object is declared, each array element is initialized to null by java? (Or is this true only for arrays of user-defined classes? Or is it true for all declared but user-uninitialized statements?
When you declare a variable of an array type ("Foo[] fooArr;") it will have the value null. (But in a method or constructor you simply can't use a variable you have declared there before it is initialised: that's a compile time error.)
When you initialise the variable of type array ("fooArr = new Foo[10]") its elements will all be null. But arrays of primitive things *do* get values which makes sense because they certainly can't be null.
It follows that the initialisation of the array elements is a second operation. Unless you use a shorthand like String[] strArr = new String[]{"fee", "fie", "foe", "fum"};
User defined classes are like every other sort of class.
Maybe all this is easier to see in code. The commented out lines are intended to be uncommented so you can watch the ensuing carnage. (Posted as an example of the sort of experiment you can perform to answer/test your own questions/hypotheses).
Code :
public class WhatsMyValue {
private int[] intArr;
private Object[] obArr;
public static void main(String[] args) {
int[] bad;
// won't compile: "The local variable bad may not have been initialized"
//System.out.println(bad);
WhatsMyValue test = new WhatsMyValue();
// array variables have value null
System.out.println("intArr=" + test.intArr);
System.out.println("obArr=" + test.obArr);
// won't run: "NullPointerException", intArr is null so can't use []
//System.out.println("intArr[0]=" + test.intArr[0]);
test.intArr = new int[10];
test.obArr = new Object[10];
// once the arrays are initialised the values are null or zero or false
System.out.println("intArr[0]=" + test.intArr[0]);
System.out.println("obArr[0]=" + test.obArr[0]);
// won't run: "NullPointerException", obArr[0] is null so can't use methods
//System.out.println("obArr[0].hashCode()=" + test.obArr[0].hashCode());
for(int ndx = 0; ndx < test.obArr.length; ndx++) {
test.obArr[ndx] = new Object();
}
// all good now: obArr *and* obArr[0] are initialised
System.out.println("obArr[0].hashCode()=" + test.obArr[0].hashCode());
}
}
I haven't read the rest of your post yet. Maybe this answers it.
Re: NullPointerException Error in Code that Prints Array Elements
Quote:
It seems that I confused declaring and initializing the array with initializing the array elements.
Yes, exactly.
Quote:
But if "alpha[i] = new ArrayClass1(0,0);" initializes each element, then why didn't I get an error when I ran...
Where would you expect the error? The point is you *did* initialise both alpha and each of the alpha[i] elements. Everything initialised == no NullPointerException.
Oddly, you did assign values to alpha[i] twice. We call the first assignment "initialisation", but that's just terminology. You are free to assign as many things as you like to alpha[i] - the old values are simply discarded. (which is why it is odd to make two such assignments).
Re: NullPointerException Error in Code that Prints Array Elements
Don't compilers fail to compile whenever you reinitialize the same declared pointer? Say:
Int x = 0;
Int x = 1;
Would give an error along the lines of "x is already defined. Is that because here "x" is being re-declared whereas
alpha[i] = new ArrayClass1(0,0);
alpha[i] = new ArrayClass1(1,1);
is analogous to an assignment after int x; :
x = 0;
x = 1;
Re: NullPointerException Error in Code that Prints Array Elements
Yes, you can't declare a variable twice.
But in the code you were asking about (#5) only one variable is declared (other than the loop variables): alpha. And it is declared just once.
The expression alpha[i] is not declared at all (expressions never are). And you are free to assign things to it as often as you like.