Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Variable Arguments (Varargs) in Java
Next article icon

Variable Arguments (Varargs) in Java

Last Updated : 23 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, Variable Arguments (Varargs) write methods that can take any number of inputs, which simply means we do not have to create more methods for different numbers of parameters. This concept was introduced in Java 5 to make coding easier. Instead of passing arrays or multiple methods, we can simply use one method, and it will handle all the test cases.

Example: Now, let us see the demonstration of using Varargs in Java to pass a variable number of arguments to a method.

Java
// Java program to pass a variable  // number of arguments to a method import java.io.*;  class Geeks {        // Method that accepts variable number      // of String arguments using varargs     public static void Names(String... n) {                // Iterate through the array          // and print each name         for (String i : n) {             System.out.print(i + " ");          }         System.out.println();      }      public static void main(String[] args) {                // Calling the 'Names' method with          // different number of arguments         Names("geek1", "geek2");                    Names("geek1", "geek2", "geek3");        } } 

Output
geek1 geek2  geek1 geek2 geek3  

Explanation: In the above example, the String... names allows the method to accept a variable number of String arguments. Inside the method, the for-each loop iterates over the names array and prints each name. The method is called twice in main(), with two and three arguments respectively.

What is Varargs?

Varargs lets a method to take many values or even no value at all. Java will treat these values like a list, so that we can use them inside the method easily.

Syntax of Varargs

Internally, the Varargs method is implemented by using the single dimensions arrays concept. Hence, in the Varargs method, we can differentiate arguments by using Index. A variable-length argument is specified by three periods or dots(…). 

public static void fun(int ... a)
{
// method body
}

This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result, here, a is implicitly declared as an array of type int[].

Why do we Need Varargs?

  • Until JDK 4, we can not declare a method with variable no. of arguments. If there is any change in the number of arguments, we have to declare a new method. This approach increases the length of the code and reduces readability.
  • Before JDK 5, variable-length arguments could be handled in two ways.
    • One uses an overloaded method(one for each).
    • Another puts the arguments into an array and then passes this array to the method. Both of them are potentially error-prone and require more code. 
  • To resolve these problems, Variable Arguments (Varargs) were introduced in JDK 5. From JDK 5 onwards, we can declare a method with a variable number of arguments. Such types of methods are called Varargs methods. The varargs feature offers a simpler, better option.

Example: Varargs with Integer Arguments

Java
// Demonstrating the working of  // varargs with integer argument class Geeks {        // A method that takes variable     // number of integer arguments.     static void fun(int... a)     {         System.out.println("Number of arguments: "                            + a.length);          // using for each loop to display contents of a         for (int i : a)             System.out.print(i + " ");         System.out.println();     }      // Driver code     public static void main(String args[])     {         // Calling the varargs method with         // one parameter         fun(100);          // four parameters         fun(1, 2, 3, 4);          // no parameter         fun();     } } 

Output
Number of arguments: 1 100  Number of arguments: 4 1 2 3 4  Number of arguments: 0

Explanation: In the above example, the fun(int... a) method accepts a variable number of integers. The length of the arguments is accessed using a.length. A for-each loop is used to iterate over the arguments and print each value.

Note: A method can have variable length parameters with other parameters too, but one should ensure that there exists only one varargs parameter that should be written last in the parameter list of the method declaration. For example:

int nums(int a, float b, double … c)

In this case, the first two arguments are matched with the first two parameters, and the remaining arguments belong to c.

Example: Varargs with Other Arguments

Java
// Demonstrating the working of  // varargs with other parameters class Geeks{        // Takes string as a argument      // followed by varargs     static void fun2(String s, int... a) {         System.out.println("String: " + s);         System.out.println("Number of arguments is: "                            + a.length);          // using for each loop to          // display contents of a         for (int i : a)             System.out.print(i + " ");          System.out.println();     }      public static void main(String args[])     {         // Calling fun2() with different parameter         fun2("GeeksforGeeks", 100, 200);         fun2("CSPortal", 1, 2, 3, 4, 5);         fun2("forGeeks");     } } 

Output
String: GeeksforGeeks Number of arguments is: 2 100 200  String: CSPortal Number of arguments is: 5 1 2 3 4 5  String: forGeeks Number of arguments is: 0


Important Rules and Limitations

Case 1: Specifying two Varargs in a single method: 

void method(String... gfg, int... q)
{
// Compile time error as there
// are two varargs
}

Note: Only one Varargs parameter is allowed per method.

Case 2: Specifying Varargs as the first parameter of the method instead of the last one: 

void method(int... gfg, String q)
{
// Compile time error as vararg
// appear before normal argument
}

Note: The Varargs parameter must be the last in the parameter list.

Important Points:

  • Vararg Methods can also be overloaded, but overloading may lead to ambiguity.
  • Vararg internally use an array to store arguments.
  • Before JDK 5, variable length arguments could be handled in two ways: One was using overloading, other was using array argument.
  • There can be only one variable argument in a method.
  • Variable argument (Varargs) must be the last argument.

Next Article
Variable Arguments (Varargs) in Java

K

kartik
Improve
Article Tags :
  • Java
  • java-basics
Practice Tags :
  • Java

Similar Reads

    Argument vs Parameter in Java
    Argument An argument is a value passed to a function when the function is called. Whenever any function is called during the execution of the program there are some values passed with the function. These values are called arguments. An argument when passed with a function replaces with those variabl
    2 min read
    Environment Variables in Java
    In Java, Environment variables are widely used by operating systems to deliver configuration data to applications. Environment variables are key/value pairs with both the key and the value being strings, similar to properties in the Java platform. What are Environment Variables in Java?In Java, Envi
    5 min read
    Overloading Variable Arity Method in Java
    Here we will be discussing the varargs / variable arity method and how we can overload this type of method. So let us first understand what a variable arity method is and its syntax. A variable arity method also called as varargs method, can take a number of variables of the specified type. Note: Un
    5 min read
    Rules For Variable Declaration in Java
    Variable in Java is a data container that saves the data values during Java program execution. Every variable is assigned a data type that designates the type and quantity of value it can hold. Variable is a memory location name of the data. A variable is a name given to a memory location. For More
    2 min read
    Unnamed Patterns and Variables in Java
    Java programming language offers multiple features that allow developers to write rich and concise code. Among these features, there are unnamed patterns and variables which enables developers to work with data in a more flexible and elegant way. In this article, we will study about unnamed patterns
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences