Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoboxing/widening occurs in Short a=3 but not in Float a=3;

I understand that the following code won't work

Float a=3

because its translated as Float a=Integer.valueOf(3). We'll have a Float reference on the LHS and an Integer object on the RHS, which is incompatible. But :

1.

     `Short a=3;`

This works, though here again, we'll have a Short reference on the LHS and an Integer object on the RHS.

2.

Float a=(Float) 3

If we hadn't typecasted 3, it would have been translated as Integer.valueOf(3). Now, will it be translated as Float.valueOf(3) ?

like image 329
Daud Avatar asked Oct 26 '22 07:10

Daud


1 Answers

If your question is "Why Float f = 3; does not compile, but Short s = 3; does?", then the answer is:

the Java compiler does some special work on integer constants to fit them with the left-hand side: it finds the most suitable type and uses it. So,

Short s = 3;

is compiled to

Short s = Short.valueOf(3);

Essentially, the same magic happens when you write

short s = 3;

But this is done only for Integers, and not for floating-point values.

like image 100
Andrey Breslav Avatar answered Oct 29 '22 23:10

Andrey Breslav