在Java中,可以通過以下方式初始化數(shù)組并賦值:
int[] arr = {1, 2, 3, 4, 5};
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
需要注意的是,在Java中數(shù)組是引用類型,所以要確保在初始化數(shù)組后進(jìn)行賦值操作,否則數(shù)組元素的默認(rèn)值將會是數(shù)組元素類型的默認(rèn)值。