Java ternary 操作员是唯一需要三个操作员的条件操作员。Java ternary 操作员是 if-then-else 语句的一个线程替代品,并且在 Java 编程中被广泛使用。
Java Ternary 操作员
The first operand in java ternary operator should be a boolean or a statement with boolean result. If the first operand is true then java ternary operator returns second operand else it returns third operand. Syntax of java ternary operator is:
result = testStatement ? value1 : value2;
If testStatement is true then value1 is assigned to result variable else value2 is assigned to result variable. Let's see java ternary operator example in a simple java program.
1package com.journaldev.util;
2
3public class TernaryOperator {
4
5 public static void main(String[] args) {
6
7 System.out.println(getMinValue(4,10));
8
9 System.out.println(getAbsoluteValue(-10));
10
11 System.out.println(invertBoolean(true));
12
13 String str = "Australia";
14 String data = str.contains("A") ? "Str contains 'A'" : "Str doesn't contains 'A'";
15 System.out.println(data);
16
17 int i = 10;
18 switch (i){
19 case 5:
20 System.out.println("i=5");
21 break;
22 case 10:
23 System.out.println("i=10");
24 break;
25 default:
26 System.out.println("i is not equal to 5 or 10");
27 }
28
29 System.out.println((i==5) ? "i=5":((i==10) ? "i=10":"i is not equal to 5 or 10"));
30 }
31
32 private static boolean invertBoolean(boolean b) {
33 return b ? false:true;
34 }
35
36 private static int getAbsoluteValue(int i) {
37 return i<0 ? -i:i;
38 }
39
40 private static int getMinValue(int i, int j) {
41 return (i<j) ? i : j;
42 }
43
44}
上述三位操作员Java程序的输出是:
14
210
3false
4Str contains 'A'
5i=10
6i=10
正如你所看到的,我们正在使用java ternary 操作员来避免 if-then-else 和 switch 案例陈述,以这种方式,我们正在减少java 程序中的代码行数。