JAVA常见错误

1、数组越界

public static void main(String[] args) {
    int [] a=new int[2];
    System.out.println(a[2]);
}

错误提示:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at javastudy.ArrayDemo.main(ArrayDemo.java:17)

错误说明:

ArrayIndexOutOfBoundsException  数据角标越界异常。

因为本数据只有两个元素,输出是a[2]是第3个元素,越界了,访问到了数组不存在的角标元素。

2、空指针异常

public static void main(String[] args) {
    int [] a=new int[2];
    a=null;
    System.out.println(a[2]);//ArrayIndexOutOfBoundsException
}

错误提示:

Exception in thread "main" java.lang.NullPointerException
at javastudy.ArrayDemo.main(ArrayDemo.java:19)

错误说明:

NullPointerException 空指针异常

因为本数组定义后,又赋null后数组为空。引用没有指向任何值,为null时,该引用还在操作实体。

3、注释包

在注释JAVA源文件代码时,不能温注释package包,否则会出现以下提示:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

at javastudy.ConfunDemo7.main(ConfunDemo7.java:37)

原文地址:https://www.cnblogs.com/ibelieve618/p/6398829.html