Search code examples
javaarraysindexingjlsunboxing

Why does unboxing occur in this case?


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?


Solution

  • 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.