×
☰ See All Chapters

Variable Argument (Varargs)

Varargs is used to simplify method overloading. It is generally used when you want to send multiple values of the same type as argument. One method can have only one vararg and it should be the last in the parameter list. Varargs can be applied to main method and constructor also.

Varargs Syntax

Access_specifier  Non_Access_specifier   returntype   methodName (type1 pmtr1, type2 pmtr2, datatype... var)

{

        //Method body

        return exp;|return;

}

 

Varargs Example

package com.java4coding;

 

public class VarargsDemo {

       

        public static void main(String... args) {

                System.out.println("www.java4coding.com");

        }

       

        void meth(String s, int... a) {

                for (int x : a) {

                        System.out.println(x);

                }

        }

 

}

 

Overloading Vararg Methods

We can overload a method that takes a variable-length argument. For example, the following program overloads vaTest( ) three times:

java-varargs-0
 

All Chapters
Author