三元运算符写法
?
为三元运算符。
使用以下表达式:
语句1 ? 语句2 : 语句3
其中语句1返回true
或者false
。如果为true
则使用语句2的值,如果为false
则使用语句3的值。使用此语法代替if else
语句。
空指针情况:语句2或者语句3为基础类型,但是另外相对的语句不是直接为null值,而是返回值为null,或者值为null的变量,则会返回空指针。
情况1:语句2方法返回null,语句3为int类型,则空指针。
public static void main(String[] args) {
Integer result = true ? getNull() : 1;
}
private static Integer getNull() {
return null;
}
output>
Exception in thread "main" java.lang.NullPointerException
at com.dzq.Practice_10.main(Practice_10.java:7)
情况2:语句2直接为null,语句3为int类型,不会报空指针。
public static void main(String[] args) {
Integer result = true ? null : 1;
}
情况3:语句2为嵌套三元运算符返回null,语句3为int类型,则空指针。
public static void main(String[] args) {
Integer result = true ? (true ? null : 1) : 1;
}
output>
Exception in thread "main" java.lang.NullPointerException
at com.dzq.Practice_10.main(Practice_10.java:7)
情况4:语句2为嵌套三元运算符返回null,语句3为Integer类型,不会报空指针。
public static void main(String[] args) {
Integer result = true ? getNull() : new Integer(1);
}
private static Integer getNull() {
return null;
}
情况5:语句2为null的变量,语句3为int类型,则空指针。
public static void main(String[] args) {
Integer num = null;
Integer result = true ? num : 1;
}
output>
Exception in thread "main" java.lang.NullPointerException
at com.dzq.Practice_10.main(Practice_10.java:7)