Ternary Operator in Java
![]() |
Java - Ternary Operator |
The ternary operator in Java is a concise alternative to the if...else statement, allowing for cleaner and more readable code. It evaluates a condition and returns one of two expressions based on whether the condition is true or false.
Ternary Operator :
The ternary operator syntax:
condition ? expression1 : expression2;
- If the condition is true, expression1 is executed.
- If the condition is false, expression2 is executed.
Example:
A vending machine dispenses water when the correct token is inserted.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int token = input.nextInt();
String message = (token == 20) ? "Collect Water Bottle" : "Invalid Token";
System.out.println(message);
input.close();
}
}
Input 1:
20
Output 1:
Collect Water Bottle
Input 2:
34
Output 2:
Invalid Token
Nested Ternary Operator :
A ternary operator can be nested inside another to handle multiple conditions.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
int largest = (a >= b) ? ((a >= c) ? a : c) : ((b >= c) ? b : c);
System.out.println(largest + " is the largest among " + a + ", " + b + ", and " + c);
input.close();
}
}
Input 1:
67 78 76
Output 1:
78 is the largest among 67, 78, and 76
Input 2:
79 56 87
Output 2:
87 is the largest among 79, 56, and 87
Common Mistakes :
Incorrect :
Correct :
Replacing colon (:) with a semicolon (;) :
InCorrect :
Correct :
boolean isDivisibleByFive = (num % 5 == 0) ? true : false;Summary
The ternary operator in Java provides a concise way to replace if...else statements. It evaluates a condition and returns one of two expressions based on the result. Nested ternary operators allow for multiple conditions but should be used carefully to maintain readability.