Java Varargs - Simple Addition HackerRank Solution with Explanation
Problem Description :
Create the class Add and the required methods so that the code prints the sum of the numbers passed to the function add.
Sample Input and Output :
Input :
1
2
3
4
5
6
Output :
1+2=3
1+2+3=6
1+2+3+4+5=15
1+2+3+4+5+6=21
Lets first see what is Varargs before jump on solution.
What is Varargs in Java?
In Java, an argument of a method can accept arbitrary number of values. This argument can accept variable number of values is called varargs.
Varargs is a short name for variable arguments.
Every time we use varargs, the Java compiler creates an array to hold the given parameters.
If you want to create Java method, but you are not sure how many arguments is method accept. So in that case you can use Variable arguments.
Syntax of Varargs :
void methodName (datatype ...args) {
// Method body
}
void add (int ...args) {
// Method body
}
So lets jump on solution
Solution 1 :
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
class Add {
public static void add(int ...args) {
int sum = 0;
StringBuffer sumOf = new StringBuffer();
for (int i : args) {
sum += i;
sumOf = sumOf.append(i + "+");
}
sumOf.deleteCharAt(sumOf.length()-1);
System.out.println(sumOf +"="+ sum);
}
}
public class Solution {
public static void main(String[] args) {
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n1=Integer.parseInt(br.readLine());
int n2=Integer.parseInt(br.readLine());
int n3=Integer.parseInt(br.readLine());
int n4=Integer.parseInt(br.readLine());
int n5=Integer.parseInt(br.readLine());
int n6=Integer.parseInt(br.readLine());
Add ob=new Add();
ob.add(n1,n2);
ob.add(n1,n2,n3);
ob.add(n1,n2,n3,n4,n5);
ob.add(n1,n2,n3,n4,n5,n6);
Method[] methods=Add.class.getDeclaredMethods();
Set<String> set=new HashSet<>();
boolean overload=false;
for(int i=0;i<methods.length;i++)
{
if(set.contains(methods[i].getName()))
{
overload=true;
break;
}
set.add(methods[i].getName());
}
if(overload)
{
throw new Exception("Overloading not allowed");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Solution Explanation :
- In this problem, we have to create new Add class and add() method that takes Variable arguments.
- Create add method in Add class : public static void add(int ...args) { }
- Create new int variable and StringBuffer object. We can also use String class but StringBuffer is more preferred when we want to append another String.
- Loop through given varargs arguments and store sum of numbers in sum variable.
- Also same time add current number and + in StringBuffer for print.
- At last, before print numbers and sum remove last + from StringBuffer. We are using deleteCharAt() method of StringBuffer class for remove last extra +.
- Print Varargs numbers and sum.
We can also solve this problem without removing last + sign. lets see that solution also.
Solution 2 :
public void add(int... args) {
int sum = 0;
String addSign = "";
for (int i : args) {
sum += i;
System.out.print(addSign + i);
addSign = "+";
}
System.out.println("=" + sum);
}
Here we are appending + sign at last, so we does not have to remove last extra + from String.
Check How we can use varargs in Method Method Overloading and Method Overriding :
- Method Overloading in Java | Var args in Method Overloading
- Method Overriding in Java with examples and Rules | How overriding works var-args methods
Must remember things while using Varargs (Variable Arguments)
1. Method contains only one Varargs parameter
We can not use more than one Varargs parameter in one method.
Following code gives error.
public static void add(int ...args1, float ...args2) {
// Method body
}
2. While defining method signature, put varargs as last parameter.
// Following method declaration gives error.
public static void add(int ...args1, int a) {
// Method body
}
When we try to put varargs parameter before other parameter compiler gives error. Eclipse also gives following suggestion.
The variable argument type int of the method add must be the last parameter.
Following code compile successfully
public static void add(int a, int ...args1) {
// Method body
}
Happy Coding ...
Other HackerRank problem and its Solution :
Comments
Post a Comment