## daudiam -8 Junior Poster

The following assignment would work

``float a=3;``

But the following won'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

mvmalderen commented: Double post of: http://stackoverflow.com/questions/3675365/assigning-integer-value-to-a-float-wrapper-in-java -2

## JamesCherrill 4,219

Yes, it's a cast/box too many in one step.

``````Float a = 3f;
Float a  = (float) 3;
Float a = new Float(3);``````

all work

ps Khalid Mogul may be a great guy, but I would always prefer to find an authoritative source in the official Sum/Oracle documentation

## daudiam -8

But then, this should not work too

``Short a=34;``

But it does. There are as many cast/box conversions here.

## JamesCherrill 4,219

short is an integer type, as is 34, which I guess makes the difference

## mvmalderen 2,072

But then, this should not work too

``Short a=34;``

But it does. There are as many cast/box conversions here.

From the Java Language Specification (3rd Edition):

5.2 Assignment Conversion

...

A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is :

• Byte and the value of the constant expression is representable in the type byte.
• Short and the value of the constant expression is representable in the type short.
• Character and the value of the constant expression is representable in the type char.

Therefore it is legal to write things such as:

``````public class TestBoxing
{
public static void main(String[] args)
{
Short s = 1 * 2 * 3 * 4 * 5 * 6; // assign 720
System.out.println(s);
}
}``````

However, the following isn't legal:

``````public class TestBoxing2
{
public static void main(String[] args)
{
Short s = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8; // try to assign 40320
System.out.println(s);
}
}``````

If you'd try to compile the TestBoxing2 class, then you'd get a compiler error, because the value of the constant expression `1 * 2 * 3 * 4 * 5 * 6 * 7 * 8` (that is: 40320) cannot be represented in the type short. For your convenience I included the compiler error as well:

TestBoxing2.java:5: incompatible types
found : int
required: java.lang.Short
Short s = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8;
^
1 error

I hope this clears your doubt.

## daudiam -8

Thanks.
In section 5.2 of the link you gave, they have mentioned 5 ways in which assignments are permissible. None of them permit a widening operation followed by boxing. That explains why Float a=3 won't work.

Thanks again.