12

Let's say we have following if statement:

int a = 1;
int b = 2;

if(a < b) {
    System.out.println("A is less than B!");
}
else {
    System.out.println("A is greater or equal to B!");
}

I have been wondering that if ternary operator replaces if statement when if statement consists from one line of code in each sub-block (if and else blocks), then why above example is not possible to write like this with ternary operator?

(a < b) ? System.out.println("A is less than B!") : System.out.println("A is greater or equal to B!");
Amir
  • 1,031
  • 2
  • 19
  • 42
  • 4
    Because the JLS says so: _"It is a compile-time error for either the second or the third operand expression to be an invocation of a void method."_ – Alexis C. Mar 15 '14 at 10:40

2 Answers2

21

You can only use ? : for expressions, not statements. Try

System.out.println(a < b ? "A is less than B!" : "A is greater or equal to B!");

Note: this is also shorter/simpler.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • I know that works, but I was wondering why it could not be written like the ternary statement I wrote, but I know now the reason thanks :) – Amir Mar 15 '14 at 10:42
  • 1
    @AmirAl `? :` has to return something but println() is a `void` method. – Peter Lawrey Mar 15 '14 at 11:06
  • @PeterLawrey I have tried the ternary statement that I provided by giving values true when it is true and false when it is false and it didn't work. But it must be used in such that you have described in your answer. – Amir Mar 15 '14 at 11:23
  • @AmirAl it is an expression, not a statement so you must do something with the value such as assign it to a variable. – Peter Lawrey Mar 15 '14 at 17:09
7

Because it doesn't replace an if statement.

The ternary operator only works on expressions and not statements, itself being an expression.

Because it is an expression, it is evaluated rather than executed, and it has to return a (non-void) value. The type of that value is inferred from the types of the two optional expressions specified, and the rules are fairly complex, with some unexpected gotchas.

(So as a rule I only use ?: in the simplest situations to keep the code easy to read.)

biziclop
  • 48,926
  • 12
  • 77
  • 104