BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java Varargs explained with examples

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

Varargs is a term used for variable arguments. In this guide, you will learn what is varargs, how to use it in Java and various examples to understand this concept in detail.

What is varargs?

Varargs is used when you are not sure how many arguments a method can accept. For example, let say you are writing a java program to calculate the sum of input integers, this program contains several sum() methods with different number of arguments.

sum(int a, int b); //to find the sum of two integers
sum(int a, int b, int c); //to find the sum of three integers
sum(int a, int b, int c, int d); //to find the sum of four integers.
...
so on

This is called method overloading. We are not sure how many integers the user will pass while calling the method so we have created various variations of this method using method overloading.

The other simple way of doing the same thing would be using the varargs like this:

sum(int... args);

There are three dots(…) used just after data type and before the parameter name. These dots represents that the args is not a normal argument rather a variable argument (varargs). Now even if the user pass 100 integers while calling the sum method, this same method will serve the user.

Let’s look at the complete example to understand the usage of varargs in java:

Java Program without using varargs

In this program, we are not using varargs, instead we are using method overloading to cover the different number of arguments this method can accept.

public class JavaExample {

  public int sum(int a, int b){
    return a+b;
  }

  public int sum(int a, int b, int c){
    return a+b+c;
  }
  public int sum(int a, int b, int c, int d){
    return a+b+c+d;
  }

  public static void main( String[] args ) {
    JavaExample obj = new JavaExample();
    System.out.println(obj.sum(10, 15));
    System.out.println(obj.sum(10, 15, 20));
    System.out.println(obj.sum(10, 15, 20, 25));
  }
}

Output:

25
45
70

The issue with the above program:
Although the above program runs fine, however there is a limit in the above program. User cannot calculate the sum of more than four integer numbers.

This issue can be easily solved using varargs:

The same program using varargs

public class JavaExample {

  public int sum(int... args){
    int sum = 0;

    //running a loop to add all numbers.
    for(int num: args){
      sum = sum+num;
    }
    return sum;
  }

  public static void main( String[] args ) {
    JavaExample obj = new JavaExample();
    System.out.println(obj.sum(10, 15));
    System.out.println(obj.sum(10, 15, 20));
    System.out.println(obj.sum(10, 15, 20, 25));
    //calculating sum of 7 numbers
    System.out.println(obj.sum(2, 2, 2, 2, 2, 2, 2));
    //calculating sum of 10 numbers
    System.out.println(obj.sum(2, 4, 6, 8, 10, 12, 14, 16, 18, 20));
  }
}

Output:

25
45
70
14
110

As you can see in this program, we didn’t have to care about the number of integers that we can pass to the sum() method. This is because varargs can handle any number of arguments.

How varargs works in Java?

Let’s look at the declaration of method with varargs parameter:

public int sum(int... args){
   //statements
}

The three dots ... instructs the compiler that args is not a normal argument, rather it is a variable argument. The compiler internally creates an array with name args (args[]), the data type of the array is same as the type of args, which is int in the above code snippet.

So for the above method sum(), the compiler internally declared an array args[] with the data type int.

The compiler then set the size of the array based on the arguments. If you are calling the sum method like this: sum(10, 20, 30) then compiler set the size of args as 3.

When to use varargs in Java

The varargs is not suitable for all scenarios. You should use varargs in the following scenarios:

1. If you are not sure how many arguments, a user can pass while calling the method.

2. If you expect the method argument to work like an array.

The popular example of this is predefined method in String class, which is String.format() method. This method accepts any number of arguments.

String.format("My number: %d", num);
String.format("My number: %d and my string: %s", num, str);

Method overloading for the methods with Varargs parameter

We can overload a method with varargs parameter as shown below. Here we have overloaded a method sum(). The first variation of this method accepts variable int arguments and prints the sum of them. The second variation of method sum() accepts, variable string arguments and prints the concatenated string.

class JavaExample {

  public void sum(int... num){
    int sum = 0;
    for (int i: num) {
      sum += i;
    }
    System.out.println( sum);
  }

  public void sum(String... str){
    String str2 = "";
    for (String s: str) {
      str2 = str2.concat(s);
    }
    System.out.println(str2);
  }

  public static void main( String[] args ) {
    JavaExample obj = new JavaExample();
    System.out.print("Output of int varargs method: ");
    obj.sum(10, 20, 39);
    System.out.print("Output of String varargs method: ");
    obj.sum("Beginners", "Book", ".com");
  }
}

Output:
Output varargs example

Rules to remember regarding Varargs

1. Only one Varargs parameter:
A method signature can have only one varargs parameter, multiple varargs parameters are not allowed. For example, the following method declaration is not valid.

void sum(int a, int... num1, int... num2){
   //statements
}

You will get the following error:
Multiple vararg-parameters are prohibited

2. Varargs should always be the last parameter while declaring a method:
For example:
Invalid method declaration: Here, the compiler will not be able to comprehend which value should be assigned to parameter a as the num1 can accept any number of arguments.

void sum(int... num1, int a){
  //statements
}

Valid method declaration: In this case, compiler is sure that the first argument should be assigned to a and rest can be assigned to varargs num1.

void sum(int a, int...num1){
  //statements
}

Recommended Posts

  • Java 9 – @SafeVarargs Annotation with examples
  • Java main() method explained with examples
  • Method Overloading – Passing Null values
  • Method Overriding in Java
  • Java Program to perform Arithmetic operation using Method Overloading
❮ Java Programming

Top Related Articles:

  1. Method Overloading “Reference is Ambiguous” error in Java
  2. Ambiguity error while overloading Method with Varargs parameter
  3. Java Integer byteValue() Method
  4. Deque Interface in Java Collections
  5. Java StringBuffer setLength() Method

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap