The 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;
else
    numberOfEnemies = 5;

A shorter way to do this is to use the ternary operator, which is ?. A ternary operator ...

Get SAMS Teach Yourself Programming with Java™ in 24 Hours, FOURTH EDITION now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.