C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: The two results in a ternary must have the same type. In the example 4 and 1 are both ints. A mismatch error will otherwise occur.
Condition: In a ternary, this can be any expression that evaluates to true or false. Even a method may be called.
Result: This is the value that was determined by the logical condition. We can return a ternary from a method.
Java program that uses ternary expressions
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);
}
}
Output
4
lesser
Here: The getStringMultiplier method returns 1000 if the argument string ends in K, and 1 otherwise.
Java program that returns ternary expression
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"));
}
}
Output
1000
1
1000
Java program that has type mismatch
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;
}
}
Output
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)