Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange things in java [duplicate]

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 integer value returns only if value for false is not a double or if string value added to value for true? Why in second line rounding works by (int) cast, but double value returns yet? Is it a bug?

like image 552
Jozek Avatar asked Oct 10 '16 20:10

Jozek


2 Answers

https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25 specifies all these rules, which are behaving exactly consistently with your observed output.

There is only one type for the entire ternary expression, and that's what gets returned and that's what System.out.println is being called on. If you look it up in the table in that specification, you'll find the types in the lines you've mentioned are going to be double, int, and Object respectively.

like image 164
Louis Wasserman Avatar answered Sep 28 '22 06:09

Louis Wasserman


In a schematic:

(true) ? (int)2.5 : 3.5

         int        double
           \        /
             double

The double literal 2.5 is downsampled to int 2, then promoted back to double 2.0 because that's the type of the conditional expression.

like image 28
Marko Topolnik Avatar answered Sep 28 '22 06:09

Marko Topolnik