views:

80

answers:

4

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) ?

A: 

The short form is:

Float a=3.0f;

For Double type:

Double b=3.0;
Turbo J
+2  A: 

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.

Andrey Breslav
+1  A: 

If you try to initialize a variable with a value bigger than it can hold (regardless of the numerical form of the value), the compiler will give you an error message.

char c = 0xffff; // max char hex value
byte b = 0x7f; // max byte hex value
short s = 0x7fff; // max short hex value

Notice in the above code the maximum possible hexadecimal values for char, byte, and short. If you exceed these, the compiler will automatically make the value an int and tell you that you need a narrowing cast for the assignment. You’ll know you’ve stepped over the line.

So in your case Short s = 3 actually becomes Short s = new Short(3) and works. (valueOf methods are not used when Autoboxing that is why modern IDEs have options to flag these autoboxing as errors and we can replace them with the valueOf method for better mgmt of memory)

In the second case Float a=(Float) 3 will become Float.valueOf(3)

Faisal Feroz
Thanks. Very clear. Can u confirm then, that "Float a=3 will not work because Java does not allow widening following by autoboxing". Also, autoboxing doesn't just mean that the appropriate wrapper constructor is called for the LHS. If it was the case, Float a=3 would have worked. What must be happening is that before autoboxing, a narrowing conversion must be taking place to make the primitive type the same as the wrapper's primitive type and then only the autoboxing would take place. Am I right here ?
Daud
A: 

There is no way to specify short and byte constants, so the compiler allows you to translate int constants transparently. There are float constants in java so it doesn't support implied translation. If you want a float/Float I suggest you use a float constant.

Byte b = 3;
Short s = 3;
Integer i = 3;
Long l = 3L;
Float f = 3f;
Double d = 3d;
Peter Lawrey