Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator

Tags:

java

ternary

Why the output of following code is 9.0 and not 9 ? If ternary operator is nothing but short form of if-else branch then why java compiler is promoting int to double ?

public class Ternary
  {
public static void main(String args[])
     {
    int a = 5;
    System.out.println("Value is - " + ((a < 5) ? 9.9 : 9));
     }
  }
like image 632
Praveen Kumar Avatar asked Feb 10 '13 09:02

Praveen Kumar


2 Answers

If ternary operator is nothing but short form of if-else branch then why java compiler is promoting int to double ?

A conditional expression has a single type, which both the second and third operands are converted to as necessary. The JLS gives the rules determining the expression type, which are slightly complicated due to auto-unboxing.

The conditional operator is sort of just shorthand for an if/else construct, but not the sort of shorthand I think you expected. So your code is equivalent to this:

double value;
if (a < 5) {
    value = 9.9;
} else {
    value = 9;
}
System.out.println("Value is - " + value);

It's not short for:

if (a < 5) {
    System.out.println("Value is - " + 9.9);
} else {
    System.out.println("Value is - " + 9);
}

For more details, see section 15.25 of the Java Language Specification.

like image 143
Jon Skeet Avatar answered Sep 19 '22 19:09

Jon Skeet


Because the type of the conditional operator(Yes, it's conditional operator and not ternary operator) in this case will be the promoted type of the 3rd operand, since 2nd and 3rd operand are not of same type.

This is clearly listed in JLS Secion - 15.25: -

Otherwise, if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases:

  • If one of the operands is of type byte or Byte and the other is of type short or Short, > then the type of the conditional expression is short.

  • If one of the operands is of type T where T is byte, short, or char, and the other operand is a constant expression (§15.28) of type int whose value is representable in type T, then the type of the conditional expression is T.

  • If one of the operands is of type T, where T is Byte, Short, or Character, and the other operand is a constant expression (§15.28) of type int whose value is representable in the type U which is the result of applying unboxing conversion to T, then the type of the conditional expression is U.

  • Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.

See the last point, that is of use here. So, in this case, as a rule of binary numeric promotion - See JLS Section 5.6.2: -

  • If either operand is of type double, the other is converted to double.
like image 33
Rohit Jain Avatar answered Sep 19 '22 19:09

Rohit Jain