javacodex.com
Java Examples
Java Examples
memu home questions

Ternary Example

Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement. This operator is also known as the ternary operator because it uses three operands. In the following example:

result = condition ? value1 : value2;

If condition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result.

Source: (Ternary.java)

public class Ternary {
   public static void main(String[] args) {
 
      int a = 1;
      int b = 2;
 
      System.out.println(true ? "this" : "that");
      System.out.println(false ? a : b);
      System.out.println( (a > b)  ? "this" : "that");
      System.out.println( (b > a)  ? (false ? "1st" : "2nd") : "3rd");
 
   }
}
 

Output:

# java Ternary 
this
2
that
2nd

Contact: javacodex@yahoo.com