ArrayList Program in Java for Interview Practice

In this tutorial, we have listed the various types of ArrayList program in Java for practice. All example programs with explanations are important for beginners to understand the concepts of ArrayList in Java.

I will recommend that before going to practice all these programs, you must read the previous tutorial of ArrayList in Java that is very helpful for interviews.

How to add elements to ArrayList in Java Dynamically

Let’s take an example program where we will add elements in the array list dynamically. Look at the source code.

Program source code 1:

package arrayListProgram; 
import java.util.ArrayList; 
import java.util.List; 
public class ArrayListEx1 
{ 
public static void main(String[] args) 
{ 
// Creates an ArrayList object with an initial capacity of 10. 
   List<String> list = new ArrayList<String>(); 

// Call add() method to add elements at the end of the list using the reference variable list. 
   System.out.println("Adding elements to end of list"); 
    list.add("A"); // Adding elemen at index 0.
    list.add("B"); // Adding element at index 1.
    list.add("D"); // Adding element at index 2.
    list.add("E"); // Adding element at index 3.
    list.add("G"); // Adding element at index 4.
   
System.out.println("ArrayList insertion order: " +list); 
   
System.out.println("Adding an element at a specific index after B element."); 
   list.add(2, "C"); 
System.out.println("ArrayList insertion order after adding C: " +list ); 

System.out.println("Adding an element at a specific index after E"); 
   list.add(5, "F"); 
System.out.println("ArrayList insertion order after adding F: " +list); 
 } 
}
Output: 
       Adding elements to the end of the list 
       ArrayList insertion order: [A, B, D, E, G] 
       Adding an element at a specific index after B element. 
       ArrayList insertion order after adding C: [A, B, C, D, E, G] 
       Adding an element at a specific index after E 
       ArrayList insertion order after adding F: [A, B, C, D, E, F, G]

Explanation with diagram:

ArrayList Program in Java

In this example program, when we added a new element ‘C’ at a specific index 2, elements D,  E, and G are shifted to the one position left as shown in the above figure.


After inserting element C, the reference variable ‘list’ will reassign to the new array list and copy all the elements into the new ArrayList. The old default array list will be gone to the garbage collection.

Now the position of the element E is shifted from position 3 to position 4 in the new ArrayList. Therefore, the element F after E has been added at position 5, not at position 4.

Program source code 2:

package arrayListProgram; 
import java.util.ArrayList; 
public class ArrayListEx2 
{ 
public static void main(String[] args) 
{ 
// Creates an ArrayList1 with an initial capacity of 10. 
   ArrayList<String> al = new ArrayList<String>(); 
    al.add("G"); 
    al.add("H"); 
    al.add("I"); 
    al.add("M"); 
    al.add("N"); 
  System.out.println("Original ArrayList insertion order: " +al); 

// Creates another ArrayList2 with an initial capacity of 10. 
   ArrayList<String> al2 = new ArrayList<String>(); 
    al2.add("J"); 
    al2.add("K"); 
    al2.add("L"); 

// Call addAll() method to add all elements in the list2 at spcefic index 3. 
   al.addAll(3, al2); 
   System.out.println("ArrayList insertion order after adding group of elements in the list1 : " +al); 

// Creates ArrayList3 with initial capacity 10. 
   ArrayList<String> al3 = new ArrayList<String>(); 
    al3.add("20"); 
    al3.add("40"); 
    al3.add("12"); 
// Adding group of elements at the end of list1. 
    al.addAll(al3); 
    System.out.println(al); 
  } 
}
Output: 
       Original ArrayList insertion order: [G, H, I, M, N] 
       ArrayList insertion order after adding a group of elements in the list1 : [G, H, I, J, K, L, M, N] 
       [G, H, I, J, K, L, M, N, 20, 40, 12]

Java ArrayList Program based on Remove, Get, Contains, and Set methods

Let’s create a program where we will perform the following operations such as remove, get, contains, and set on elements of the list. Look at the source code.

Program source code 3:

