Search code examples
javaternary

simplified Ternary expression


I am trying to wrap my head around a small block of code int maximumVal = counter > 20 ? 20 : counter;

I know that ? is used for a true if expression and : is used for a false if expression

is this what that expression is saying in simplified if else terms?:

if (counter > 20) {
int maximumVal = 20;
else {
maximumVal = counter;
}

Solution

  • You can think of it as

    int maximumVal;
    if (counter > 20) {
        maximumVal = 20;
    } else { 
        maximumVal = counter;
    }
    

    maximumVal must be declared outside the if in order for it to be visible to code following this.

    The conditional expression has the advantage where you can know the variable being assigned from the expression is assigned some value, where in the if-else form you have to read both branches to verify the variable gets set.