For Each in Arraylist Java

CodeForHunger
2 min readMay 22, 2023

--

How to use for each loop in array list in java.

For Each in Arraylist Java, for each in java, for each loop, arrayList in java

In Java, an ArrayList is a dynamic array that can store objects of any type. To iterate through an ArrayList, you can use a for-each loop, which is also known as an enhanced for loop. The for-each loop simplifies the code because it hides the iterator or index variable and directly reaches each element of the ArrayList. Here are the steps to use a for-each loop with an ArrayList:

Step 1: Declare and initialize an ArrayList
First, you need to declare and initialize an ArrayList. You can use the ArrayList class and its add() method to add elements to the ArrayList. Let’s create an ArrayList of integers as an example:

ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(10);
numbers.add(20);
numbers.add(30);

Step 2: Use the for-each loop with the ArrayList: To use the for-each loop, you need to specify the data type of the elements present in the ArrayList, followed by giving a variable name that will represent each element in the ArrayList. Then, you need to provide a colon (:) and the name of the ArrayList. Here’s an example where the elements of the ArrayList are printed using a for-each loop:

for (int num : numbers) {
System.out.println(num);
}

In this example, the variable name “num” represents each element of the ArrayList, and the loop prints each element on a new line.

Step 3: Perform Actions on Each Element: You can perform actions on each element of the ArrayList by adding statements inside the for-each loop. Let’s say we want to add 5 to each element:

for (int num : numbers) {
num += 5;
System.out.println(num);
}

In this example, the special for-each loop adds 5 to each element and shows the updated values.

That’s all! Now you can use a for-each loop with an ArrayList in Java. Just remember, the for-each loop lets you read the elements of the ArrayList but doesn’t let you change them. If you want to modify the elements, you can use a regular for loop that includes an index variable.

--

--

CodeForHunger
CodeForHunger

Written by CodeForHunger

Here, I will share programming language tutorials and tech updates. Learn C and Java with tutorials, coding examples & interview questions. Follow for more...

No responses yet