Loop through ArrayList in Java

Java 8Object Oriented ProgrammingProgramming

The elements of the ArrayList can be accessed one by one by using a for loop. A program that demonstrates this is given as follows

Example

 Live Demo

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      ArrayList<String> aList = new ArrayList<String>();
      aList.add("Sun");
      aList.add("Moon");
      aList.add("Star");
      aList.add("Planet");
      aList.add("Comet");
      System.out.println("The ArrayList elements are:");
      for (String s : aList) {
         System.out.println(s);
      }
   }
}

Output

The output of the above program is as follows

The ArrayList elements are:
Sun
Moon
Star
Planet
Comet

Now let us understand the above program.

The ArrayList aList is created. Then ArrayList.add() is used to add the elements to this ArrayList. Then the ArrayList elements are displayed using a for loop. A code snippet which demonstrates this is as follows

ArrayList<String> aList = new ArrayList<String>();
aList.add("Sun");
aList.add("Moon");
aList.add("Star");
aList.add("Planet");
aList.add("Comet");
System.out.println("The ArrayList elements are:");
for (String s : aList) {
   System.out.println(s);
}
raja
Published on 17-Jan-2019 17:52:31
Advertisements