0
0
Javaprogramming~20 mins

Ternary operator in Java - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ternary Operator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
    }
}
ACompilation error
BMedium
CNegative
DSmall
Attempts:
2 left
💡 Hint
Check the conditions in the nested ternary carefully.
Predict Output
intermediate
2: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);
    }
}
AOnly a true
BBoth true
Ca is false
DCompilation error
Attempts:
2 left
💡 Hint
Evaluate the conditions step by step.
🔧 Debug
advanced
2: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);
    }
}
ANo error, prints "Greater"
BType mismatch: cannot convert from int to String
CNo error, prints "5"
DSyntax error: missing colon
Attempts:
2 left
💡 Hint
Check the types of both expressions in the ternary operator.
🧠 Conceptual
advanced
2: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?
ABoth a and b are evaluated before the ternary operator returns a value
BThe ternary operator always evaluates both expressions regardless of the condition
COnly the expression corresponding to the true condition is evaluated
DThe ternary operator evaluates neither expression and returns the condition's boolean value
Attempts:
2 left
💡 Hint
Think about short-circuit behavior in conditional expressions.
Predict Output
expert
2: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);
    }
}
AOdd
BToo small
CCompilation error
DEven
Attempts:
2 left
💡 Hint
Evaluate the condition and then the method call.