次のスニペットの簡単な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 = new Main();
System.out.println(m.temp());
System.out.println(m.same());
}
}
この最も単純なJavaコードでtemp()は、関数の戻り値の型がであっても、メソッドはコンパイラエラーを発行せずint、値をnull(ステートメントを通じてreturn true ? null : 0;)返します。コンパイルすると、明らかにランタイム例外が発生しNullPointerExceptionます。
ただし、3項演算子をif(same()メソッドのように)ステートメントで表すと、コンパイル時エラーが発生し、同じことが間違っているように見えます。どうして?
nullものIntegerです...それは、私にとって「推測」または「物事を機能させる」ように見えます...
Integer foo() { return "1"; }はコンパイルされません。)
int foo = (true ? null : 0)およびnew Integer(null)コンパイル罰金、オートボクシングの明示的な形である第2の両方。