package arrayListProgram; 
import java.util.ArrayList; 
public class ArrayListEx3 
{ 
public static void main(String[] args) 
{ 
  ArrayList<String> al = new ArrayList<String>(); 
   al.add("Science"); 
   al.add("Maths"); 
   al.add("Hindi"); 
   al.add("English"); 
   al.add("Social Science"); 
 System.out.println("Original ArrayList insertion order: " +al); 

// Call get() method to get element at the index 2. 
   String str = al.get(2); // Since the return type of get method is String. So we will store it using str variable with data type string. 
   System.out.println("Element at index 2: " +str); 

// Call contains() method to check whether the element English is present in the list or not. 
   boolean b = al.contains("English"); // Since the return type of contains method is boolean. So we will store it by using 'b' variable with type boolean. 

// The contains() method returns true if the specified element is present in the list otherwise false. 
   System.out.println(b); // return true. 
   boolean b2 = al.contains("Sanskrit"); 
   System.out.println(b2); // return false. 
   
   boolean bo=al.containsAll(al); // It will return truse if this collection contains all elements in the specified collection. 
   System.out.println(bo); 

// call remove() method to remove element English at a specified index. 
   al.remove(3); 
   System.out.println("After removing element, ArrayList Order: " +al); 

// Call set() method to replace element Social Science. 
   al.set(3, "Computer"); 
   System.out.println("After replacing element, ArrayList Order: " +al); 
  }
}
Output: 
      Original ArrayList insertion order: [Science, Maths, Hindi, English, Social Science] 
      Element at index 2: Hindi 
      true 
      false 
      true 
      After removing element, ArrayList Order: [Science, Maths, Hindi, Social Science] 
      After replacing element, ArrayList Order: [Science, Maths, Hindi, Computer]

Iteration ArrayList Program using Iterator, ListIterator, Enumeration, & Enhanced for loop

Let’s make a program where we will iterate elements of array list using Iterator, ListIterator, Enumeration, and for loop.


Program source code 4:

package arrayListProgram; 
import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Enumeration; 
import java.util.Iterator; 
import java.util.List; 
import java.util.ListIterator; 

public class ArrayListEx4 
{ 
public static void main(String[] args) 
{ 
 List<Integer> list = new ArrayList<Integer>(); 
  list.add(20); 
  list.add(25); 
  list.add(30); 
  list.add(35); 
  list.add(40); 
System.out.println("Original ArrayList: " +list); 
System.out.println("--Using Iterator--"); 

// Call iterator() method to iterate over the elements. 
   Iterator<Integer> itr = list.iterator(); 

// Checking the next element availability using reference variable itr. 
   while(itr.hasNext())
   { 
// Moving the cursor to next element using reference variable itr. 
     Integer it = itr.next(); // Here, return type is an integer. 
     System.out.println(it); 
   } 
System.out.println("--Iterating in forwarding direction using ListIterator--"); 

// Call ListIterator() method to iterate over the elements. 
   ListIterator<Integer> litr = list.listIterator(); 

// Checking the next element availability using reference variable litr. 
   while(litr.hasNext())
   { 
     Integer lit = litr.next(); 
     System.out.println(lit); 
    } 
System.out.println("--Using Enumeration-- "); 
 
Enumeration<Integer> enumlist = Collections.enumeration(list); 
while(enumlist.hasMoreElements())
 { 
   System.out.println(enumlist.nextElement()); 
  } 
System.out.println("--Using Enhanced for loop--"); 
for(Integer in : list)
{ 
   System.out.println(in); 
  } 
 } 
 } 
}
Output: 
       Original ArrayList: [20, 25, 30, 35, 40] 
       --Using Iterator-- 
       20 25 30 35 40 
      --Iterating in forwarding direction using ListIterator-- 
       20 25 30 35 40 
      --Using Enumeration-- 
       20 25 30 35 40 
      --Using Enhanced for loop-- 
       20 25 30 35 40

ArrayList Program based on isEmpty, Size, and Clear methods

Let’s create a program where we will perform the following operations such as checking of elements in the list, size of list, and delete all elements from the list. To perform these operations n the program, we will call three methods isEmpty(), size(), and clear() methods.

Program source code 5:

package arrayListProgram; 
import java.util.ArrayList; 
import java.util.List; 
public class ArrayListEx5 
{ 
public static void main(String[] args) 
{ 
// Creates an array with an initial capacity of 10. 
   List<String> list = new ArrayList<String>(); 

// Call isEmpty() method to check elements in the list. 
   boolean b = list.isEmpty(); // It will return true if this list contains no elements. 
   System.out.println(b); 

// Adding elements to the end of the list. 
   list.add("INDIA"); 
   list.add("USA"); 
   list.add("SRILANKA"); 
   list.add("JAPAN"); 
   list.add("FRANCE"); 
 System.out.println("Original ArrayList insertion order: " +list); 

// Call size() method to get the number of elements or length of ArrayList in the list. 
   Integer sizelist = list.size(); 
 System.out.println("Size/Length of the list: " +sizelist); 
 System.out.println(list.isEmpty()); // Return false. 
   
 System.out.println("--Clear all elements from the list--"); 
  list.clear(); 
 boolean bol = list.isEmpty(); 
 System.out.println(bol); 
   
Integer size = list.size(); 
System.out.println("No of elements in the list: " +size); 
 } 
}
Output: 
       true 
       Original ArrayList insertion order: [INDIA, USA, SRILANKA, JAPAN, FRANCE] 
       Size/Length of the list: 5 
       false 
      --Clear all elements from the list-- 
       true 
       No of elements in the list: 0

