BCA / B.Tech 14 min read

Conditional Operator

The Conditional Operator in Java:

The conditional operator in Java, also known as the ternary operator, is a concise way to write an `if-else` statement. It is the only operator in Java that takes three operands. It is used to decide which value should be assigned to a variable based on a boolean condition.

Syntax:

variable = (condition) ? value_if_true : value_if_false;

How it works:
  • The `condition` is evaluated first.
  • If the `condition` evaluates to `true`, the `value_if_true` is returned and assigned to the variable.
  • If the `condition` evaluates to `false`, the `value_if_false` is returned and assigned to the variable.

Example:

int score = 75;
String result = (score >= 50) ? "Pass" : "Fail";
// result will be "Pass"
        

While it makes code more compact, it should be used for simple conditions to maintain readability. Complex or nested ternary operations can make code difficult to understand.