C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

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.
Submitted by IncludeHelp, on October 19, 2017

Here, we are creating an ArrayList, adding 5 elements (100, 200, 300, 400 and 500) and printing them 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 arrList.size() method of “ArrayList” class, here arrList is an object of ArrayList class.

Consider the program

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

Array List elements: 
500
400
300
200
100






COMMENTS