1

I'm confused by the following Java code, in which I try to use two methods to cast an Object to an int:

Object o = 1;
System.out.println((int) o);
Class <?> t = int.class;
System.out.println(t.cast(o));

The second line casts the Object to an int traditionally, and succeeds. The fourth, however, which I would expect to be functionally equivalent, throws

Exception in thread "main" java.lang.ClassCastException: Cannot cast java.lang.Integer to int

What's the functional difference between the second line and the fourth? Why would one fail while the other succeeds?

Luke Taylor
  • 8,631
  • 8
  • 54
  • 92
  • 1
    I think it is because the cast method (4th line) must return an Object (after type erasure) so it does not allow casting from primitives. Not that well documented... – user85421 Jan 20 '18 at 21:15
  • same reason why you get compillation errof for ->Integer i = 9; boolean isInstance = i instanceof int;// You get compilation error – surya Jan 20 '18 at 21:20
  • 2
    You are confusing autoboxing with casting. It is the *compiler* that applies autoboxing, not the JVM, so when you call `cast(o)` in line, that's exactly what the JVM will try to do, but the operation requires unboxing, so it fails. – Andreas Jan 20 '18 at 21:20

1 Answers1

-1
Object o = 1;
System.out.println((int) o);

With these two lines of code, you have encountered boxing and unboxing. The first line implicitly converts the int value 1 to an Integer object. o is assigned a reference to this object. This implicit conversion is called boxing.

On the second line, the Integer object referred to by o is unboxed to an int which can be cast to int.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268