0
0
Javaprogramming~5 mins

Ternary operator in Java - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the ternary operator in Java?
The ternary operator is a shortcut for an if-else statement. It uses the syntax: condition ? valueIfTrue : valueIfFalse;
Click to reveal answer
beginner
How does the ternary operator improve code?
It makes code shorter and easier to read when choosing between two values based on a condition.
Click to reveal answer
beginner
Example: What does this code print?<br>
int a = 5; int b = 10; System.out.println(a > b ? a : b);
It prints 10 because the condition (a > b) is false, so it chooses the value after the colon, which is b (10).
Click to reveal answer
intermediate
Can the ternary operator be nested in Java?
Yes, you can nest ternary operators inside each other, but it can make code harder to read.
Click to reveal answer
intermediate
What types of values can the ternary operator return?
It can return any type as long as both possible values are of compatible types (e.g., both int, or both String).
Click to reveal answer
What is the correct syntax of the ternary operator in Java?
Acondition : valueIfTrue ? valueIfFalse
Bif (condition) then valueIfTrue else valueIfFalse
Ccondition ? valueIfTrue : valueIfFalse
Dcondition ? valueIfFalse : valueIfTrue
What will this print?<br>
int x = 3; System.out.println(x > 5 ? "Yes" : "No");
AYes
B3
CError
DNo
Can the ternary operator replace all if-else statements?
ANo, only simple if-else that return values
BOnly for boolean variables
COnly for loops
DYes, always
What happens if you nest ternary operators too much?
ACode becomes easier to read
BCode becomes harder to read and maintain
CCode runs faster
DIt causes a syntax error
Which of these is a valid use of the ternary operator?
Aint max = (a > b) ? a : b;
Bint max = if (a > b) a else b;
Cint max = a > b ? a, b;
Dint max = a > b : a ? b;
Explain how the ternary operator works in Java and give a simple example.
Think of it as a short if-else that picks one of two values.
You got /3 concepts.
    What are the advantages and disadvantages of using the ternary operator?
    Consider when it helps and when it might confuse.
    You got /3 concepts.