- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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"); }
- Related Articles
- Variable Arguments (Varargs) in C#
- Overloading Varargs Methods in Java
- Explain about Varargs in java?
- What are the rules to be followed while using varargs in java?
- Convert Kotlin Array to Java varargs
- Method Overloading and Ambiguity in Varargs in Java
- Command line arguments in Java
- Java command line arguments
- What are variable arguments in java?
- Demonstrating variable-length arguments in Java
- Can you have a method in Java with varying number of arguments?
- Explain Java command line arguments.
- Command Line arguments in Java programming\n
- How to implement a constructor reference with one or more arguments in Java?
- What are wildcards arguments in Generics In Java?
