Ternary Operator ? : Tutorial

The conditional ternary operator is used to assign a value to a variable based on the result of a conditional test. The result of the conditional test must equal true or false. Surrounding the conditional test with parentheses is optional, however, doing so will improve readability. A complete ternary statement must have three punctuation marks: = ? :   To use the ternary operator in a statement, you will need to understand the following structure:
(variable) (=) (conditional test) (?) (test == true, assign this value to variable) (:) (test == false, assign this value to variable) (;)
String tooHotOut = "";
int temperature = 101;
tooHotOut = (temperature > 87) ? "I am staying inside today." : "I am going for a walk." ;
System.out.println(tooHotOut);
// I am staying inside today.

The same thing can be accomplished with a simple if statement.
String tooHotOut = "";
int temperature = 101;
if (temperature > 87) {
    tooHotOut = "I am staying inside today.";
} else {
    tooHotOUt = "I am going for a walk.";
}
System.out.println(tooHotOut);
// I am staying inside today.

Think of the ternary statement as short-hand for the if statement in certain circumstances.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md TernaryOperator
C:\Java>cd TernaryOperator
C:\Java\TernaryOperator>Notepad TernaryOperator.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class TernaryOperator {
    public static void main(String args[]) {
        String tooHotOut = "";
        int temperature = 101;
        tooHotOut = (temperature > 87) ? "I am staying inside today." : "I am going for a walk." ;
        System.out.println(tooHotOut); 

        // Acme Bank charges a 10% monthly service fee on balances below $100, let's calculate the fee (if any).
        double balance = 52.50D, fee = 0.0D;
        fee = (balance >= 100.00D) ? 0.0 : (balance * .1D) ; // parenthesis are optional, but highly recommended
        System.out.println("Your monthly service fee is: $" + fee);        
    }
}

Now switch back to the command prompt (CMD) and type in javac TernaryOperator.java and press Enter.
Now type in java TernaryOperator and press Enter.


C:\Java\TernaryOperator>javac TernaryOperator.java
C:\Java\TernaryOperator>java TernaryOperator
I am staying inside today
Your monthly service fee is: $5.25


Final thoughts

The ternary operator is basically shorthand for a common use of the if-else statement. The syntax may look a little strange at first, but you will definitely want to understand how the =, ?, and : all work together.


Tutorials