Search code examples
javaarraysobjectforeachprimitive

Using for-each over an array of Objects - "Integer[] array" - Why Does "for(int i : array)" Work?


Why does using a primitive data type work in the second "for-each" loop when I am looping over an array of objects. Is there a casting back to the primitive equivalent of the Integer object occurring behind the scenes?

import java.util.Arrays;
import java.util.Collections;

public class CodeTestingClass 
{

    public static void main(String[] args) 
    {

     Integer[] array = {1,2,3,4,5};

     Collections.rotate(Arrays.asList(array), 1);

     System.out.println(Arrays.toString(array) + "\n" );

  for(Integer i : array)
  {

   System.out.print(i);

  }

  System.out.print("\n");

  for(int i : array)
  {

   System.out.print(i);

  }  

    }
}

Solution

  • It's auto-unboxing, that's all. There's no need for iterating over anything to demonstrate that:

    Integer x = 10;
    int y = x;
    

    From the Java Language Specification, section 5.1.8:

    Unboxing conversion converts values of reference type to corresponding values of primitive type.

    (There are a few more details there, but it's mostly just the list of conversions.)

    Section 5.2 calls out unboxing conversions as being available in the context of assignment conversions.