//声明1,默认[0,0,0]
int[] a = new int[3];
for(int i = 0 ; i < a.length ; i++){
System.out.println(a[i]);
}
// 声明2,默认[0,0,0]
int a[] = new int[3];
System.out.println(Arrays.toString(a));
// [null,null]
String[] b = new String[2];
for(int i = 0 ; i < b.length ; i++){
System.out.println(b[i]);
}
声明+赋值
//声明1 先声明 后赋值
int[] a = new int[3];
a[0] = 3;
a[1] = 4;
a[2] = 5;
//声明2
int[] b = new int[]{3, 4, 5};
//声明3
int[] c = {3, 4, 5};
//遍历输出
for (int i = 0; i < c.length; i++) {
System.out.println(c[i]);
}
数组越界异常ArrayIndexOutOfBoundsException
// [null,null]
String[] a = new String[2];
// null
System.out.println(a[0]);
// null
System.out.println(a[1]);
// java.lang.ArrayIndexOutOfBoundsException
System.out.println(a[2]);
System.out.println("aaaaaaa");
2、二维数组
int[][] score = new int[][]{
{1, 2, 3},
{4, 5, 6, 8},
{7, 8, 9}
};
System.out.println(score[0][1]);
System.out.println(score[1][1]);
System.out.println(score.length);
System.out.println(score[1].length);
System.out.println(score[0].length);
for (int i = 0; i < score.length; i++) {
for (int j = 0; j < score[i].length; j++) {
System.out.print(score[i][j] + " ");
}
System.out.println();
}