💎Common Ternary Operator Statements
Assign variable based on a condition:
int num = 10;
String result = (num > 5) ? "Greater than 5" : "Less than or equal to 5";Print message based on a condition:
int num = 10;
System.out.println(num % 2 == 0 ? "Even" : "Odd");Return value based on condition:
public int getNumberType(int num) {
return (num > 0) ? 1 : (num < 0) ? -1 : 0;
}Set variable to max of two values:
int a = 10;
int b = 20;
int max = (a > b) ? a : b;Conditionally instantiate object:
Last updated