Back to Boolean Expressions and if Statements

Lesson PreviewLesson 8 of 8 in this unit

3.8 EXTRA: Ternary Operators

Part of Boolean Expressions and if Statements in AP® Computer Science A. Read the opening section, then create a free account for the full interactive lesson, practice, and progress tracking.

Note: These concepts aren't tested on the AP exam, but they're useful tools that can make your code cleaner and more efficient.

A ternary operator is like a compact if-else statement that fits on one line. Think of it as asking a yes/no question and getting one of two answers instantly. These are useful when trying to write neat code, allowing you to shrink an entire if-else statement into one line of code.

java
int age = 19;
String status = (age >= 18) ? "Adult": "Minor";
System.out.println(status);

Output

Adult

Continue the full lesson in Stellar

Create a free account to unlock the remaining sections, checkpoints, course practice, and progress tracking for AP® Computer Science A.