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 value3
, but not the address of the object. -
What's
I
inclass [I
? I mean that forclass C{};
C[].class
givesclass [LC
where[
means "array" andLC
means "instance of class C"
source to share
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
.
source to share
- Java expects you to assign
int
to an array element, but you get throughInteger
, so automatically unboxed asint
. By the way, when you create an array,Integer[]
you also get the same result when executedSystem.out.println
, because itInteger.toString
just creates a string of that value, not an "object address". -
[
means one dimensional array.I
meansint
.
source to share
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
source to share