Type Conversion and compile-time constant

byte b=5; Integer i=(int)b;//b cast to int and int wrapped into Integer Integer k=(byte)b;//compilation error, cannot convert from byte to Integer Integer z=(byte)5;//compiles 

My question is: why does Integer z=(byte)5 compile, but Integer k=(byte)b does not? In this case, Integer z1 = (byte)5L and Integer z2 = (byte)5.3F also compiled. Is it because I'm trying to set a compile-time constant, and the cast does not affect it?

+4
source share
1 answer

As an appointment

Integer z=(byte)5

uses a literal value, it is immediately converted by the compiler to

 Integer z = Integer.valueOf(5); 

The compiler is not smart enough to refer to variables, as in the case of:

 Integer k= (byte)b; 
+6
source

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


All Articles