Java letter offset behavior

In the SCJP leadership book by Katie Sierra, in the assignment chapter, we learn that we can declare something like this byte b = 7;. Behind the scene code byte b = (byte) 7;. This is because in java the number 7 is considered the literal value of int, so it needs to be converted to int.

Now the situation is different. A double can include every byte contained within the float value, since it is a larger data type. So, we can say that float f = 10.543;As 10.543 is a rather small value and should fit into the float. Also, the literal value for such a number is considered Double, so the compiler must implicitly use it for float. But this is not so, the compiler stops us. We must add For Fafter this value.

Why do these two conflicting behaviors exist for literal assignment of values? In short, if byte b = 7possible. Why is float f = 10.543it impossible?

+5
source share
5 answers

You can read JLS 5.2 Conignment Conversion

Narrowing the compile time constant means that the code, for example:

 byte theAnswer = 42;

allowed. Without narrowing down, the fact that the integer literal 42 is of type int will mean that it needs to be dropped to a byte:

byte theAnswer = (byte)42;  // cast is permitted but not required

If the type of the expression cannot be converted to the type of the variable by conversion allowed in the destination context, then a compile-time error occurs.

If the type of the variable is float or double, then the conversion of the set of values ​​(§5.1.13) applies to the value v

JLS # 3.10.2. Floating point literals

float, ASCII F f; , ASCII D d

5.1.2.

double float IEEE 754 (§4.2.4). , , . NaN float NaN, .

, .

+5

:

  • "" int ,
  • double float, , .
+1

double float , java , , , . .

, 10 (, ). , , .

, , : , , . , .

+1

" b = () 7".

It is not right. See JLS # 5.2 , which is mentioned in several other answers. It says: "Narrowing down a 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."

Nothing exists about type casting.

0
source

All Articles