How do you declare an array in Java SE 22?

Hello Friends Today, through this tutorial, I will tell you How to you declare an array in Java SE 22 With Example. In Java SE 22, you declare an array by specifying the data type of the elements it will contain, followed by square brackets `[]` and then the name of the array variable. Here are two examples of declaring arrays with sample outputs:

Example 1: Declaring and Initializing an Array of Integers

public class ArrayExample {
public static void main(String[] args) {

// Declare and initialize an array of integers
int[] numbers = {10, 20, 30, 40, 50};

// Access and print elements of the array
System.out.println("Elements of the array:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element " + i + ": " + numbers[i]);
}
}
}

Output:

Elements of the array:
Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50

Example 2: Declaring an Array of Strings and Assigning Values

public class ArrayExample {
public static void main(String[] args) {

// Declare an array of strings
String[] names;

// Initialize the array with values
names = new String[]{"Alice", "Bob", "Charlie", "David"};

// Print the elements of the array
System.out.println("Names in the array:");
for (int i = 0; i < names.length; i++) {
System.out.println("Name " + (i + 1) + ": " + names[i]);
}
}
}

Output:

Names in the array:
Name 1: Alice
Name 2: Bob
Name 3: Charlie
Name 4: David

In these examples, the first one demonstrates declaring and initializing an array of integers directly with values, while the second example shows declaring an array of strings and then assigning values to it later.