Java | var-args methods

Mahesh Annamalai
1 min readAug 5, 2021

--

A wonderful feature introduced in java version 1.5

var-args methods (variable number of arguments methods)

In Java version 1.5, Java has included a feature that simplifies the creation of methods that need to take a variable number of arguments. A method that takes a variable number of arguments is a var-args method.

Prior to Java version 1.5, it could be handled bytwo ways. One using overloaded method(one for each) and another put the arguments into an array, and then pass this array to the method. Both of them are potentially error-prone and require more code. The varargs feature offers a simpler, better option.

Prior to Java version 1.5

Here we need to overload the methods to perform the sum operations for different number of arguments. It requires more code.

From Java version 1.5

To solve the above problem, Java comes with var-args method.

Defining var-args method → func(int… x)

JVM internally converts the arguments and stores it in an array. Hence we can access the passed values by indexing.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Mahesh Annamalai
Mahesh Annamalai

Written by Mahesh Annamalai

Student at University of Texas at Dallas

No responses yet

Write a response