What is ArrayList?

Let's write a Java program to create an ArrayList of integers, add elements to it, and then find the sum of all the elements.

I'll provide explanations for each step of the program:


import java.util.ArrayList; 
public class ArrayListSum
public static void main(String[] args) {
// Step 1: Create an ArrayList of integers
ArrayList<Integer> numbersList = new ArrayList<>();
// Step 2: Add elements to the ArrayList
numbersList.add(5);
numbersList.add(10); 
numbersList.add(15); 
numbersList.add(20);  
numbersList.add(25); 
// Step 3: Find the sum of all elements in the ArrayList
int sum = 0
// Initialize a variable to store the sum of elements 
// Loop through the ArrayList using the enhanced for loop (for-each loop) 
for (int number : numbersList) {
 sum += number; 
 } 
// Step 4: Print the elements in the ArrayList
System.out.println("Elements in the ArrayList: " + numbersList);
// Step 5: Print the sum of all elements 
 System.out.println("Sum of all elements: " + sum); 
 } 
}

Output:

Elements in the ArrayList: [5, 10, 15, 20, 25]

Sum of all elements: 75

Explanation:

  1. We start by creating an ArrayList called numbersList that can hold integer elements. We specify the data type Integer inside the angle brackets (<>) to indicate that it is an ArrayList of integers.
  2. We use the add() method to add elements to the numbersList. In this example, we add five integers: 5, 10, 15, 20, and 25.
  3. We initialize a variable sum to store the sum of all elements in the ArrayList. The initial value of sum is set to 0.
  4. We use a for-each loop to iterate through the elements of the ArrayList. In each iteration, the current element is assigned to the variable number, and we add this element to the sum.
  5. After the loop finishes, we have calculated the sum of all elements in the ArrayList.
  6. Finally, we print both the elements in the ArrayList and the sum of all elements using System.out.println().