一、数组使用时的常见错误
1、索引越界错误
public class Test04{
public static void main(String[] args){
int[] arr = {
10, 20, 30};
System.out.println("arr[0]= " + arr[0]);
System.out.println("arr[1]= " + arr[1]);
System.out.println("arr[2]= " + arr[2]);
System.out.println("arr[3]= " + arr[3]);
}
}
如上代码中,arr[3]应该是越界了的,数组中只有3个元素,因此会出现越界错误。但在编译时系统不会报错,而在运行时才会报错。
2、空指针异常
public class Test04{
public static void main(String[] args){
int[] arr = {
10, 20, 30};
arr = null; //将数组的地址定义为空
System.out.println(arr[0]);
}
}
如上代码,就在某处将数组的地址指向空了,因此会导致空指针异常,数组的值也就找不到了。同样在编译时不会报错,而是在运行时才会报错。
二、数组的操作案例
1、数组遍历
public class Test04{
public static void main(String[] args){
int[] arr = {
11, 22, 33, 44, 55};
System.out.println(