Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning integer value to a Float wrapper in Java

Tags:

java

boxing

The following works

float a=3;

but the following doesn't:

Float a=3;

Shouldn't 3 be automatically promoted to float (as widening conversions don't require an explicit cast) and then Boxed to Float type ?

Is it because of a rule I read in Khalid Mogul's Java book ?

Widening conversions can't be followed by any boxing conversions

like image 687
Daud Avatar asked Apr 01 '26 02:04

Daud


1 Answers

The reason why Float a=3; won't work is because the compiler wraps the 3 into it's Integer object (in essence, the compiler does this: Float a = new Integer(3); and that's already a compiler error). Float object isn't and Integer object (even though they come from the same Number object).

The following works:

Number a = 3;

which in essence is translated by the compiler as:

Number a = new Integer(3);

or as Joachim Sauer mentioned,

Number a = Integer.valueOf(3);

Hope this helps.

like image 50
Buhake Sindi Avatar answered Apr 02 '26 22:04

Buhake Sindi