Pergunta

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!");
Foi útil?

Solução

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.

Outras dicas

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.)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top