1.when we assign double to float variable compiler gives us error
float f = 2753.2211;
possible loss of precision<
The second case is explicitly allowed by the JLS as a special case. In JLS 5.2, which deals with narrowing conversions, it says:
In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:
- A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
...
In other words, for the non-long integer-like values, you can implicitly narrow them iff the value you're narrowing is a constant that fits within the type you're specifying.
I'm guessing the same trick isn't applied to floats because floating point values are trickier than integer values. For instance, 0.1 can't be exactly expressed in a floating point, while 1.0 can. That means that double d = 0.1 isn't actually putting the value 0.1 into d -- just a value that's very close to 0.1. Given that, the "does it fit exactly" rule doesn't apply even to floating point literals, and the question of "does it fit exactly when we narrow" becomes trickier. Your options would basically be:
float f1 = 1.0 and double d1 = 1.0 both workdouble d2 = 0.1 works, but float f2 = 0.1 doesn't -- confusing!f char in the literal)Given these options, it seems that the designers of the JLS chose the least of three not-great options.
int is a 32-bit signed integer, byte is an 8-bit signed integer. A byte runs from -128 to 127, while a int runs from -2147483648 to 2147483647
Precision isn't lost, but do not cast a big int into a small byte or you will lose data.
Data isn't going to be lost in the second case.
A byte comprises the values of -128 and 127 inclusive, so as long as your int fits within that range, no loss of precision can occur.
Your second value is not a float-literal; by default, all floating point values in Java are double. You can explicitly make that a float by adding f to the end of it.
float f = 2573.2211f;