03-下标越界及基本特点
数组的四个基本特点
-
其长度是确定的。数组一旦被创建,它的大小是不可以改变的。
-
其元素必须是相同类型的,不允许出现混合类型。
-
数组中的元素可以是任何数据类型,包括基本类型和引用类型。
-
数组变量属于引用类型,数组也可以看作是对象,数组中的每个元素相当于该对象的成员变量。数组本身就是对象,Java中对象是在堆中的,因此数组无论保存原始类型还是其他对象类型,数组对象本身是在堆中的。
数组边界
-
下标的合法区间:[0, length-1], 如果越界就会报错;
public static void main(String[] args) { int[] a=new int[2]; System.out.println(a[2]); }
-
ArrayIndexOutOfBoundsException:数组下标越界异常
-
小结:
-
数组是相同数据类型(数据类型可以为任意类型)的有序集合
-
-
数组长度是确定的、不可变的。如果越界,则会报:ArrayIndexOutOfBounds
-
package xiaoka.array;
public class ArrayDemo02 {
public static void main(String[] args) {
int[] a={1,2,3,4,5,6,7,8};
System.out.println(a[0]);
for (int i = 0; i <= a.length; i++) {//越界示范
System.out.println(a[i]);
}
}
}