In Java SE 22, you can initialize an array in several ways. Here, I’ll show you how to initialize arrays using different methods along with example code and their corresponding outputs.
1. Initializing an Array with a Specific Size:
You can create an array with a specific size and then assign values to its elements individually.
public class ArrayInitialization { public static void main(String[] args) { // Initializing an array with a specific size int[] numbers = new int[5]; // Assigning values to array elements numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50; // Output: Displaying array elements for (int i = 0; i < numbers.length; i++) { System.out.println("numbers[" + i + "] = " + numbers[i]); } } }
Output:
numbers[0] = 10 numbers[1] = 20 numbers[2] = 30 numbers[3] = 40 numbers[4] = 50
2. Initializing an Array with Values:
You can initialize an array with predefined values directly at the time of declaration.
public class ArrayInitialization { public static void main(String[] args) { // Initializing an array with values int[] numbers = {10, 20, 30, 40, 50}; // Output: Displaying array elements for (int i = 0; i < numbers.length; i++) { System.out.println("numbers[" + i + "] = " + numbers[i]); } } }
Output:
numbers[0] = 10 numbers[1] = 20 numbers[2] = 30 numbers[3] = 40 numbers[4] = 50
3. Initializing a Multidimensional Array:
You can also initialize multidimensional arrays using similar techniques.
public class ArrayInitialization { public static void main(String[] args) { // Initializing a 2D array with values int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // Output: Displaying array elements for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.println("matrix[" + i + "][" + j + "] = " + matrix[i][j]); } } } }
Output:
matrix[0][0] = 1 matrix[0][1] = 2 matrix[0][2] = 3 matrix[1][0] = 4 matrix[1][1] = 5 matrix[1][2] = 6 matrix[2][0] = 7 matrix[2][1] = 8 matrix[2][2] = 9
These are some common ways to initialize arrays in Java SE 22. Choose the method that suits your requirements based on the context and convenience.