Loop Through an Array in Java
Looping through an array allows you to access or modify each element systematically. You can use different types of loops to iterate over arrays.
Key Topics
1. Using a For Loop
The traditional for
loop gives you access to the index of each element.
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
2. Using a For-Each Loop
The enhanced for
loop simplifies iteration when you don't need the index.
int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
System.out.println("Number: " + number);
}
3. Modifying Array Elements
You can modify elements during iteration using the index.
String[] fruits = {"Apple", "Banana", "Cherry"};
for (int i = 0; i < fruits.length; i++) {
fruits[i] = fruits[i].toUpperCase();
}
Key Takeaways
- Use loops to iterate over array elements.
- The traditional
for
loop is useful when you need the index. - The for-each loop is more concise when you only need the value.