Home »
Java Programs »
Java ArrayList Programs
Java program to add elements in ArrayList and print them in reverse order
In this program, we are going to create an ArrayList, add elements in the ArrayList and print elements in reverse order.
By IncludeHelp Last updated : December 31, 2023
Problem statement
Write a Java program to add elements in ArrayList and print them in reverse order.
Printing elements in reverse order
To print elements in reverse order, we are running a loop from N-1 (Here, N is the total number of elements in the ArrayList) to 0.
To get the total number of elements of ArrayList, we use size() method of ArrayList class.
Java program to print ArrayList elements in reverse order
Here, we are creating an ArrayList, adding 5 elements (100, 200, 300, 400 and 500) and printing them in reverse order.
import java.util.ArrayList;
public class ExArrayList {
public static void main(String[] args) {
////Creating object of ArrayList
ArrayList arrList = new ArrayList();
//adding data to the list
arrList.add("100");
arrList.add("200");
arrList.add("300");
arrList.add("400");
arrList.add("500");
System.out.println("Array List elements: ");
//display array list elements in reverse order
for(int iLoop=arrList.size()-1; iLoop >= 0; iLoop--)
System.out.println(arrList.get(iLoop));
}
}
Output
The output of the above example is:
Array List elements:
500
400
300
200
100
Java ArrayList Programs »