0% completed
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.
variable = (condition) ? expression1 : expression2;
When the condition is true, the operator returns the value of expression1; otherwise, it returns the value of expression2.
Below is an example that uses the ternary operator to determine if a number is positive or negative.
Explanation:
(number >= 0)
is evaluated.number
is -10, which is not greater than or equal to 0, the expression evaluates to "Negative"
.Below is another example that uses the ternary operator to assign a discount message based on a purchase amount.
Explanation:
(purchaseAmount >= 100.0)
checks if the purchase amount qualifies for a discount.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.
.....
.....
.....