Methods Accepting a Variable Number of Objects in Java



A method that accepts a variable number of Object arguments in Java is a form of variable length arguments(Varargs). These can have zero or multiple Object type arguments.

A program that demonstrates this is given as follows:

Example

 Live Demo

public class Demo {
   public static void Varargs(Object... args) {
      System.out.println("\nNumber of Object arguments are: " + args.length);
      System.out.println("The Object argument values are: ");
      for (Object i : args)
      System.out.println(i);
   }
   public static void main(String args[]) {
      Varargs("Apples", "4", "All");
      Varargs("Half of", 3, "is", 1.5);
   }
}

Output

Number of Object arguments are: 3
The Object argument values are:
Apples
4
All
Number of Object arguments are: 4
The Object argument values are:
Half of
3
is
1.5

Now let us understand the above program.

The method Varargs() in class Demo has variable-length arguments of type Object. 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(Object... args) {
   System.out.println("\nNumber of Object arguments are: " + args.length );
   System.out.println("The Object argument values are: ");
   for (Object i : args)
   System.out.println(i);
}

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

public static void main(String args[]) {
   Varargs("Apples", "4", "All");
   Varargs("Half of", 3, "is", 1.5);
}
Updated on: 2019-07-30T22:30:24+05:30

560 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements