Strange things in java

Found some strange things in java.

code:

System.out.println(System.getProperty("java.version")); System.out.println((true) ? (int)2.5 : 3.5); System.out.println((true) ? (int)2.5 : 3); System.out.println((true) ? (int)2.5 + "" : 3.5); 

Result:

  1.8.0_40
 2.0
 2
 2

What is it? Why is an integer value returned only if the value for false is not double or the string value added to the value for true? Why does (int) work in the second rounding loop, but a double value is returned? This is mistake?

+5
source share
3 answers

https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25 defines all these rules that behave exactly with your observed output.

For the entire three-dimensional expression, there is only one type, and that is returned, and that is called System.out.println . If you look at the table in this specification, you will see that the types in the lines you specify are double , int and Object respectively.

+4
source

In the scheme:

 (true) ? (int)2.5 : 3.5 int double \ / double 

The literal double 2.5 is flushed to int 2, and then returns to double 2.0, because it is a conditional expression type.

+3
source

The ternary operator has a constant return type.

From JLS, section 15.25 :

Otherwise, binary numeric promotion (ยง5.6.2) is used for operand types, and the conditional expression type is the advanced type of the second and third operands.

Does that mean in (true) ? (int)2.5 : 3.5 (true) ? (int)2.5 : 3.5 , 2.5 converts to int (rounds down) and then expands to double .

In (true) ? (int)2.5 : 3 (true) ? (int)2.5 : 3 , int does not need to be expanded to double , because the other side is also int .

Finally, in (true) ? (int)2.5 + "" : 3.5); (true) ? (int)2.5 + "" : 3.5); it cannot be expanded since it is already converted to String .

+2
source

Source: https://habr.com/ru/post/1257987/


All Articles