Java: Ternary operator (?:)

This entry is part 14 of 54 in the series Learn Java

In addition to the if and switch statements there is the ternary operator (?:).

This operator can replace a single if/else clause that assigns a value to a specific variable. The operator takes three expressions.

If the first one is evaluated to true then the second expression is returned, and if it is false, the third one is evaluated and returned.

package javaapplication13;

public class JavaApplication13 {

    public static void main(String[] args) {
        double x = 0.7;
        x = (x < 0.5) ? 0 : 1;

In the example above, we set x to be 0.7.  This will be bigger than 0.5 that we are comparing.  It also means that the expression (x < 0.5) will evaluate to  false causing 1 to be assigned to x.





Series Navigation<< Java: Switch statement
Java: Do while loop >>