The Conditional Operator
The most complicated conditional statement in Java is the ternary operator ?.
You can use the ternary operator when you want to assign a value or display a value based on a condition. For example, consider a video game that sets the numberOfEnemies variable based on whether the skillLevel variable is greater than 5. One way you can do this is an if-else statement:
if (skillLevel > 5) { numberOfEnemies = 10;} else { numberOfEnemies = 5;}
A shorter way to do this is to use the ternary operator. A ternary expression 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access