Sum of all elements in an ArrayList in Java

Hey, fellow programmers ! In this tutorial , You are going to learn the Java program to find the Sum of all elements in an ArrayList 

Sum of all elements in an ArrayList in Java

To find the sum of elements in an arraylist in java, we can start the programming by initializing sum to zero, then we will use loops to complete the program.

import java.util.ArrayList;

public class Codespeedytechnology {
    public static void main(String[] args) {

        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(7);
        arrayList.add(9);
        arrayList.add(6);
        arrayList.add(8);
        arrayList.add(2);
        

        int sum = 0;
        
        for (int num : arrayList) {
            sum += num;
        }
        
        System.out.println("Sum of all elements in the ArrayList: " + sum);
    }
}
Sum of all elements in the ArrayList: 32

Leave a Reply

Your email address will not be published. Required fields are marked *