如何在Java中声明和初始化数组?
在Java编程中,有很多方法可以声明和初始化数组元素,但是在这里,我们采用三种不同的方法来声明和初始化数组元素。在这里,我们正在编写三种不同的方式:
考虑给定的语句(类型1):
int[] arr1 = {10,20,30,40,50};考虑给定的语句(类型2):
int[] arr2;
arr2 = new int[] {100,200,300,400,500};考虑给定的语句(类型3):
int arr3[] = {11,22,33,44,55};Java中的数组声明和初始化示例
该程序声明三个一维整数数组,并通过不同的3种方法初始化数组元素。
public class ArrayExample{
public static void main(String args[]){
//输入1-
int[] arr1 = {10,20,30,40,50};
//类型2-
int[] arr2;
arr2 = new int[] {100,200,300,400,500};
//输入3-
int arr3[] = {11,22,33,44,55};
//打印元素
System.out.println("Array elements of arr1: ");
for(int i=0; i<arr1.length; i++){
System.out.print(arr1[i] + "\t");
}
//打印一行
System.out.println();
System.out.println("Array elements of arr2: ");
for(int i=0; i<arr2.length; i++){
System.out.print(arr2[i] + "\t");
}
//打印一行
System.out.println();
System.out.println("Array elements of arr3: ");
for(int i=0; i<arr3.length; i++){
System.out.print(arr3[i] + "\t");
}
//打印一行
System.out.println();
}
}输出结果
Array elements of arr1: 10 20 30 40 50 Array elements of arr2: 100 200 300 400 500 Array elements of arr3: 11 22 33 44 55