Reputation: 75
My code is
public class Test {
public class Struct {
public int id;
}
Struct s[] = new Struct[10];
public Test() {
s[0].id = 0;
}
public static void main(String[] args) {
Test t = new Test();
}
}
It gives an error in line s[0].id = 0; However s is initialized, so I can't understand why it is giving an error.
Upvotes: 2
Views: 138
Reputation: 10241
Lets see how it works,
when you are creating Test object inside main method, lets see what happens,
you're Test() constructor will be called, inside which you are doing
"s[0].id = 0"
But Hey wait.. isnt you're Struct array s[] still having nulls?
PS: please note when you create an object array, it is initialized with null values. Like when you create an int array int[] all elements of the array are initialized with default value (i.e. Zero's), Similary when you create an object[], all the elements are initialized with null value by default.
so basically you are setting id property of s[0] which is null and hence a NullPointerException is thrown by JRE
Upvotes: 0
Reputation: 111219
You have initialized s
, but you also have to initialize s[0]
.
s[0] = new Struct();
s[0].id = 0;
When an array is created all of its elements are set to the default value of the element type. For reference types (like here) the default value is null
, so s[0]
stays null
until something is assigned to it.
The exception to this rule is of course when the creation of multi-dimensional arrays: when you write new type[N][M]
the intermediate N arrays of length M are created for you, although their contents, too, will be set to the default value of the element type.
Upvotes: 8
Reputation: 3802
You initialized the array but not references that are in the Array so you have to initialize them before using.
s[0] = new Struct();
there is nothing that is pointed by s[0] s you have to first give it a Thing(Object) that it gonna refer. so for using any reference in the array you have too initialize whole array:
for(i=0;i<=9;i++){
s[i] = new Struct();
}
Upvotes: 1
Reputation: 10810
You're creating and initializing a new array Object, but that array object has to have its own objects also initialized, as they are null by default.
s[0] = new Struct();
s[0].id = 0;
Will fix your problem.
Upvotes: 3