Java From Beginner To Advanced

0% completed

Previous
Next
Java Ternary Operator

The ternary operator in Java is a shorthand for the if-else statement. It allows you to write a simple conditional assignment in a single line. This operator is especially useful for concise code when you need to choose between two values based on a condition.

Syntax

variable = (condition) ? expression1 : expression2;
  • condition: A boolean expression that is evaluated.
  • expression1: The value assigned to the variable if the condition is true.
  • expression2: The value assigned to the variable if the condition is false.

When the condition is true, the operator returns the value of expression1; otherwise, it returns the value of expression2.

Example 1: Basic Conditional Assignment

Below is an example that uses the ternary operator to determine if a number is positive or negative.

Java
Java

. . . .

Explanation:

  • The condition (number >= 0) is evaluated.
  • Since number is -10, which is not greater than or equal to 0, the expression evaluates to "Negative".

Example 2: Choosing Between Two Values

Below is another example that uses the ternary operator to assign a discount message based on a purchase amount.

Java
Java

. . . .

Explanation:

  • The condition (purchaseAmount >= 100.0) checks if the purchase amount qualifies for a discount.
  • Since purchaseAmount is 150.0, the condition is true, and the message "Eligible for discount" is assigned to discountMessage.

The ternary operator provides a concise way to handle conditional logic in a single statement. By mastering its syntax and usage, you can simplify many common decision-making patterns in your code.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next