The ternary operator in Java is a shorthand way of writing an if-else
statement in a single line. The syntax of the ternary operator in Java is as follows:
variable = (condition) ? expression1 : expression2;
Here’s how the ternary operator works:
true
, expression1
is evaluated and its value is assigned to the variable.false
, expression2
is evaluated and its value is assigned to the variable.Here’s an example that uses the ternary operator to assign a value to a variable based on a condition:
int a = 5;
int b = 7;
int max = (a > b) ? a : b;
In this example, the max
variable is assigned the value of a
if a
is greater than b
, and the value of b
if b
is greater than or equal to a
. The result of the ternary operator is then assigned to the max
variable.
The ternary operator can be nested, allowing for more complex expressions. Here’s an example of nested ternary operators:
int a = 5;
int b = 7;
int c = 3;
int max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
In this example, the max
variable is assigned the value of the largest of the three variables a
, b
, and c
. The nested ternary operators check which of the three variables is the largest and return that value, which is then assigned to the max
variable.
In this code example, if the age
variable is greater than 18, the message “you can drive” is assigned to the message
variable, otherwise the message “you are not allowed to drive a car” is assigned to message
. Finally, the message is printed to the console.
public class TernaryOperatorExample {
public static void main(String[] args) {
int age = 20;
String message;
message = age > 18 ? "you can drive" : "you are not allowed to drive a car";
System.out.print(message);
}
}
you can drive