How do you create an array in Java? Provide an example.
In Java, an array is a collection of elements of the same data type stored at contiguous memory locations. Here’s how you can create and initialize an array:
1. Declaration
To declare an array, specify the data type and use square brackets []. For example:
int[] numbers; // Declaration of an integer array
2. Initialization
You can initialize an array during or after declaration:
During Declaration:
int[] numbers = {1, 2, 3, 4, 5}; // Initializes an array with values
After Declaration:
numbers = new int[5]; // Allocates memory for 5 integers
numbers[0] = 10; // Assigns values to array elements
3. Example
Here’s a complete example of declaring, initializing, and accessing an array:
public class ArrayExample {
public static void main(String[] args) {
// Declaration and Initialization
int[] numbers = {10, 20, 30, 40, 50};
// Accessing elements
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
Types of Arrays
Single Dimensional Array: Example above.
Multidimensional Array: Arrays with multiple rows and columns, e.g., int[][] matrix.
Arrays are useful for storing and managing collections of data efficiently.