- How to calculate sum of all numbers in a given array in Java [Example]
- Java Program to calculate the sum of array elements in Java
- Find Sum and Average in a Java Array
- 1. Introduction
- 2. Find Sum of Array Elements
- 2.1. Sum Using a For Loop
- 2.2. Sum With the Java Stream API
- 3. Find Average in a Java Array
- 3.1. Average Without the Stream API
- 3.2. Average Using the Java Stream API
- 4. Conclusion
How to calculate sum of all numbers in a given array in Java [Example]
Hello guys, if you are thinking about how to calculate the sum of all numbers in a given integer array then you have come to the right place. Earlier, I have shared 75 programming questions from the interview and in today’s coding problem, you will learn how to write a program to calculate the sum of array elements in Java. As part of this coding problem, you need to write a method that will accept an integer array and it should return the total sum of all the elements. The array could contain both positive and negative numbers but only decimal numbers are allowed.
The array can also be null or empty so make sure your solution handles those as well. In the case of a null or empty array, your program can throw IllegalArgumentException . The empty array means an array whose length is zero or there is no element inside it.
Well, that’s enough for the requirement of this simple coding problem. The solution is really simple, just loop through the array and keep adding elements into sum until you process all the elements.
There is no tricky thing in this program. It is particularly designed to make a new programmer familiar with working with array and loop like how to loop over an array, how to retrieve elements from an array using the index, and how to write a function to return an integer.
The solution to the problem is very simple, first, you need to write code to take the input from the user. Since you cannot take an array as input from the command line, you need to take each element in store in the array you are going to pass to the sum() method.
This method takes an array and returns the sum of its elements. For the sake of simplicity, it is not throwing IllegalArgumentException but you can code it by yourself. Just do the check before calculating the sum in a for loop.
By the way, if you are new to Java and not familiar with basic concepts like an array, linked list, or how to get input from users then I highly recommend you to join a comprehensive Java course like The Complete Java Masterclass by Tim Buchalaka on Udemy. This 80+ hour course is the most comprehensive and up-to-date course to learn Java online.
Java Program to calculate the sum of array elements in Java
Here is our complete Java program to calculate the sum of all elements of the given array. It uses Scanner to take user input from the command prompt and enhanced for loop of Java 5 to loop over the array. In each step we add the current element into the sum variable and once the iteration finishes we return this value to the caller. This the sum of all elements of the given array.
By the way, if you are preparing for coding interviews and want to refresh your data structure and algorithm knowledge in Java then I also suggest you join Data Structures for Coding Interviews in Java, an interactive course by Educative to master Data Structure in Java.
The great thing about Educative is that it allows you to run code directly in your browser, which makes learning faster as you won’t need to download any software or set up your own development environment.
And, If you seriously want to develop your coding sense and understand data structure and algorithms, and love reading books then you can also solve advanced problems given in Algorithm Design Manual by Steven Skiena, after solving these basic problems.
import java.util.Scanner; /* * Java Program to calculate sum of array elements * input = [1, 2, 3, 4, 5, 6] * output = 21 */ public class ArraySumProblem < public static void main(String[] args) < System.out.println("Welcome to Java program to calculate sum of elements in an array"); System.out.println("Please enter the length of array?"); Scanner scnr = new Scanner(System.in); int length = scnr.nextInt(); int[] input = new int[length]; System.out.println("Please enter elements of array"); for (int i = 0; i < length; i++) < input[i] = scnr.nextInt(); > int total = sumOfElements(input); System.out.println("Sum of all elements of array is " + total); scnr.close(); > /** * A Java method to run sum of all elements of given array * * @param array * @return sum of all elements of int array */ public static int sumOfElements(int[] array) < int sum = 0; for (int i : array) < sum = sum + i; > return sum; > > Output Welcome to Java program to calculate sum of elements in an array Please enter the length of an array? 4 Please enter elements of array 1 2 2 3 Sum of all elements of array is 8 Welcome to Java program to calculate sum of elements in an array Please enter the length of an array? 6 Please enter elements of array 202 34 56 6 5 46 Sum of all elements of array is 349
That’s all about how to calculate the sum of array elements in Java. It’s one of the simplest Java programming exercises but very good to build command over programming constructs. At the beginner level, these small program helps you to gain confidence and learn fast.
- How to remove duplicate elements from the array in Java? (solution)
- How to reverse an array in place in Java? (solution)
- How to check if a year is a leap year in Java? (solution)
- How to print Fibonacci series in Java (solution)
- How to find all permutations of a given String in Java? (solution)
- How to reverse a String in place in Java? (solution)
- How to find if the given Integer is Palindrome in Java? (solution)
- How to check if a String contains duplicate characters in Java? (solution)
- How to find the highest occurring word from a given file in Java? (solution)
- How to count vowels and consonants in a given String in Java? (solution)
- How to implement Linear Search in Java? (solution)
- How to check if the given String is palindrome or not in Java? (solution)
- How to remove duplicate characters from String in Java? (solution)
- How to implement binary search in Java? (solution)
- How to check if the given number is prime in Java (solution)
- How to check if two given Strings are Anagram in Java? (solution)
- How to reverse words in a given String in Java? (solution)
- How to calculate the Area of Triangle in Java? (program)
P. S. — If you are new to the Java world and want to learn Java Programming forms scratch and you are also looking for a free online course to start with then you can also check out this Java Tutorial for Complete Beginners (FREE) course from Udemy. This course is completely free and more than 1.2 million people have joined this course to learn Java online.
Find Sum and Average in a Java Array
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Introduction
In this quick tutorial, we’ll cover how we can calculate sum & average in an array using both Java standard loops and the Stream API.
2. Find Sum of Array Elements
2.1. Sum Using a For Loop
In order to find the sum of all elements in an array, we can simply iterate the array and add each element to a sum accumulating variable.
This very simply starts with a sum of 0 and add each item in the array as we go:
public static int findSumWithoutUsingStream(int[] array) < int sum = 0; for (int value : array) < sum += value; >return sum; >
2.2. Sum With the Java Stream API
We can use the Stream API for achieving the same result:
public static int findSumUsingStream(int[] array)
It’s important to know that the sum() method only supports primitive type streams.
If we want to use a stream on a boxed Integer value, we must first convert the stream into IntStream using the mapToInt method.
After that, we can apply the sum() method to our newly converted IntStream:
public static int findSumUsingStream(Integer[] array)
You can read a lot more about the Stream API here.
3. Find Average in a Java Array
3.1. Average Without the Stream API
Once we know how to calculate the sum of array elements, finding average is pretty easy – as Average = Sum of Elements / Number of Elements:
public static double findAverageWithoutUsingStream(int[] array) < int sum = findSumWithoutUsingStream(array); return (double) sum / array.length; >
- Dividing an int by another int returns an int result. To get an accurate average, we first cast sum to double.
- Java Array has a length field which stores the number of elements in the array.
3.2. Average Using the Java Stream API
public static double findAverageUsingStream(int[] array)
IntStream.average() returns an OptionalDouble which may not contain a value and which needs a special handling.
Read more about Optionals in this article and about the OptionalDouble class in the Java 8 Documentation.
4. Conclusion
In this article, we explored how to find sum/average of int array elements.
As always, the code is available over on Github.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes: