Welcome to Java and varargs (short for variable arguments). In a situation where it is needed to pass in an variable amount of arguments to a method, varargs is a good answer.
Some portions of this article are the same as this one: C# params. This is because they are both written by me and cover very similair topics. The code in both examples has the same idea. This is done to create a consistency for both articles. With that in mind lets continue.
Before we get to the code there are a couple things to keep in mind.
- The varargs parameter needs to be the last in line;
- Only one vararg parameter is allowed.
The basic syntax is as follows:
1
| public void methodName(parameterType... parameterName){} |
Notice the three dots behind parameterType. This is to tell the compiler that you want to use variable arguments. So what does the compiler in the background? It gathers all of the values and puts them into an array. The type of params can be anything. You can change it to string, bool, Object, user defined object and more. To read the values just use the normal array methods.
In the example code i created two methods. One for printing int values and the other for printing string values. Perhaps not a realistic example but i wanted to keep this short and simple. Also note that i pass in both an array of strings and one or more strings separated by a comma.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
| public class test { public static void main(String[] args) { printString( "One var input" ); String[] array = new String[ 3 ]; array[ 0 ] = "array input #1" ; array[ 1 ] = "array input #2" ; array[ 2 ] = "array input #3" ; printString(array); printString( "Two var input #1" , "Two var input #2" ); printIntegers( 1 ); printIntegers( 2 , 3 , 4 ); printIntegers( 633 , 7474 , 74345 , 52432 ); } public static void printIntegers( int ...params) { String temp = "" ; for ( int s : params) { temp += s + " | " ; } System.out.println(temp); } public static void printString(String... params) { String temp = "" ; for (String s : params) { temp += s + " | " ; } System.out.println(temp); } } |
The output is as follows:
Comments
Post a Comment