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

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static jav...

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And ...