Why does the Java compiler sometimes allow the unboxing of null?

后端 未结 3 1223
梦谈多话
梦谈多话 2021-02-19 02:52

For example:

int anInt = null;

fails at compile time but

public static void main(String[] args) {
  for (int i = 0; i < 10;          


        
3条回答
  •  暖寄归人
    2021-02-19 03:10

    You can't assign null to an int

        int anInt = null;
    

    Java allows this since you are not assigning null to an int

        System.out.println("" + getSomeVal()); //null was just converted to a srting and was printed
    

    If you perform this, you can get the error

        int anInt = getSomeVal();
    

提交回复
热议问题