Java varargs

Filed Under: Java

Java varargs was introduced in Java 1.5. Java varargs is also known as java variable arguments.

Java varargs

varargs in java enables a method to accept variable number of arguments. We use three dots (…) also known as ellipsis in the method signature to make it accept variable arguments. For example;


public static int sum(int i, int...js ){
//do something
}

Important points about varargs in java

Few points to know about varargs in java are;

  1. We can have only one varargs in the method.
  2. Only the last argument of a method can be varargs.
  3. According to java documentation, we should not overload a varargs method. We will see why it’s not a good idea.

How java varargs work?

When we invoke a method with variable arguments, java compiler matches the arguments from left to right. Once it reaches to the last varargs parameter, it creates an array of the remaining arguments and pass it to the method. In fact varargs parameter behaves like an array of the specified type.


//method with variable arguments
public static int sum(int i, int...js ){
    int sum = i;
    for(int x : js){
        sum+=x;
    }
    return sum;
}

//method with same implementation as sum with array as argument
public static int sumArray(int i, int[] js ){
    int sum = i;
    for(int x : js){
        sum+=x;
    }
    return sum;
}

If you will look at both sum and sumArray methods, you will see that the implementation body is exactly same. So we should use varargs when API offers them, for example java.io.PrintStream.printf() method but we should not take it as a replacement for array.

Why we should not overload varargs method

Let’s look at an example why overloading java varargs method is not a good idea.


package com.journaldev.misc;

public class VarargsExample {

    public static void main(String[] args) {
        System.out.println(sum(1));
        System.out.println(sum(1,2)); //compiler error, ambiguous method

    }

    public static int sum(int i, int...js ){
        System.out.println("sum1 called");
        int sum = i;
        for(int x : js){
            sum+=x;
        }
        return sum;
    }
    public static int sum(int i, int k, Object...js ){
        System.out.println("sum2 called");
        int sum = i+k;
        for(Object x : js){
            sum+=1;
        }
        return sum;
    }
    
}

In above example, you will notice that compiler will not complain when we overload methods with varargs. But when we try to use it, compiler get’s confused which method to use when mapping the second argument.

If there is only one argument, compiler is smart to use first method because it can work with minimum one argument but second method needs at least two arguments. Below image from Eclipse shows the error message as The method sum(int, int[]) is ambiguous for the type VarargsExample.

java varargs, varargs in java

That’s all about java varargs. It’s good to know feature but you don’t need to use it when writing code yourself.

Reference: Official Documentation

Comments

  1. Moore.Ma says:

    private static class Base {
    void print(String… args) {
    }
    }

    private static class Sub extends Base {
    @Override
    void print(String[] args) {
    }
    }

    Base base = new Sub();
    base.print(“WDNMD”);
    Sub sub = new Sub();
    // compile error
    // sub.print(“WDNMD”);

  2. Moore.Ma says:

    Hi, Pankaj, Thanks for your sharing!

    But I still have some questions, you said that “Once it reaches the last varargs parameter, it creates an array of the remaining arguments and pass it to the method”. But when the args of a method is an array and calling the method via varargs, it compiles failed. For example:

    testVarargs("a", "b");
    void testVarargs(String[] args) { // some code }
    

    I want to know why?

    1. Pankaj says:

      It’s failed because the method is expecting string array but you are passing two strings. Put them inside an array and it will work.

      1. Moore.Ma says:

        all right, thanks.

  3. Adam says:

    Hie Thanks you very much. I am new to java and i hope i will get to learn lot from these lessons.

  4. Priya says:

    varargs is generally known as variable arguments. It uses internal mechanism of eclipse.

  5. siddu says:

    The above program works fine, no compile time error,

    1. omprakash says:

      Hi, in the above overloaded method use “int… js” instead of “Object…js” as 3rd parameter

  6. Larry says:

    Hi Pankaj,

    Thanks for sharing it!!! Well explained about the use of the Java Varargs and how one need to use it without overloading the compiler…This was informative.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages