参考链接: Java中的运算符
本示例说明如何编写Java三元运算符。 这是语法
condition ? get_this_if_true : get_this_if_false
Java三元运算符语法
(n > 18) ? true : false;
(n == true) ? 1 : 0;
(n == null) ? n.getValue() : 0;
1. Java三元运算符
1.1不带三元运算符的Java示例。
JavaExample1.java
package com.mkyong.test;
public class JavaExample1 {
public static void main(String[] args) {
int age = 10;
String result = "";
if (age > 18) {
result = "Yes, you can vote!";
} else {
result = "No, you can't vote!";
}
System.out.println(result);
}
}
输出量
No, you can't vote!
1.2使用三元运算符,可以像下面这样简化代码:
JavaExample1_2.java
package com.mkyong.test;
public class JavaExample1_2 {
public static void main(String[] args) {
int age = 10;
String result = (age > 18) ? "Yes, you can vote!" : "No, you can't vote!";
System.out.println(result);
}
}
输出量
No, you can't vote!
简而言之,它提高了代码的可读性。
2.空检查
通常,将三元运算符用作null检查。
JavaExample2.java
package com.mkyong.test;
import com.mkyong.customer.model.Customer;
public class JavaExample2 {
public static void main(String[] args) {
Customer obj = null;
int age = obj != null ? obj.getAge() : 0;
System.out.println(age);
}
}
输出量
0
参考文献
Oracle –相等,关系和条件运算符
标记: Java 三元运算符
翻译自: https://mkyong.com/java/java-ternary-operator-examples/