HomeContact

How to use Java variable arguments

Published in Java
May 22, 2023
1 min read

Variable arguments (varargs) refer to grammar that dynamically accepts arguments and functions regardless of the number of values entering the parameter.

For example, suppose you have a print() method with an inconsistent number of parameters, such as.

print("apple");
print("apple", "grape");
print("apple", "grape", "banana");
print("apple", "grape", "banana", "peach");
print("apple", "grape", "banana", "peach", "mango");

The method of configuring a method in which multiple parameters can be entered can be typically handled by method overloading.

However, it can be said that it is variable and not very efficient to overload and implement methods daily when there are not certain parameters to be passed on, where varargs exerts force.

Variable arguments can dynamically receive parameters because they are accepted and processed as an array as a whole. Thanks to this, it is possible to process the method at once without overloading it n times.

Variable arguments have been added since JDK 1.5, and in Java, the System.out.printf() method is a representative method using variable factors.



🌱How to use variable arguments

Type in method parameter type… It can be used if it is treated as a variable life.

Variable arguments can contain 0 to n transfer factors. The values handed over to the parameters are then collected and processed into an array at compile time. It should be noted that there is no limit to the number of factors, but the array data type depends on what is specified as a parameter type.

public static void main(String[] args) {
print("apple");
print("apple", "grape");
print("apple", "grape", "banana");
print("apple", "grape", "banana", "peach");
print("apple", "grape", "banana", "peach", "mango");
}
public static void print(String... str) {
// The variable argument, the str parameter, is taken as the String[] array type.
for(String s : str) {
System.out.print(s + ", ");
}
System.out.println();
}


If a parameter receives parameters other than variable factors, it must be defined so that the variable factor is placed at the end of the method parameter.

And in the order in which the parameters are handed over, the factors are handed over one by one from the preceding parameter, and the remaining factors are handed over to the variable factor.

public static void main(String[] args) {
print(1, true, "apple", "grape", "banana");
}
// If there are multiple parameters, the variable factor (varargs) must be last
public static void print(int num, boolean bool, String... str) {
System.out.println("number : " + num);
System.out.println("bool : " + bool);
System.out.println("rest parameters : " + Arrays.toString(str));
}

Tags

#Java#java.lang

Share


Previous Article
Using the StartsWith Method in Java in the String

Topics

Java
Other
Server

Related Posts

How to use BigInteger in Java - 2
May 31, 2023
1 min