Important Java Concept

Variable Argument (Varargs) in Java

The … parameter in Java is called as varArgs that means variable-length Arguments. These varArgs were introduced in JDK [Java (Standard Edition) Development Kit] version 5.
The usage of varArgs is more beneficial when it is not certain how many arguments are needed to be passed.

Syntax

 return_type  method_name(data_type… variable name){

 //code
  
}

Following java codes help understand the usage of varArgs more deeply.

A simple example for varArgs in Java

class Main {
          static void varArgs(String...values) {
             for (String s: values) {
                System.out.print(s + " ");
             }
          }
public static void main(String[] args) {
             varArgs("Hello", "everyone", "this", "is", "aniket", "malik");
             }
         }

Output:

Hello everyone this is aniket malik

Explanation:

In the above block of code, we have created a method varArgs which takes strings as arguments, and also varArgs (…) is used inside this method. We didn’t define how many strings we are giving as input, this is one of the advantages of the varArgs parameter, and inside the main method, the varArgs method is called.

Using varArgs with multiple arguments

class Main {
          static void varArgs(int a, String...values) {
             System.out.print(a + " ");
             for (String s: values) {
                System.out.print(s + " ");
                 }
          }
public static void main(String[] args) {
             varArgs(1, "Hello", "everyone", "this", "is", "aniket", "malik");
             }
       }

Output:

1 Hello everyone this is aniket malik

Explanation:

The above code is similar to that of previously used code, the difference is we have added a new data type as an argument inside the varArgs method. This is a valid declaration using the varArgs parameters whereas varArgs(int… a, String… values) is an invalid declaration and varArgs(int… a , String values) is also a invalid declaration.

Rules for varArgs:

➤ There should be only one variable argument in the method.
➤ The variable argument must be the last argument.

Conclusion

 In this article, we have learned about what is varArgs parameters, where and when to use varArgs parameter, a detailed explanation for varArgs parameters using java, and rules for varArgs parameters.

Do you want

Java Tutor?

Aniket Malik

Aniket Malik

ORACLE CERTIFIED JAVA TUTOR

🟢 Oracle Certified Java Expert

🟢 300 + ⭐ ⭐ ⭐ ⭐ ⭐

🟢 B.tech & M.tech in CSE

🟢 6+ Years of Teaching Experience

🟢 Worked as SE in Virtusa and Digidez

Do you want

Java Tutor?