Skip to main content

Operators

Ternary Operator

In Java, the ternary operator, also known as the conditional operator, is a special operator that takes three operands: a condition followed by a question mark (?), an expression to evaluate if the condition is true, followed by a colon (:), and an expression to evaluate if the condition is false.

Syntax

condition ? expression1 : expression2

Here's how it works:

  • If the condition is true, the expression before the colon (:) is evaluated and becomes the result of the operation.
  • If the condition is false, the expression after the colon (:) is evaluated and becomes the result of the operation.

Example

int x = 5;
int y = (x > 0) ? 10 : 20; // If x is greater than 0, y will be assigned 10, otherwise 20.
System.out.println(y); // Output will be 10

The ternary operator is often used as a shorthand for simple if-else statements when the conditions are straightforward. It can make code more concise and readable, especially when used judiciously. However, excessive nesting or complex conditions within the ternary operator can reduce code readability, so it's important to use it wisely.