In the book of SCJP guide by Kathy Sierra, in the assignments chapter, we learn that we can declare something like this byte b = 7;
. Behind the scene the code is byte b = (byte) 7;
. This is so because in java, number 7 is considered a literal int value so has be to cast to int.
Now other situation. Double can include every byte contained within a float value as it is a bigger datatype. So can we say float f = 10.543;
As 10.543 is quite a small value and should fit within a float. Also literal value for such number is considered a Double so compiler should implicitly cast it to float. But it's not so, compiler stops us. We have to append an F
or f
after that value.
Why are these two conflicting behaviour there for literal value assignment? In short if byte b = 7
is possible. Why is float f = 10.543
not possible?