Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
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);
} Advertisements
