Assign int to byte vs double for float in java
1. When we assign double to float variable , the compiler gives us an error
float f = 2753.2211;
possible loss of precision Required for creation.
2. When assigning int to a byte variable, the compiler does not give us an error
byte b = 24;
OK
In the second case, data may also be lost. So why is casting clearly unnecessary.?
source to share
The second case is explicitly allowed by the JLS as a special case. In JLS 5.2 , which deals with narrowing conversions, it says:
Also, if the expression is a constant expression ( §15.28 ) of type byte, short, char, or int:
- A narrowing primitive conversion can be used if the type of the variable is byte, short, or char, and the value of the constant expression is represented in the type of the variable.
...
In other words, for values not equal to long
integers, you can implicitly narrow them if the value you are narrowing is a constant that matches the type you specify.
I guess the same trick does not apply to floats because floating point values are more complex than integer values. For example, 0.1 cannot be exactly floating point, but 1.0 can. This means it double d = 0.1
doesn't actually fit a value of 0.1 in d
- just a value that is very close to 0.1. Given that the “does exactly” rule does not even apply to floating point literals, and the question of “does it fit when we narrow down” becomes more complex. Your options will be basically:
- always allows it (which can lead to unexpected behavior if the value differs significantly from its literal representation)
- only allow if the value can be exactly inserted. This would look very inconsistent:
-
float f1 = 1.0
anddouble d1 = 1.0
work -
double d2 = 0.1
works butfloat f2 = 0.1
doesn't confuse!
-
- never let this (a little awkward because you have to type
f
char in a literal)
Given these parameters, it seems that the JLS designers chose the smallest of three not-so-large options.
source to share
In the second case, the data will not be lost.
The byte contains the values -128 and 127, inclusive, so as long as your int fits within this range, no loss of precision can occur.
The second value is not float
-literal ; by default all floating point values in Java are double
. You can explicitly do this float
by adding f
at the end.
float f = 2573.2211f;
source to share