VarArgs in Java Tutorial for Beginners

In Java varargs is a unique concept. This tutorial helps students learn varargs (variable arguments) in Java in an easy way. Let us learn about the main reason behind the origin.
  • What will happen if you don't know how many arguments you need to pass to a method?
  • What will happen if you want to pass unlimited variables to a method?
There is an answer for these questions in Java. It is simple, and there is varargs. Using this concept you can send as many as parameters of the same type without any restriction. An example will give you a better understand.

Normal Method


public void MyMeth(int a,int b){....}


VarArg Method


public void MyMeth(int... a) {....}


Explanation

The normal method above takes no more than 2 parameters of int type.
The varargs method takes as many number of parameters as you give of int type only*

As discussed earlier, the use of varargs is this one. You cannot write as many as parameters for a method and also if you do, you must ensure that values to every parameter is sent when you make the method call. This is a drawback of the normal methods but not for the varargs method not only in Java but in any programming language.

Not only for primitive types, varargs in java is applicable for classes also. Simply, applicable for all kinds of parameters.

How it works?

In the above varargs method, parameter acts as an int array with a reference name a. To check this, you can call the length property of the arrays and that works.

Varargs is not just a simple concept in Java, it is highly important at critical times for the developers. This tutorial demonstrates the main part necessary for developers to fire. You'll have to note that not only in Java but C/C++ do support varargs. This feature in Java is implemented from Java 5 (Java 1.5) version.

+ Next VarArgs for Integer

No comments: