让我们看看以下代码段中的简单Java代码:
public class Main {
private int temp() {
return true ? null : 0;
// No compiler error - the compiler allows a return value of null
// in a method signature that returns an int.
}
private int same() {
if (true) {
return null;
// The same is not possible with if,
// and causes a compile-time error - incompatible types.
} else {
return 0;
}
}
public static void main(String[] args) {
Main m = …Run Code Online (Sandbox Code Playgroud) 为什么此代码返回错误:java.lang.NullPointerException
Object obj = null;
Long lNull = null;
Long res = obj == null ? lNull : 10L;
Run Code Online (Sandbox Code Playgroud)
但是以下方式可以正常运行:
Object obj = null;
Long res = obj == null ? null : 10L;
Run Code Online (Sandbox Code Playgroud) 据我了解,以下代码不应抛出,Null Pointer exception因为我正在安全地使用 Optional 接口。
但是,当我运行此代码时,它会抛出NPE.
public class Test {
public static void main(String[] args) {
final Integer inte = false ? 0 : Optional.ofNullable((Integer) null).orElse(null);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我在代码中的某个地方弄错了,请告诉我并帮助我纠正相同的错误。