Conditional Operator

The most complicated conditional statement is one that you might not find reasons to use in your programs: the ternary operator. If you find it too confusing to implement in your own programs, take heart: You can use other conditionals to accomplish the same thing. You can use the ternary operator when you want to assign a value or display a value based on a conditional test. For example, in a video game, you might need to set the numberOfEnemies variable based on whether the skillLevel variable is greater than 5. One way to do this is with an if-else statement:

if (skillLevel > 5)
 numberOfEnemies = 10;
 numberOfEnemies = 5;

A shorter way to do this is to use the ternary operator, which is ?. A ternary operator has five parts:

  • The condition to test, surrounded by parentheses, as in (skillLevel > 5)
  • A question mark (?)
  • The value to use if the condition is true
  • A colon (:)
  • The value to use if the condition is false

To use the ternary operator to set the value of numberOfEnemies based on skillLevel, you could use the following statement:

numberOfEnemies = (skillLevel > 5) ? 10 : 5;

You also can use the ternary operator to determine what information to display. Consider the example of a program that displays the text Mr. or Ms. depending on the value of the gender variable. You could do this action with another if-else statement:

if (gender.equals("male"))

A shorter method is to use the ternary operator to accomplish the same thing, as in the following:

System.out.print( (gender.equals("male")) ? "Mr." : "Ms." );

The ternary operator can be useful, but it's also the hardest conditional in Java to understand. As you learn Java, you won't encounter any situations where the ternary operator must be used instead of if and else statements.