Search code examples
javaarraysunboxing

Are arrays being transformed when using an enhanced for loop?


Does Java 5 or higher apply some of form of "boxing" to arrays? This question came to mind as the following code goes through an array as if it's an Iterable.

for( String : args ){
// Do stuff
}

Solution

  • No, arrays are always reference types. There's no need for boxing or unboxing, unless it's on the access for each element. For example:

    int[] x = new int[10]; // The value of x is a reference
    
    int y = x[0]; // No boxing
    Integer z = x[1]; // Boxing conversion from x[1] (which is an int) to Integer
    

    Also note that although the enhanced for loop is available for both arrays and iterables, it's compiled differently for each.

    See section 14.14.2 of the JLS for the two different translations of the enhanced for loop.