Tracks
/
Java
Java
/
Syllabus
/
Ternary Operators
Te

Ternary Operators in Java

1 exercise

About Ternary Operators

The ternary operators can be thought of as being a compact version of if-else. It's usually used in (but not restricted to) return statements, it needs just one single line to make the decision, returning the left value if the expression is true and the right value if false.

A lot of simple if/else expressions can be simplified using ternary operators.

// this ternary statement
return 5 > 4 ? true : false;

// is equivalent to this if/else
if ( 5 > 4 ) {
    return true;
} else {
    return false;
}

So, how to decide between if-else and ternary? Well, ternary operators are used in simple scenarios, where you just need to return a value based on a condition and no extra computation is needed. Use an if-else for everthing else, like nested conditions, big expressions and when more than one line is needed to decide the return value.

While you can nest ternary operators, the code often becomes hard to read. In these cases, nested if's are preferred.

// hard to read
int value = expr1 ? expr2 && expr3 ? val1 : (val2 + val3) : expr4;

// easier to read
if (expr1){

    if (expr2 && expr3){

        return val1;
    }

    return val2 + val3;
}
return val4;


Ternary operators and if/else statements are a good example that you have different ways of achieving the same result when programming.

For more examples check out this and this.

Edit via GitHub The link opens in a new window or tab

Learn Ternary Operators