Try this code at Ideone.com:
Object o1 = new int[3];
Object[] o2 = new int[3]; //C.E
Why second statements gives compile time error while first one does not ?
Try this code at Ideone.com:
Object o1 = new int[3];
Object[] o2 = new int[3]; //C.E
Why second statements gives compile time error while first one does not ?
As the Comments explain:
Object
. This works because every array (of any type) is itself a subtype of the Object
class. See the Java specifications.int
values. The int
type is a primitive type, not an object-oriented type. You cannot assign a reference pointing to an array of primitives to a variable declared to hold an array of Object
objects. That is a type mismatch, as primitives and objects are not directly compatible.Understand that Java has two type systems, operating in parallel:
Work is underway to blur the distinction between these two type systems in future versions of Java. But that work is far from complete. So in the meantime you as a Java programmer must be fully cognizant of each realm. Auto-boxing helps to bridge the divide between those realms, but the divide is still very much present.
Let's make that second line work. Change the int
to Integer
. The Integer
class is a wrapper class. Each Integer
object holds an int
value. Now on the right side we instantiate an array of Integer
objects, where each element of that array is null
.
Object[] o2 = new Integer[3] ;
Arrays.toString( o2 ): [null, null, null]
We can assign something to each element.
Integer
object of course.int
primitive. The auto-boxing feature in Java automatically wraps that int
value inside of an Integer
object, then places a reference to that object within our array.o2[0] = new Integer( 7 ) ; // Assign an `Integer` object holding a `int` primitive within.
o2[2] = 42 ; // Assign a primitive value where auto-boxing automatically wraps the `int` value in an `Integer` object, then places a reference within the array.
See this code run at Ideone.com.
Arrays.toString( o2 ): [7, null, 42]