Java Varargs Simple Addition – Hackerrank Problem

Java Varargs Simple Addition Problem:

You are given a class Solution and its main method in the editor.
Your task is to create the class Add and the required methods so that the code prints the sum of the numbers passed to the function add.

Before solve this problem, firstly know about JAVA VARARGS –

It is a variable argument. The varrags allows the method to accept zero or muliple arguments. Before varargs either we use overloaded method or take an array as the method parameter but it was not considered good because it leads to the maintenance problem. If we don’t know how many argument we will have to pass in the method, varargs is the better approach.

Syntax of Varargs :

return_type method_name(data_type… variableName){}

Note: Your add method in the Add class must print the sum as given in the Sample Output

Input Format of Java Varargs Simple Addition

There are six lines of input, each containing an integer.

Output Format of Java Varargs Simple Addition

There will be only four lines of output. Each line contains the sum of the integers passed as the parameters to add in the main method.

Sample Input


Sample Output


Solution Code of Java Varargs Simple Addition Problem :

class Add {
	public void add(int... intArgs) {
		int sum = 0;
		String separator = "";
		for (int i : intArgs) {
			sum += i;
			System.out.print(separator + i);
			separator = "+";			
		System.out.println("=" + sum);


Leave a reply:

Your email address will not be published.