Search code examples
javaalgorithmternary

Converting if else statement to java statement using ternary operator


Is it possible to convert the below java code using ternary operator:

if (x > 0) {
    a = 100;
    b = 100;
} else {
    a = 1;
    b = 1;
}

Solution

  • You can write:

    a = b = x > 0 ? 100 : 1;
    

    but only because you assign the same value to a and b.

    In the general case, you'd need a separate ternary conditional operator for each variable you wish to assign to:

    a = x > 0 ? 100 : 1;
    b = x > 0 ? 100 : 1;