Java三元运算符是唯一采用三个操作数的条件运算符。Java三元运算符是if-then-else
语句的单行替换方案,它在java编程中使用非常广泛。也可以使用三元运算符来替换switch-case
语句。
Java三元运算符
java三元运算符中的第一个操作数应该是布尔值或带有布尔结果的语句。如果第一个操作数为true
,则java三元运算符返回第二个操作数,否则返回第三个操作数。
java三元运算符的语法是:
result = boolean_test_statement ? value1 : value2;
如果boolean_test_statement
为true
,则将value1
分配给result
变量,否则将value2
分配给result
变量。
下面来看一个java程序中的三元运算符的例子。
// Power by example.com public class TernaryOperator { public static void main(String[] args) { System.out.println(getMinValue(4, 10)); System.out.println(getAbsoluteValue(-10)); System.out.println(invertBoolean(true)); String str = "example.com"; String data = str.contains("A") ? "Str contains 'A'" : "Str doesn't contains 'A'"; System.out.println(data); int i = 10; switch (i) { case 5: System.out.println("i=5"); break; case 10: System.out.println("i=10"); break; default: System.out.println("i is not equal to 5 or 10"); } System.out.println((i == 5) ? "i=5" : ((i == 10) ? "i=10" : "i is not equal to 5 or 10")); } private static boolean invertBoolean(boolean b) { return b ? false : true; } private static int getAbsoluteValue(int i) { return i < 0 ? -i : i; } private static int getMinValue(int i, int j) { return (i < j) ? i : j; } }
执行上面示例代码,得到以下结果 -
4 10 false Str doesn't contains 'A' i=10 i=10
正如上面所看到的,代码使用java三元运算符来代替if-then-else
和switch case
语句。这样就减少了java程序中的代码行数。