I came to know from this stackoverflow question that the code
test1[] t = new test1[2];
in the following program
class test1{
public int n;
void set(int n1){
n=n1;
}
}
class test{
public static void main(String arg[]){
test1[] t = new test1[2];
for(int i=0;i<2;i++)
t[i] = new test1();
t[0].set(12);
t[1].set(13);
for(int i=0;i<2;i++)
System.out.println(t[i].n);
}
}
is needed to initialize the array of objects of the class test1, and trying to access the objects without the code :
for(int i=0;i<2;i++)
t[i] = new test1();
throws the following error :
Exception in thread "main" java.lang.NullPointerException
at test.main(test1.java:12)
But I also tried to execute the following program:
class test{
public static void main(String args[]){
Integer[] n = new Integer[2];
n[0] = 9;
n[1] = 18;
for(int i=0;i<2;i++){
byte b = n[i].byteValue();
System.out.println(b);
}
}
seems to work without any error although I have not initialized the array of object of the Integer class, using the code :
for(int i=0;i<2;i++)
n[i] = new Integer();
How is it that, the array of objects of the Integer class and that of the class created by me differ in this case.
Is it that the objects for the class that I create requires initialization and the objects for the class Integer does not require initialization. Am I getting it right ? I just wanted to know how the classes that users create and classes that already exist differ.