Introduction to Conditional Operators
An alternative to using if and else keywords in a conditional statement is to use the conditional operator, sometimes called the ternary operator (ternary means three; the conditional operator has three parts).
The conditional operator is an expression, meaning that it returns a value (unlike the more general if, which can only result in a statement or block being executed). The conditional operator is most useful for very short or simple conditionals.
Syntax
test ? trueresult : falseresult;
test is a boolean expression that returns true or false, just like the test in the if statement. If the test is true, the conditional operator returns the value of trueresult; if it's false, it returns the value of falseresult.
Example
1. /**
2. * @(#)ConditionalOperatorDemo.java
3. *
4. *
5. * @author
6. * @version 1.00 2009/11/4
7. */
8.
9. public class ConditionalOperatorDemo {
10.
11. /**
12. * Creates a new instance of ConditionalOperatorDemo.
13. */
14. public ConditionalOperatorDemo() {
15. }
16.
17. /**
18. * @param args the command line arguments
19. */
20. public static void main(String[] args) {
21. // TODO code application logic here
22.
23. int a = 100;
24. int b = 50;
25.
26. String result = a > b ? "a is greater than b" : "a is not greater than b";
27.
28. System.out.println(result);
29. }
30. }
Output
a is greater than b
