1

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?

bcsb1001
  • 2,834
  • 3
  • 24
  • 35
Necromancer
  • 869
  • 2
  • 9
  • 25

1 Answers1

7

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.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 6
    Actually, autoboxing doesn't replace `1` by `new Integer(1)` but by `Integer.valueOf(1)`, which may return a cached `Integer` object. – Jesper Jun 12 '16 at 18:58