次のコードは、単純な条件演算子を使用しています。
public class Main
{
public static void main(String[] args)
{
Integer exp1 = true ? null : 5;
Integer exp2 = true ? null : true ? null : 50;
System.out.println("exp1 = " +exp1+" exp2 = "+exp2);
Integer exp3 = false ? 5 : true ? null: 50; //Causes the NullPointerException to be thrown.
System.out.println("exp3 = "+exp3);
}
}
このコードは正常にコンパイルされます。すべての式は、最終的に型変数に割り当てようnull
とします。Integer
exp1
exp2
exp3
最初の2つのケースでは、例外をスローせずexp1 = null exp2 = null
、明らかな結果を生成します。
ただし、最後のケースを注意深く調べると、型変数null
への割り当ても試行され、前の2つのケースと似ていますが、がスローされることがわかります。なぜそれが起こるのですか?Integer
exp3
NulllPointerException
質問を投稿する前に、この素敵な質問を参照しましたが、この場合、JLSで指定されているルールがここで適用されていることがわかりませんでした。