Casting an int primitive to a number

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 cannot be passed to a reference type. Does Java know to create an Integer from a primitive int and then pass it to a superclass? How exactly does Java handle this behind the scenes? Thank!

+3
source share
1 answer

This process is called autoboxing . In short, the compiler sees that it needs a wrapper ( Integer), not a primitive ( int), and automatically adds the conversion. And in fact, your tide is Numbernot needed.

+3
source

Source: https://habr.com/ru/post/1737409/


All Articles