How numeric promotion in conditional assignment works in Java

Found some strange things in java.

the 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? This is mistake?

+6
source share
2 answers

This specification documents Java numerical advertising. Section 2 says that if any of the operands is of type double , then the result is of type double. This specification (which was added by @Januson) mentions that:

the type of conditional expression is the advanced type of the second AND third operand

Now, if we apply these two documents to our examples, we get the following:

 System.out.println(System.getProperty("java.version")); 

This is the version (release) of Java. This is a String .

 System.out.println((true) ? (int)2.5 : 3.5); 

In this case, the compiler looks at both parts of the conditional expression and decides the data type. (int) 2.5 is integer and 3.5 is a double . The result will be double . Thus, the integer part 2.5 (i.e. 2) will be passed to double .

 System.out.println((true) ? (int)2.5 : 3); 

In this case, the compiler looks at 2 integers, so the result is integer . The first case gives an integer , and the second case is also an integer , so the result will be in integer .

 System.out.println((true) ? (int)2.5 + "" : 3.5); 

In this case, the compiler looks at the first case and takes the integer part, which is 2. Now, since this number is added to the string, it becomes String . The result will also be a string. If you try to return 3.5, it will be returned as String , not double .

+4
source

Due to the way the ternary operator decides its return type. For more information check its specification .

The first expression returns double, because 2.5 is first converted to int 2, but since the third argument is double and int is converted to double, then the return type for the whole expression is double 2.0

The second return is symply int 2, because 2.5 for int is 2, and the return type is int.

The third converts 2.5 to 2 first, then to string "2", and the return type is String.

+1
source

All Articles