0

Do primitive data type extend Object class? If no, then how this piece of code possible

long l=4567;
Object o=l;
System.out.println(o);

Why dont we get any compile error?

Abhilash28
  • 645
  • 1
  • 9
  • 15

2 Answers2

5

It is called auto-boxing and was introduced in Java 5.

The compiler will detect that you use a primitive where you should be using an object and inserts the following transformation automatically:

Object o = Long.valueOf(l);

It also works the other way around (auto-unboxing):

Long one = 1;

System.out.println(one + 2);
// gets compiled to
System.out.println(one.longValue() + 2);
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • ok..thanks I got that point now if suppose the code is like : Object o=new int[]{1,2,3}; int[] array=(int[]) o; -Why dont i get a classcast exception here while iterating through the array given array extends Object class? – Abhilash28 Mar 20 '15 at 10:56
0

The primitive long gets auto boxed into an Object of type Long. This is very useful as the primitives will automatically be converted to and from objects as needed. See here for some details - http://docs.oracle.com/javase/tutorial/java/data/numberclasses.html

And http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html