The ternary operator in Java is a shorthand for an if-else statement and is used to evaluate a boolean expression. It has the following syntax:
java
condition ? expression1 : expression2;
- If condition is true, expression1 is executed; otherwise, expression2 is executed.
- It returns a value based on the result of the condition and is often used for assigning values in a compact manner.
Example:
java
int x = 10, y = 20;
int max = (x > y) ? x : y;Â // max will be assigned the value of y (20) because x is not greater than y.
The ternary operator improves readability and reduces code length, especially in simple conditional assignments. However, it should be used carefully for clarity when dealing with complex expressions.