Challenge - 5 Problems
Ternary Operator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of nested ternary operator
What is the output of the following Java code?
Java
public class Main { public static void main(String[] args) { int x = 5; String result = x > 0 ? (x < 10 ? "Small" : "Medium") : "Negative"; System.out.println(result); } }
Attempts:
2 left
💡 Hint
Check the conditions in the nested ternary carefully.
✗ Incorrect
The variable x is 5, which is greater than 0, so the first condition is true. Then it checks if x < 10, which is also true, so it returns "Small".
❓ Predict Output
intermediate2:00remaining
Ternary operator with boolean expressions
What will be printed by this Java program?
Java
public class Main { public static void main(String[] args) { boolean a = true; boolean b = false; String output = a ? (b ? "Both true" : "Only a true") : "a is false"; System.out.println(output); } }
Attempts:
2 left
💡 Hint
Evaluate the conditions step by step.
✗ Incorrect
Variable a is true, so the first condition is true. Then it checks b, which is false, so it returns "Only a true".
🔧 Debug
advanced2:00remaining
Identify the error in ternary usage
What error does this Java code produce?
Java
public class Main { public static void main(String[] args) { int x = 10; String result = x > 5 ? "Greater" : 5; System.out.println(result); } }
Attempts:
2 left
💡 Hint
Check the types of both expressions in the ternary operator.
✗ Incorrect
The ternary operator requires both expressions to be of compatible types. Here, one is String and the other is int, causing a type mismatch error.
🧠 Conceptual
advanced2:00remaining
Ternary operator evaluation order
Consider this Java code snippet:
int a = 3; int b = 4; int max = a > b ? a : b;Which statement is true about how the ternary operator works here?
Attempts:
2 left
💡 Hint
Think about short-circuit behavior in conditional expressions.
✗ Incorrect
The ternary operator evaluates only the expression that matches the condition's result, not both.
❓ Predict Output
expert2:00remaining
Complex ternary operator with method calls
What is the output of this Java program?
Java
public class Main { static String check(int n) { return n % 2 == 0 ? "Even" : "Odd"; } public static void main(String[] args) { int x = 7; String result = x > 5 ? check(x) : "Too small"; System.out.println(result); } }
Attempts:
2 left
💡 Hint
Evaluate the condition and then the method call.
✗ Incorrect
x is 7, which is greater than 5, so check(7) is called. 7 % 2 is 1, so it returns "Odd".