Tuesday, January 14, 2025
HomeTechFor-each loop in Java

For-each loop in Java

The for-each loop in Java is a simplified version of the traditional for loop, used to iterate over collections or arrays. It eliminates the need for using an index and directly accesses each element in the collection or array.

Syntax of the for-each loop:

for (datatype variable : array_or_collection) {
    // Code to be executed for each element
}
  • datatype: The type of the elements in the array or collection (e.g., int, String, Object).
  • variable: A temporary variable that holds each element of the array or collection as the loop iterates.
  • array_or_collection: The array or collection that you want to iterate over (e.g., an array, a List, a Set).
See also  How do I make text bold in HTML?

Example 1: Iterating over an Array

public class ForEachExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        
        // Using for-each loop to iterate over the array
        for (int number : numbers) {
            System.out.println(number);
        }
    }
}

Output:

1
2
3
4
5

Example 2: Iterating over a List

import java.util.*;

public class ForEachListExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        
        // Using for-each loop to iterate over the List
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

Output:

Apple
Banana
Cherry

Advantages of the for-each Loop:

  1. Simpler syntax: You don’t need to manage the loop index or the length of the array/collection.
  2. Readability: The loop is easier to read and write, especially when you’re only interested in the elements.
  3. Safety: It reduces the risk of errors like ArrayIndexOutOfBoundsException or ConcurrentModificationException (in certain situations).
See also  How to fix Recovery Pending State in SQL Server Database?

Limitations of the for-each Loop:

  1. No access to index: You can’t access the index of elements while iterating.
  2. Read-only iteration: You can’t modify the elements of the array or collection during the iteration, as it’s designed for read-only operations.
See also  Introduction to Microsoft Azure A Cloud Computing Service

In general, the for-each loop is a great tool when you just need to access the elements of a collection or array and don’t need the index. For more complex operations involving indices or modifications, a traditional for loop is more suitable.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x