Top 3 Examples of variable arguments or varargs feature in java

Variable Arguments feature in java

timers in java example

Varargs Feature in java

Variable arguments feature is one of java language feature introduced in Java 5. Java 5 introduced a lot of new features like Enum feature[] etc.

method have multiple arguments, this arguments count are fixed, with Variable arguments feature in java5, the method can have multiple arguments(zero to many) to be passed without defining a number of arguments by specifying variable argument syntax. variable arguments are specified in method definition by an ellipse (…).

Before Varargs feature or prior to Java 1.5:-

prior to Java 1.5 version, developers have no choice of variable arguments supplied but we

Java has a feature of method overloading in which the same method can have different versions with changing arguments.

Advantages of Varargs feature:-

variable declaration not required at compile time or runtime.
Clients have free control over passing variable arguments to Service API methods
backward compatibility support for prior java versions

Variable argument syntax

We have to declare a DataType … arguments in the method declaration

public void method(DataType … arguments)

arguments are followed by ellipse … the meaning method accepts at least zero arguments to multiple arguments

Rules for Variable arguments

1. Varargs can be combined with other normal arguments.
2. Only one varargs in any method declaration
3. if there is a combination of varargs and normal arguments, varargs declaration should be defined at last

JVM Execution for varargs:-

when the variable argument is declared in the method, java compiler of JVM loads that method and create an array of arguments of Data type

Varargs Simple example

package com.cloudhadoop.varargs;

public class VarargsExample {

static void print(String… words) {
String sentence = null;
for (String word : words) {
sentence = sentence + word;
System.out.println(" " + sentence);

public static void main(String[] args) {
print(“Hi”, “How “, “are”, “You”);


and output is:- Hi How are you

Iteration of Variable arguments in java example

Variable arguments variable name is a reference to an array of argument type. so we can use for each loop to iterate variable arguments

static void print(String… words) {
String sentence = null;
for (String word : words) {
sentence = sentence + word;

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.