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) ?
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.
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 = 3actually becomesShort 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) 3will becomeFloat.valueOf(3)