tags:

views:

71

answers:

3

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

+3  A: 

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.

The Elite Gentleman
Actually auto-boxing is the equivalent of `Integer.valueOf(3)` and not of `new Integer(3)`. The difference is that the former does some caching of common values.
Joachim Sauer
Aaah, good to know....thanks Joachim Sauer.
The Elite Gentleman
Thanks. 3 is translated as Integer.valueOf(3) but What happens when we typecast 3 as (Float) 3 ? Is Float.valueOf(3) is called now ?
Daud
@Daud, nope....Autoboxing is done by the compiler, so in essence, the compiler will do this: `Float a = (Float)Integer.valueOf(3);` which is still an error.
The Elite Gentleman
Float sf =3.0f; works!!
Suresh S
+2  A: 
Float               Integer
  ^                    ^
  |                    |
  |                    |
  v                    v
float <----------->   int

There is a boxing/unboxing conversion betwen the primitive and the wrapper, and there is a promotion from one numeric primitive to another. But Java is not able to make this conversion twice (convert from int to Float, in your case).

barjak
A: 

Float a= 3.0f; will work.

Suresh S
Have you tested this?
The Elite Gentleman
yes it is working.
Suresh S
Nice. I asked this to encourage responders to first prove their answers before posting it. It gives a sense of relief to those reading your answer.
The Elite Gentleman