Skip to main content

Varargs in Java with Examples | HackerRank Solution | Varargs in Method Overloading and Overriding

Java Varargs - Simple Addition HackerRank Solution with Explanation

Varargs in Java with examples | varargs with method overloading and overriding

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 : 

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

Popular posts from this blog

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...