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

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

But then, this should not work too

Short a=34;

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

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

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.

(Source: http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#184206)

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.