Java: boolean in println (boolean ? “print true”:”print false”) [duplicate]

? : is the conditional operator. (It’s not just the : part – the whole of the method argument is one usage of the conditional operator in your example.)

It’s often called the ternary operator, but that’s just an aspect of its nature – having three operands – rather than its name. If another ternary operator is ever introduced into Java, the term will become ambiguous. It’s called the conditional operator because it has a condition (the first operand) which then determines which of the other two operands is evaluated.

The first operand is evaluated, and then either the second or the third operand is evaluated based on whether the first operand is true or false… and that ends up as the result of the operator.

So something like this:

int x = condition() ? result1() : result2();

is roughly equivalent to:

int x;
if (condition()) {
    x = result1();
} else {
    x = result2();
}  

It’s important that it doesn’t evaluate the other operand. So for example, this is fine:

String text = getSomeStringReferenceWhichMightBeNull();
int usefulCharacters = text == null ? 0 : text.length();

Leave a Comment