Top 3 Examples of variable arguments| varargs feature in java
java variable arguments in methods: Learn with syntax and examples.
What are Variable Arguments in java
Variable arguments
feature is one of the java language feature introduced in Java5
.
Java5 introduced a lot of new features like the Enum
feature[] etc.
Before Java5, methods can have multiple arguments, but the number of arguments is fixed.
With Java5, the method can have multiple parameters (zero to many) to be supplied without having to define many arguments by specifying variable argument syntax
.
An ellipse
(…) is used to specify variable arguments in method definitions.
Java has a feature of method overloading in which the same method can have different versions with changing arguments.
Varargs Advantages in java
- variable declaration not required at compile time or runtime.
- Clients have complete flexibility over sending variable arguments to Service API methods, and older Java versions are supported.
Variable argument syntax:
We have to declare DataType and … arguments in the method declaration.
public void method(DataType … arguments)
The ellipsis(…) follows just after arguments. As a result, this method accepts a minimum of zero arguments and a maximum of multiple arguments.
Variable arguments Rules:
1. Varargs
can be combined with other normal arguments. 2. Only one varargs
in any method declaration 3. If there are both varargs
and standard arguments, the varargs
declaration should come last.
How JVM Execution for varargs
when the variable argument is declared in the method, the java compiler of JVM loads that method and create an array of arguments of Data type
Varargs Simple example
package com.cloudhadoop.varargs;
public class VarargsExample {
static void print(String... words) {
String sentence = null;
for (String word : words) {
sentence = sentence + word;
}
System.out.println(" " + sentence);
}
public static void main(String[] args) {
print("Hi", "How ", "are", "You");
}
}
output:
Hi How are you
How to iterate Variable arguments in java example
Variable arguments variable name is a reference to an array of argument of the specified type. therefore, we can use use for loop to iterate variable arguments.
public class VarargsExample {
static void print(String... words) {
String sentence = null;
for (String word : words) {
sentence = sentence + word;
}
public static void main(String[] args) {
print("Hi", "How ", "are", "You");
}
}
Conclusion
In this tutorial, learned variable arguments with examples for How to iterate Variable arguments in java example How JVM Execution for varargs rules advantages.