☕ Java
Beginner
What is the ternary operator in Java?
Answer
The ternary operator (? :) is a shorthand for a simple if-else expression that evaluates a condition and returns one of two values. Syntax: condition ? valueIfTrue : valueIfFalse. Example: String result = (age >= 18) ? "adult" : "minor";. It is an expression (it returns a value), unlike an if-else statement. Use it for simple, inline assignments where both branches are short. Avoid nesting ternary operators as this significantly reduces readability. Unlike if-else, both branches of the ternary operator must be expressions that produce a value.
Previous
What is the enhanced for loop (for-each) in Java?
Next
What is a default constructor in Java?