How does array of primitive types work in Java?

Java says that "any instance other than a primitive type is an object."

I am trying to figure this point using the code below (line 4 for specific).

public class dummy{
    public static void main(String[] args){
        int[] i = new int[2];
        i[0] = new Integer(3); //line 4
        i[1] = 3;
        System.out.println(int[].class);
        System.out.println(i[0]);
    }
}

      

After launch

int[] i = new int[4];

      

Java creates an object of [0,0]

type class [I

. The two members in this object [0,0]

are primitive data types (but not a reference type).

My questions:

  • Why does Java allow an object to be assigned to a primitive type member on the next line?

    i[0] = new Integer(3); // object of type 'class Integer' getting assigned to i[0]
    
          

    How do I understand this? The counter i[0]

    displays the value 3

    , but not the address of the object.

  • What's I

    in class [I

    ? I mean that for class C{};

    C[].class

    gives class [LC

    where [

    means "array" and LC

    means "instance of class C"

+3


source to share


5 answers


i[0] = new Integer(3);

      

This includes what is known as auto-unboxing . In Dark Age of Java (pre-1.5), we had to explicitly inject primitives into the box and unbox. But fortunately, the language designers took pity on our poor fingers and added syntactic sugar. They now allow you to freely convert between primitives and their wrapper types. Java secretly converts the above code to this:

i[0] = new Integer(3).intValue();

      

It's auto-unpacking. Likewise, it will be useful to you without your request. If you write:

Integer i = 5;

      



Java will actually do:

Integer i = Integer.valueOf(5);

      


What am I in class [I

?

This is I

for int

.

+10


source


  • Java expects you to assign int

    to an array element, but you get throughInteger

    , so automatically unboxed as int

    . By the way, when you create an array, Integer[]

    you also get the same result when executed System.out.println

    , because it Integer.toString

    just creates a string of that value, not an "object address".
  • [

    means one dimensional array. I

    means int

    .


+3


source


java/lang/Integer.intValue:()I

called when you do i[0] = new Integer(3); //line 4

ie, the compiler implicitly gets the int Integer value and adds it to the array.

+1


source


For your first question, Java autoboxes primitive types with their wrapper classes (for example, int ends up in an Integer class) and also unboxes wrappers for primitive types.

Here is the documentation: http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

+1


source


the compiler does the conversion between primitives and their corresponding objects as a convenience to the programmer.

+1


source







All Articles