- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Explain about Varargs in java?
Since JSE1.5 you can pass a variable number of values as argument to a method. These arguments are known as var args and they are represented by three dots (…)
Syntax
public myMethod(int ... a) { // method body }
Example
In the following example, the method named sample() accepts varargs (of type String) and from the main method, we are invoking this method multiple times by passing a different number of arguments each time we invoke it.
public class VarargsExample{ void sample(String... args) { for (String arg: args) { System.out.println(arg); } } public static void main(String args[] ){ VarargsExample obj = new VarargsExample(); obj.sample("Ram", "Rahim", "Robert"); obj.sample("Krishna", "Kasyap"); obj.demoMethod("Vanaja"); } }
Output
Ram Rahim Robert Krishna Kasyap Vanaja
When to use − Whenever, you want to pass different number of arguments each time you call a method you should use vararg methods.
Example
In the following example the sample() method accepts varargs of type integer and from the main method we are invoking this method multiple times and, we are passing different number of integer arguments each time we invoke it.
public class VarargsExample{ void demoMethod(int... args) { for (int arg: args) { System.out.println(arg); } } public static void main(String args[] ){ VarargsExample obj = new VarargsExample(); obj.demoMethod(1101, 10225, 26); obj.demoMethod(22365, 12); obj.demoMethod(1); } }
Output
1101 10225 26 22365 12 1
- Related Articles
- Overloading Varargs Methods in Java
- Explain about field hiding in java?
- Using Varargs with standard arguments in Java
- Convert Kotlin Array to Java varargs
- Method Overloading and Ambiguity in Varargs in Java
- Variable Arguments (Varargs) in C#
- Explain about StringJoiner in java8?
- Explain about derivatives in finance.
- What are the rules to be followed while using varargs in java?
- Explain about financial strategy.
- Explain about Transfer pricing
- Explain about bitwise operators in JavaScript?
- Explain about financial system in India.
- Explain about modelling in financial management.
- Explain about forecasting in financial management.

Advertisements