java.lang.nullpointerexception 错误分析

    xiaoxiao2022-07-05  225

    java.lang.nullpointerexception 它发生在Java程序在需要对象时尝试使用null时。

    NullPointerException是一个扩展RuntimeException的公共类。

    对于不同的方案,抛出NullPointerException,例如,如果您调用null对象的实例方法。

    同样,如果对象为null并且您尝试访问或修改该null对象的字段,则会发生此错误。如果尝试获取null的数组长度,也会抛出异常。

    public class error_demo {     public static void main(String []args) {         Integer Interger_demo = null;         int int_pri = Interger_demo.intValue();         System.out.println(int_pri);      } } NullPointerException是在Integer对象的null值被赋值给int类型变量时引发的。

    另请注意,将为Integer对象生成错误。如果在上面的示例中声明一个类似int的基本类型的变量而没有赋值,则不会生成错误。因此,int类型变量的默认值为0。

    在将其赋值给基本类型int变量之前,只需为Integer对象赋值。看到几乎相同的代码,我在上面的代码中将null更改为零并查看输出:

    public class error_demo {     public static void main(String []args) {         Integer Interger_demo = 0;         int int_pri = Interger_demo.intValue();         System.out.println("The NullPointerException is fixed and value of variable is: " +int_pri);      } } 在此示例中,java.lang.NullPointerException是在访问String数组的长度时引发的,该数组设置为null。这是String数组的声明方式:

    最新回复(0)