Java Varargs

Java Varargs

What are Varargs?

In the Article, we will Discuss about the varargs of java.
Java varargs (variable arguments) is a feature that allows a method to accept a variable number of arguments. With varargs, you can define a method that takes a variable number of arguments of the same type, and call the method with any number of arguments (including zero) of that type.

Java Varargs:

Java Varargs (short for variable-length arguments) is a feature introduced in Java 5 that allows a method to accept a variable number of arguments of the same type. With varargs, you can define a method that takes a variable number of arguments, and call the method with any number of arguments (including zero) of that type.
To define a method that uses varargs, you need to use the ellipsis symbol … after the parameter type in the method signature.

Initializing a Varargs in Java:

Syntax:

public void methodName(Type... varName) {
    // method body
}

Explanation:

  • methodName is the name of the method.
  • Type is the type of the varargs parameter.
  • varName is the name of the varargs parameter.

The … syntax indicates that the method can accept a variable number of arguments of the same type. The varargs parameter is treated like an array, and you can use it like any other array within the method.

Java Program to return sum of two variables using Varargs:

Run
import java.util.*;

public class Main{
  public static void main(String[] args){
      
    // Calling the printNames function
    printNames("John", "Doe");
    
    // Calling the printNames function
    printNames("Mary", "Smith", "Jones");
    
    // Calling the printNames function
    printNames("Bob");
  }

  // printNames Function Definition    
  public static void printNames(String... names){
    // Printing the names  
    System.out.print("Names: ");
    
    for (String name : names) {
      System.out.print(name + " ");
    }
    System.out.println();
  }
}

Output:

Names: John Doe 
Names: Mary Smith Jones 
Names: Bob 

Explanation:

In the above program, we have a printNames method that takes a varargs parameter of type String. The method simply prints out all the names passed to it, separated by spaces.
In the main method, we call printNames with different numbers of arguments. We pass two names, three names, and one name to the method. In each case, the varargs parameter is treated like an array and the method prints out all the names that were passed to it.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription