Demonstrating variable-length arguments in Java


A method with variable length arguments(Varargs) in Java can have zero or multiple arguments. Variable length arguments are most useful when the number of arguments to be passed to the method is not known beforehand. They also reduce the code as overloaded methods are not required.

A program that demonstrates this is given as follows:

Example

 Live Demo

public class Demo {
   public static void Varargs(String... str) {
      System.out.println("
Number of arguments are: " + str.length);       System.out.println("The argument values are: ");       for (String s : str)          System.out.println(s);    } public static void main(String args[]) { Varargs("Apple", "Mango", "Pear"); Varargs(); Varargs("Magic"); } }

Output

Number of arguments are: 3
The argument values are:
Apple
Mango
Pear

Number of arguments are: 0
The argument values are:

Number of arguments are: 1
The argument values are:
Magic

Now let us understand the above program.

The method Varargs() in class Demo has variable-length arguments of type String. This method prints the number of arguments as well as their values. A code snippet which demonstrates this is as follows:

public static void Varargs(String... str) {
   System.out.println("
Number of arguments are: " + str.length ); System.out.println("The argument values are: "); for (String s : str) System.out.println(s); }

In main() method, the method Varargs() is called with different argument lists. A code snippet which demonstrates this is as follows:

public static void main(String args[]) {
   Varargs("Apple", "MAngo", "Pear");
   Varargs();
   Varargs("Magic");
}

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements