Using Varargs with standard arguments in Java

A method with variable length arguments(Varargs) in Java can have zero or multiple arguments. Variable length arguments(Varargs) can also be used with standard arguments However they must be the last argument in the argument list. Moreover, there can only be one variable length argument in the method.

A program that demonstrates this is given as follows:

Example

Live Demo

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

Output

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

Number of Vararg are: 0
The argument values are:

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

Now let us understand the above program.

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

public static void Varargs(int i, String... str) {
System.out.println("Number of Vararg are: " + i );
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(3, "Apple", "Mango", "Pear");
Varargs(0);
Varargs(1, "Magic");
}
Vikyath Ram

A born rival