The conditional (ternary) operator is often used as a short form of an if-else statement. This is simply a conditional assignment of a value to a variable. if-then-else, on the other hand, is a flow control.
condition ? expression1 : expression2;
Line | Description |
---|---|
3 | Initializes the variable age of type integer with the value 20 |
4 | Creates a new variable message of type String |
6 | If age is higher than 18 the string behind the question mark will be displayed. In this case “you can drive”. Otherwise, the string after the double dot is output “you are not allowed to drive a car” |
8 | Outputs the content of the variable message |
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