Here is this code:
int[] someArray = {0, 1, 2, 3};
//System.out.println(someArray[0].toString()); int cannot be dereferenced
// creating Object element with use of primitive element fails
//Object newObject = new Object(someArray[0]); constructor Object in class java.lang.Object cannot be applied to given types;
for(Object someObject : someArray)
{
// here int is casted to Object
System.out.println(someObject.toString()); // prints 0, 1, 2, 3
}
How does it happen that primitive type variable (element of array) cannot be explicitly casted to Object, however somehow in for loop this primitive element is casted to Object?
Since 1.5, the Java compiler will automatically box and unbox primitive types when the context calls for it. (That is, an
intgets wrapped in anIntegerobject and vice versa.) This happens when assigning between a primitive and an object variable. (Or casting a primitive to an object type.) So, for example, the following code is valid:The same goes for the implicit assignment
Object someInt = someArray[…]that the compiler emits for the foreach loop.The reason why
someArray[0].toString()doesn’t work is that you’re not assigningsomeArray[0]to an object typed variable or doing anything else that would tell the compiler to autobox – trying to call a method on a primitive simply isn’t recognized as one of the conditions when this should occur.