Reputation: 45
According to the Java Tutorial, the
Converting an object of a wrapper type (Integer) to its corresponding primitive (int) value is called unboxing. The Java compiler applies unboxing when an object of a wrapper class is:
- Passed as a parameter to a method that expects a value of the corresponding primitive type.
- Assigned to a variable of the corresponding primitive type.
Why does unboxing occur in this case?
char l = 0;
int arr[] = new int[]{1,2,3};
System.out.println(arr[new Integer(1)]);
Where in this scenario does either of those things happen? Is there an underlying method that governs element access in an array? Or does [] imply some sort of variable?
Upvotes: 2
Views: 112
Reputation: 20195
The JLS 15, §15.10.3 is pretty clear on this one:
...
The index expression undergoes unary numeric promotion (§5.6). The promoted type must be
int
, or a compile-time error occurs....
Similar paragraphs can be found in older JLSes, e.g. JLS 8, §15.10.3.
Upvotes: 4
Reputation: 70939
The unboxing occurs on line three
System.out.println(arr[new Integer(1)]);
arr
is an array as declared on line two
int arr[] = int[]{1, 2, 3};
Note that the type of arr
is an "array of int". All arrays accept an int
for the index being accessed. In line 3, you are passing an Integer
, these two types are not the same. One is a primitive type, while the other is an Object
type. Since there exists a "unboxing conversion" to change the Integer
to an int
, unboxing occurs just before the value is passed as an index into the int
array.
Upvotes: 1
Reputation: 2865
In (arr[new Integer(1)]
the wrapper Integer gets converted to primitive type, because it is used as an array index.
Upvotes: 0