Ternary Operator in Java – How It Works and When to Use It - Quiz
Total: 1 questions
1. What is the ternary operator in Java, and how does it fundamentally differ from an if statement?
What is the ternary operator in Java, and how does it fundamentally differ from an if statement?
The ternary (conditional) operator is the only Java operator that takes three operands. Its form is condition ? valueA : valueB. The boolean condition is evaluated first; if it is true, the result is valueA, otherwise it is valueB. The key difference from if: the ternary operator is an expression that produces a value, so it can be used on the right-hand side of an assignment, passed as a method argument, or embedded inside another expression: int max = (a > b) ? a : b; or System.out.println(x > 0 ? "positive" : "negative");. An if, by contrast, is a control-flow statement: it returns nothing and cannot appear on the right-hand side of an assignment. Both branches of a ternary must yield values of compatible types.