Arrays in Java are a fundamental data structure that allow you to store multiple values of the same type in a single variable. Here's an in-depth explanation of arrays in Java:
Declaration: You can declare an array by specifying the type of its elements and the array's name.
int[] numbers;
String[] names;
Initialization: You can initialize an array at the time of declaration or later in your code.
// Initialization at the time of declaration
int[] numbers = new int[5];
String[] names = new String[3];
// Initialization with values
int[] primes = {2, 3, 5, 7, 11};
String[] fruits = {"Apple", "Banana", "Cherry"};
Array elements are accessed using their index, which starts at 0. You can use the array's name followed by the index in square brackets.
int firstPrime = primes[0]; // Accessing the first element
String firstFruit = fruits[0]; // Accessing the first element
System.out.println(firstPrime); // Output: 2
System.out.println(firstFruit); // Output: Apple
You can modify the elements of an array by assigning new values to specific indices.
numbers[0] = 10;
numbers[1] = 20;
fruits[1] = "Blueberry";
System.out.println(numbers[0]); // Output: 10
System.out.println(fruits[1]); // Output: Blueberry
The length of an array can be determined using the length property.
int numberOfPrimes = primes.length;
int numberOfFruits = fruits.length;
System.out.println(numberOfPrimes); // Output: 5
System.out.println(numberOfFruits); // Output: 3
You can use loops to iterate over array elements.
// Using a for loop
for (int i = 0; i < primes.length; i++) {
System.out.println(primes[i]);
}
// Using an enhanced for loop
for (String fruit : fruits) {
System.out.println(fruit);
}