java数组如何定义
数组定义的基本语法
在Java中,数组是固定长度的同类型数据集合。定义数组需要指定数据类型和数组名称,并可以选择直接初始化或后续赋值。
一维数组定义示例:
// 方式1:声明后初始化(长度必须指定)
int[] arr1 = new int[5];
// 方式2:声明时直接初始化(长度自动推断)
int[] arr2 = {1, 2, 3, 4, 5};
// 方式3:先声明再赋值(较少用)
int arr3[];
arr3 = new int[]{6, 7, 8};
多维数组定义
多维数组本质是数组的数组,最常见的是二维数组(如矩阵)。
二维数组定义示例:
// 方式1:指定行数和列数
int[][] matrix1 = new int[3][4];
// 方式2:不规则数组(每行长度不同)
int[][] matrix2 = {{1, 2}, {3, 4, 5}, {6}};
// 方式3:分步初始化
int[][] matrix3 = new int[2][];
matrix3[0] = new int[3];
matrix3[1] = new int[5];
动态初始化与注意事项
数组长度在创建时确定且不可变,动态初始化需通过new关键字指定长度。
关键点:
- 基本类型数组默认值:
int为0,boolean为false,引用类型为null - 数组长度通过
length属性获取(如arr1.length) - 数组越界访问会抛出
ArrayIndexOutOfBoundsException
示例:动态填充数组
String[] names = new String[3];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";






