In if
-statements, we change the flow of control in programs. With ternary statements, we assign a variable based on a conditional expression.
While if
-statements can become complex, ternary statements tend to be simpler. We use them to assign variables based on a logical expression.
This program uses the ternary operator in two places. After the condition, we type the question mark, and then we separate the true and false conditions with a ":" char
.
public class Program { public static void main(String[] args) { int value1 = 100; // If value1 equals 100, set value2 to 4. // ... Otherwise set value2 to 1. int value2 = value1 == 100 ? 4 : 1; System.out.println(value2); // If value1 is greater than or equal to 200, set value3 to a string literal. // ... Otherwise, assign a different string literal. String value3 = value1 >= 200 ? "greater" : "lesser"; System.out.println(value3); } }4 lesser
We can use a ternary expression in the result statement of a method. This sometimes gives us elegant code. It is also shorter to type.
getStringMultiplier
method returns 1000 if the argument string
ends in K, and 1 otherwise.public class Program { public static int getStringMultiplier(String test) { // Return 1000 if the string ends in K, and 1 if it does not. return test.endsWith("K") ? 1000 : 1; } public static void main(String[] args) { System.out.println(getStringMultiplier("125K")); System.out.println(getStringMultiplier("?")); System.out.println(getStringMultiplier("10K")); } }1000 1 1000
Both results of a ternary operation must be of the same type, or must be able to convert to that type. Here an error results because 0 is not a String
.
public class Program { public static void main(String[] args) { int v = 1000; // Both possible results from a ternary must have valid types. String result = v == 1000 ? "one thousand" : 0; } }Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from int to String at program.Program.main(Program.java:8)
For a compiler, the obvious approach to a ternary statement is to use the same code as an if
-statement. Usually ternary statements have nearly the same performance as ifs.
To some developers, ternary statements make it harder to read code. If
-statements are more expected, and may be easier to scan. I tend to avoid ternaries.