Week 15 — What are Varargs in Java?

Question of the Week #15
What are Varargs in Java?
6 Replies
dan1st | Daniel
A Java feature called Varargs (variable-length arguments) enables a method to accept any number of arguments of the same type. It gives methods that need to handle a range of arguments flexibility and gets rid of the necessity to overload methods to handle variable quantities of arguments. Varargs are declared in Java by following the type of the final parameter in a method declaration with three dots ('...')
Submission from SATANGAMER451#9942
dan1st | Daniel
With varargs, it is possible to create a method that accepts an arbitrary number of parameters of the same type. When creating a method with a vararg, ... needs to be added after the type of the parameter. This is only possible for the last parameter of a method. For example, take the following method:
public String concat(String... toConcat){//note the String... here
StringBuilder sb = new StringBuilder();
for(String toAppend:toConcat){
sb.append(toAppend);
}
return sb.toString();
}
public String concat(String... toConcat){//note the String... here
StringBuilder sb = new StringBuilder();
for(String toAppend:toConcat){
sb.append(toAppend);
}
return sb.toString();
}
This method can be called like concat() which returns an empty String. But it can also be called using any number of Strings as arguments. For example, concat("Hello ","World") returns "Hello World".
dan1st | Daniel
Varargs are passed as arrays. So, the parameter String... toConcatis semantically equivalent to String[] toConcat. It is also possible to pass arrays directly to the method, e.g. concat(new String[]{"Hello ", "World"}). Inside the method, it is also possible to access the vararg like an array:
public String concat(String... toConcat){
StringBuilder sb = new StringBuilder();
for(int i=0;i<toConcat.length;i++){
sb.append(toConcat[i]);
}
return sb.toString();
}
public String concat(String... toConcat){
StringBuilder sb = new StringBuilder();
for(int i=0;i<toConcat.length;i++){
sb.append(toConcat[i]);
}
return sb.toString();
}
⭐ Submission from dan1st#7327
dan1st | Daniel
Varargs are a special kind of argument that accept several elements without having to explicitly define them, eg. void foo(String... bar) will accept foo("a", "b", "c", "etc"); and anything in between. The bar argument in foo will then be a String array, containing all the elements passed into the vararg, that being "a", "b", "c" and "etc" in this case. passing in a string array into the vararg will pass the string array along, -> foo(new String[4]) will pass in a string array of length 4 with all elements set to null as bar, without the vararg effect. Varargs can appear only at the end of the argument list, anything else is illegal. Examples:
void simpleVararg(String... messages) {
System.out.println(Arrays.toString(messages));
}
simpleVararg("hello", "world");
simpleVararg(new String[] {"hello", "world"});

void complexVararg(String a, int... numbers) {
System.out.println(a);
for(int i : numbers) {
System.out.println(i);
}
}
complexVararg("hello", 123, 456, 678);

void illegalDefinition(Object... objects, String message) {} // won't compile; vararg not at last argument slot
void simpleVararg(String... messages) {
System.out.println(Arrays.toString(messages));
}
simpleVararg("hello", "world");
simpleVararg(new String[] {"hello", "world"});

void complexVararg(String a, int... numbers) {
System.out.println(a);
for(int i : numbers) {
System.out.println(i);
}
}
complexVararg("hello", 123, 456, 678);

void illegalDefinition(Object... objects, String message) {} // won't compile; vararg not at last argument slot
⭐ Submission from 0x150#9699
dan1st | Daniel
VarArgs (short for variable [number of] arguments) is a way of defining a method parameter that allows you to pass an arbitrary number of the same type of object to a method. These "endless parameters" are later turned into an array on the receiving end if there are multiple, but to the caller it is as though you can use as many parameters as you want. A VarArgs parameter must be the last parameter of a method, and is declared with the following syntax: Type.... For example:
public void foo(String... strings) {
// code
}
private String bar(int x, int y, double... weights) {
// code
}
public void foo(String... strings) {
// code
}
private String bar(int x, int y, double... weights) {
// code
}
You can call a VarArgs method using standard syntax. For example:
foo("string");
foo("string1", "string2", "string3", "string4");
bar(0, 1, 0.5, 2.0, 4.8)
foo("string");
foo("string1", "string2", "string3", "string4");
bar(0, 1, 0.5, 2.0, 4.8)
Common examples include List.addAll(Object... elements) and Strings.join(String delimiter, String... items). Since any VarArgs call with multiple arguments is turned into an array on the receiving end, you are also able to pass in an array of the specified type when calling the method if desired, such as:
String[] arr = new String[2];
arr[0] = "string1";
arr[1] = "string2";
foo(arr);
String[] arr = new String[2];
arr[0] = "string1";
arr[1] = "string2";
foo(arr);
To note when writing a VarArgs method: VarArgs parameters - for this example we'll use Object... - can come in the form of either the singular Object or the array Object[] depending on how many arguments are used in the method invokation. To ensure that the parameter always comes in the form of an array - even when passed a single value - use the @SafeVarArgs annotation on the method. Otherwise, use instanceof checks to determine the type of the parameter. Example:
public void unsafeMethod(String... strings) {
if (strings instanceof String[]) {
// Act on array
} else {
// Act on a `String` or `null` value
}
}

@SafeVarArgs
public void safeMethod(String... strings) {
// strings can only be `null` or of type `String[]`
}
public void unsafeMethod(String... strings) {
if (strings instanceof String[]) {
// Act on array
} else {
// Act on a `String` or `null` value
}
}

@SafeVarArgs
public void safeMethod(String... strings) {
// strings can only be `null` or of type `String[]`
}
Submission from Haiku#1184
dan1st | Daniel
Varargs, short for variable-length arguments, is a feature in Java that allows a method to accept a variable number of arguments. This feature was introduced in Java 5. In Java, you can define a method with varargs by using three dots ... after the type of the last argument in the method's parameter list. for example public void printValues(String... values) { for (String value : values) { System.out.println(value); } } Here, the parameter values is a varargs parameter that allows the method to accept any number of String arguments. Now I can print how much values I want printValues("apple", "banana", "cherry"); //this prints apple banana and cherry printValues(); //this prints nothing
⭐ Submission from Karolus#1973
Want results from more Discord servers?
Add your server