Program on ArrayList based on getting Index of First occurrence of Element

Let’s create a program where we will get the first occurrence of element from the list.

Program source code 6:

package arrayListProgram; 
import java.util.ArrayList; 
public class ArrayListEx6 
{ 
public static void main(String[] args) 
{ 
 ArrayList<String> al = new ArrayList<String>(); 
  al.add("ABC"); 
  al.add("DEF"); 
  al.add("ABC");  
  al.add("GHI"); 
  al.add(null); // null element is allowed in the ArrayList. 
System.out.println("Original ArrayList order:" +al); 

// Call indexOf() method to get the index of the first occurrence of a specific element in the list. 
  Integer indexofElement = al.indexOf("ABC"); // It will return the index of the first occurrence of the element. 
  System.out.println("Index of the element ABC: " +indexofElement); 
  
Integer indexElement = al.indexOf(null); 
System.out.println("Index of the element null: " +indexElement); 
Integer indexE = al.indexOf("JKL"); // It will return -1 if the element is not present in the list. 
System.out.println("Index of the element JKL: " +indexE); 
 } 
}
Output: 
       Original ArrayList order:[ABC, DEF, ABC, GHI, null] 
       Index of the element ABC: 0 
       Index of the element null: 4 
       Index of the element JKL: -1

ArrayList Program based on getting Index of Last occurrence of Element

Program source code 7:

package arraylistProgram; 
import java.util.ArrayList; 
public class ArrayListEx7 
{ 
public static void main(String[] args) 
{ 
 ArrayList<Integer> arlist = new ArrayList<Integer>(); 
  arlist.add(20); 
  arlist.add(25); 
  arlist.add(30); 
  arlist.add(35); 
  arlist.add(40); 
  arlist.add(25); 
  arlist.add(20); 
 System.out.println("Original ArrayList Order: " +arlist); 

Integer lastindex = arlist.lastIndexOf(25); 
System.out.println("Index of last occurrence of the element 25: " +lastindex); 
Integer lindex = arlist.lastIndexOf(20); 
System.out.println("Index of the element 20: " +lindex ); 
  } 
}
Output:  
       Original ArrayList Order: [20, 25, 30, 35, 40, 25, 20] 
       Index of last occurrence of the element 25: 5 
       Index of the element 20: 6

8. Assume that list1 is an array list that contains strings Apple, Mango, and Grapes, and list2 is another array list that contains strings Apple, Mango, and Guava.

Answer the following questions:

a. What are list1 and list2 after executing list1.addAll(list2)?
b. What are list1 and list2 after executing list1.add(list2)?
c. What are list1 and list2 after executing list1.removeAll(list2)?
d. What are list1 and list2 after executing list1.remove(list2)?
e. What are list1 and list2 after executing list1.retainAll(list2)?
f. What is list1 after executing list1.clear()?

Answer:

a) List1: [Apple, Mango, Grapes, Apple, Mango, Guava]

List2: [Apple, Mango, Guava]

b) Compile time error: The method add(String) in the type List<String> is not applicable for the arguments (List<String>).

c) List1: [Grapes]

List2: [Apple, Mango, Guava]

d) List1: [Apple, Mango, Grapes]

List2: [Apple, Mango, Guava]

e) List1: [Apple, Mango]

List2: [Apple, Mango, Guava]

f) List1: [ ]

9. What is wrong with each of the following code?

a. ArrayList<int> al = new ArrayList<int>();
b. ArrayList<String> al = new ArrayList();
c. ArrayList<String> al = new ArrayList<String>;

d. ArrayList<Integer> al = new ArrayList<Integer>();
   for (int i = 1; i <= 10; i++)
   {
     al.set(i - 1, i * i);
   }
e. ArrayList<Integer> al;
   for (int i = 1; i <= 10; i++)
   {
     al.add(i * i);
    }

Answer:
a) Syntax error.
b) No problem.
c) Syntax error.
d) IndexOutOfBoundsException
e) Compile time error: The local variable al may not have been initialized.

10. What is the output of the following program?

public class AddDemo 
{
public static void main(String[] args) 
{
 ArrayList<String> al = new ArrayList<String>();
  al.add("A");
  al.add(0, "B");
  al.add("C");
  al.remove(1);	
System.out.println(al);
 }
}

Output: [B, C]

Hope that this tutorial has covered almost all the important ArrayList programs in Java based on all methods provide by array list. I hope that you will have practiced all the interview programs.
Thanks for reading!!!

Next ⇒ Use of ArrayList in Java⇐ PrevNext ⇒

Leave a Comment