Java array
Created By: chatGPT
Java arrays are a fundamental structure in Java that allow you to store multiple values in a single variable. An array can hold a fixed number of values of a single type and is zero-indexed. Here’s how you can declare, initialize, and access elements of an array.
int[] numbers = new int[5]; // Declare an array of integers with size 5
numbers[0] = 10; // Assign value to the first element
numbers[1] = 20; // Assign value to the second element
numbers[2] = 30; // Assign value to the third element
// Accessing array elements
System.out.println(numbers[0]); // Outputs 10
System.out.println(numbers[1]); // Outputs 20
Arrays can also be initialized at the time of declaration. You can create an array and assign values in one line. Here’s an example of how to declare an array with initial values.
String[] fruits = {"Apple", "Banana", "Cherry"};
// Accessing elements
System.out.println(fruits[0]); // Outputs Apple
System.out.println(fruits[2]); // Outputs Cherry
You can also find the length of an array using the length property. This helps you understand how many elements your array can hold, enabling you to iterate through it safely.
int[] numbers = {1, 2, 3, 4, 5};
int arrayLength = numbers.length; // arrayLength will be 5
// Loop through the array
for (int i = 0; i < arrayLength; i++) {
System.out.println(numbers[i]);
}
Multi-dimensional arrays are another useful feature in Java. They allow you to create arrays of arrays, which is perfect for representing data in a grid or table format.
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// Accessing elements in a multi-dimensional array
System.out.println(matrix[0][0]); // Outputs 1
System.out.println(matrix[1][2]); // Outputs 6
To iterate through an array efficiently, you can use an enhanced for loop which simplifies the syntax and reduces the chances of errors.
for (int number : numbers) {
System.out.println(number);
}