Java Array – Sum of Elements

To find the sum of numbers in a Java Array, use a looping technique to traverse through the elements, and accumulate the sum.

In this tutorial, we will learn how to find the sum of elements in array, using different looping statements.

Java Integer Array Sum using While Loop

In the following program, we will initialize an integer array, and find the sum of its elements using Java While Loop.

Java Program

public class ArraySum {
	public static void main(String[] args) {
		int numbers[] = {5, 2, 3, 7, 3, 6, 9, 1, 8};
		int sum = 0;
		int index = 0;
		while (index < numbers.length) {
			sum += numbers[index];
			index++;
		}
		System.out.println("Sum : " + sum);
	}
}

Output

Sum : 44
ADVERTISEMENT

Java Float Array Sum using For Loop

In the following program, we will initialize a float array, and find the sum of its elements using Java For Loop.

Java Program

public class ArrayExample {
	public static void main(String[] args) {
		float numbers[] = {0.5f, 1.2f, 0.3f, 0.7f, 0.3f, 1.6f, 1.9f, 0.1f, 2.8f};
		float sum = 0;
		for (int index = 0; index < numbers.length; index++) {
			sum += numbers[index];
		}
		System.out.println("Sum : " + sum);
	}
}

Output

Sum : 9.4

Java Double Array Sum using For-each Loop

In the following program, we will initialize a double array, and find the sum of its elements using Java For-each Loop.

Java Program

public class ArraySum {
	public static void main(String[] args) {
		double numbers[] = {0.5, 1.2, 0.3, 0.7, 0.3, 1.6, 1.9, 0.1, 2.8};
		double sum = 0;
		for (double number: numbers) {
			sum += number;
		}
		System.out.println("Sum : " + sum);
	}
}

Output

Sum : 9.399999999999999

Conclusion

Concluding this Java Tutorial, we learned how to find Sum of Elements in Java Array with some of the combinations of numeric datatypes for array elements and looping technique. You may use any looping technique on any of the numeric datatypes and find the Java Array sum.