0

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.

Community
  • 1
  • 1
kaartic
  • 523
  • 6
  • 24

1 Answers1

1

I have not initialized the array of object of the Integer class, using the code :

Yes, you did initialize the contents of the array n. Just like any reference array, an Integer[] is initialized with all nulls.

However, you did supply values:

n[0] = 9;
n[1] = 18;

You just didn't use new, because Java will autobox the int literals into Integer objects. You are storing the Integer objects corresponding to 9 and 18.

It doesn't matter if the objects are for classes that you create or not. It matters whether you are using a "wrapper" type for Java's primitive values. You can always have Java autobox primitive values into wrapper types, e.g. int to Integer.

The JLS, Section 5.1.7, lists all possible boxing conversions:

  • From type boolean to type Boolean

  • From type byte to type Byte

  • From type short to type Short

  • From type char to type Character

  • From type int to type Integer

  • From type long to type Long

  • From type float to type Float

  • From type double to type Double

  • From the null type to the null type

Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357