Search code examples
javaprimitiveautoboxing

Why can Object[] store primitives?


Object[] can store any object from any class because every class in Java extends java.lang.Object.

I don't think primitives extend from Object, so why can we store them like the following?

Object[] obj_arr = {1, 2, 1.2, 'a', false, new MyClass(), null};

The question is why can primitives be stored in an Object array and did Auto boxing happen or not in the above code?


Solution

  • The primitive types get auto-boxed into their respective wrapper types, so for instance: 1 becomes Integer.valueOf(1) and that's an instance of the Integer class which extends from Object, hence it can be stored into an Object[]. The same thing happens for the other primitives - instances of Double, Character and Boolean are used in place of the corresponding primitive values.