数组常见的问题

1. NullPointerException空指针异常

          原因:引用类型(8种基本数据类型以外的所有类型)变量没有指向任何对象,而访问了对象的属性或者是调用了对象的方法。

案例1如下:

/**
* Author:Liu Zhiyong
* Version:Version_1
* Date:2016年4月5日19:07:10
* Desc:数组中最常见的问题:
* NullPointerException空指针异常
* 原因:引用类型(8种基本数据类型以外的所有类型)变量没有指向任何对象,而访问了对象的属性或者是调用了对象的方法。
*/
class Demo20
{
public static void main(String[] args) throws Exception
{
int[] arr = new int[2];
arr = null; //null让该变量不要引用任何的对象(即不要记录任何的内存地址)
System.out.println("这里会被执行吗1");
arr[1] = 10;//问题出在这里
System.out.println("这里会被执行吗2");
System.out.println(arr[1]);
}
}

案例1结果:

数组常见的问题_基本数据类型

案例1分析:

数组常见的问题_数组_02

2.ArrayIndexOutOfBoundsException索引值越界异常

    原因:访问了不存在的索引值

案例2如下:

/**
* Author:Liu Zhiyong
* Version:Version_1
* Date:2016年4月5日19:07:10
* Desc:数组中最常见的问题:
* 2.ArrayIndexOutOfBoundsException
* 原因:访问了不存在的索引值
*/
class Demo20
{
public static void main(String[] args) throws Exception
{
int[] arr = new int[2];
arr[0] = 1;
arr[1] = 2;
// System.out.println(arr[2]);//访问索引值为2的内存空间存储的值
for(int index=0; index<=arr.length; index++){ //问题出在这里,index<=,=的话就越界了
System.out.println(arr[index]);
}
}
}

案例2结果:

数组常见的问题_ArrayIndexOutOfBound_03

案例2分析:

数组常见的问题_基本数据类型_04