Question

Let's say that I have the following:

int a = 2;
Number b = (Number) a;

System.out.println(b); // Prints 2

http://java.sun.com/docs/books/jls/first_edition/html/15.doc.html#238146 says that a primitive value may not be cast to a reference type. Does Java know to create an Integer from the primitive int and then cast to the superclass? How exactly does Java handle this behind the scenes? Thanks!

Was it helpful?

Solution

The process is called autoboxing. In short, the compiler sees that a wrapper (Integer) rather than a primitive (int) is needed and automatically adds the conversion. And actually your cast to Number is not necessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top