
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
public class Demo { public static void Varargs(String... str) { System.out.println("\nNumber 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("\nNumber 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"); }
Advertisements