English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Java Other Topics

Java Variable Arguments (Varargs)

In this article, you will learn about variable arguments (Varargs) in Java through examples. You will also learn when to use varargs and when not to use them.

What is varargs in Java?

Suppose you are creatingJava Methods. But you are not sure how many arguments your method will accept. To solve this problem, Java 1.5Varargs have been introduced.

Varargs is an abbreviation for variable arguments. In Java, a method's parameters can accept any number of values. A parameter that can accept a variable number of values is called varargs.

The syntax for implementing varargs is as follows:

accessModifier methodName(datatype… arg) {
    // Method Body
}

To define a vararg, use the ellipsis (...) in the method's parameter list.

A method that accepts a variable number of arguments is called a variable-argument method, or simply a varargs method.

First, let's look at an example without using varargs:

class NoVararg {
    public int sumNumber(int a, int b){
        return a+b;
    }
    public int sumNumber(int a, int b, int c){
        return a+b;+c;
    }
    public static void main(String[] args) {
        NoVararg obj = new NoVararg();
        System.out.println(obj.sumNumber(1, 2));
        System.out.println(obj.sumNumber(1, 2, 3));
    }
}

When you run the program, the output will be:

3
6

As you can see, you must overload the sumNumber() method to make it applicable for3arguments.

if the user wants to add5a number or10Or10What should we do if there are 0?

Using varargs can handle this issue in a concise way. Let's look at a code example:

Example: Demonstration of variable arguments

class VarargExample {
    public int sumNumber(int ... args){
        System.out.println("Parameter length: " + args.length);
        int sum = 0;
        for(int x: args){
            sum +=" + x;
        }
        return sum;
    }
    public static void main(String[] args) {
        VarargExample ex = new VarargExample();
        int sum2 =" + ex.sumNumber(2, 4);
        System.out.println("sum2 =" + sum2);
        int sum3 =" + ex.sumNumber(1, 3, 5);
        System.out.println("sum3 =" + sum3);
        int sum4 =" + ex.sumNumber(1, 3, 5, 7);
        System.out.println("sum4 =" + sum4);
    }
}

When running the program, the output is:

Parameter Length: 2
sum2 = 6
Parameter Length: 3
sum3 = 9
Parameter Length: 4
sum4 = 16

Here, the sumNumber() method returns the sum of the int parameters passed to it (irrespective of the number of parameters passed).

As you can see, varargs are very useful in some cases. However, if you are sure about the number of parameters passed to the method, please use method overloading instead. For example, if you are sure that the sumNumber() method is only used to calculate2or3The sum of the total number of parameters, please use overloading like the first example.

Let's take another example. The format() method defined in the Java library accepts varargs. In JDK, the format() method is defined as follows:

public static String format(Locale l, String format, Object... args) {
    // body
}

Example: format() Method

class Company {
    public static void main(String[] args) {
        String siteName = "oldtoolbag.com";
        int empCount = 6;
        String type = "Tutorial Website";
        System.out.println(
                String.format(
                        "Site Name : %s, Emp Count: %d Type: %s"
                        siteName, empCount, type
                )
        );
    }
}

When running the program, the output is:

Site Name : oldtoolbag.com, Emp Count: 6 Type: Tutorial Website

How do variable arguments work in the background?

Let's look at the following pseudocode:

public int sumNumber(int ...nums) {
    // Method Body
}

... syntax tells the Java compiler that zero or more parameters can be used to call this method. As a result, the nums variable is implicitly declared as an int [] typeArray. Therefore, within the method, use array syntax to access the nums variable.

If there are no parameters, the length of nums is 0.

Overloading Varargs Methods

Similar to typical methods, you can overload vararg methods.

Example: Varargs Method Overloading

class VarargOverload {}}
    private void test(int ... args){
        int sum = 0;
        for (int i: args) {
            sum += i;
        }
        System.out.println("sum = ", + sum);
    }
    private void test(boolean p, String ... args){
        boolean negate = !p;
        System.out.println("negate = ", + negate);
        System.out.println("args.length = ",+ args.length);
    }
    public static void main(String[] args) {
        VarargOverload obj = new VarargOverload();
        obj.test(1, 2, 3);
        obj.test(true, "hello", "world");
    }
}

When running the program, the output is:

sum = 6
negate = false
args.length = 2

In the above program, the test() method is overloaded by changing the number of parameters it accepts.

Things to remember when using Varargs

Here are a few things to remember when using Java Varargs:

1Be sure to define the method signature correctly when using Java Varargs:ReservedFinally, varargs.

Variable arguments must be the last parameter passed to the method. Consider, you called the following doSomething() method:

doSomething(1, 2, 3, 4);

And, your doSomething() method is defined as:

//Incorrect method declaration
public void doSomething(int ... nums, int p){
    // method body
}

In this case, the compiler cannot determine the number of parameters passed to nums.

However, if the method is defined as:

public void doSomething(int p, int ... nums) {
    // method body
}

The Java compiler assigns the first parameter to p, and the remaining int parameters to nums.

2A method can have only one varargs parameter.

For example, the method declaration is incorrect:

int doSomething(int p, float ... floatNums, double ... doubleNums) {
    // code
}

Ambiguity in Varargs Method Overloading

Let's look at such an overloaded test() method:

class Demo { 
  
    static void test(int ... vargs) {
        // method body
    }
    
    static void test(int n, int ... vargs) {
        // method body
    }
}

In the above program, even if you try to call the test() method, even if the test() method is overloaded and accepts a different number of parameters, the compiler may be confused.

The compiler does not know which method to call. The compiler may think that you are trying to call test(int ... vargs) using a varargs parameter. Similarly, the compiler may think that you are trying to call test(int n, int ... vargs) using the parameters passed to the first argument, while the second argument is empty.

Due to two possibilities, ambiguity may arise. Therefore, you may need to use two different method names instead of overloading varargs methods.