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

Sales by Match HackerRank Solution | Java Solution

HackerRank Sales by Match problem solution in Java   Problem Description : Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n=7 socks with colors socks = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .   Example 1 : Input : n = 6 arr = [1, 2, 3, 4, 5, 6] Output : 0 Explanation : We have 6 socks with all different colors, So print 0. Example 2 : Input : n = 10 arr = [1, 2, 3, 4, 1, 4, 2, 7, 9, 9] Output : 4 Explanation : We have 10 socks. There is pair of color 1, 2, 4 and 9, So print 4. This problem easily solved by HashMap . Store all pair of socks one by one in Map and check if any pair is present in Map or not. If pair is present then increment ans variable by 1 ...

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...