For example, Java's own String.format()
supports a variable number of arguments.
String.format("Hello %s! ABC %d!", "World", 123);
//=> Hello World! ABC 123!
How can I make my own function that accepts a variable number of arguments?
Follow-up question:
I'm really trying to make a convenience shortcut for this:
System.out.println( String.format("...", a, b, c) );
So that I can call it as something less verbose like this:
print("...", a, b, c);
How can I achieve this?
This question is related to
java
function
methods
overloading
The variable arguments must be the last of the parameters specified in your function declaration. If you try to specify another parameter after the variable arguments, the compiler will complain since there is no way to determine how many of the parameters actually belong to the variable argument.
void print(final String format, final String... arguments) {
System.out.format( format, arguments );
}
Take a look at the Java guide on varargs.
You can create a method as shown below. Simply call System.out.printf
instead of System.out.println(String.format(...
.
public static void print(String format, Object... args) {
System.out.printf(format, args);
}
Alternatively, you can just use a static import if you want to type as little as possible. Then you don't have to create your own method:
import static java.lang.System.out;
out.printf("Numer of apples: %d", 10);
You can pass all similar type values in the function while calling it. In the function definition put a array so that all the passed values can be collected in that array. e.g. .
static void demo (String ... stringArray) {
your code goes here where read the array stringArray
}
This is just an extension to above provided answers.
Clearly explained here and rules to follow to use Variable Argument.
The following will create a variable length set of arguments of the type of string:
print(String arg1, String... arg2)
You can then refer to arg2
as an array of Strings. This is a new feature in Java 5.
This is known as varargs see the link here for more details
In past java releases, a method that took an arbitrary number of values required you to create an array and put the values into the array prior to invoking the method. For example, here is how one used the MessageFormat class to format a message:
Object[] arguments = {
new Integer(7),
new Date(),
"a disturbance in the Force"
};
String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet "
+ "{0,number,integer}.", arguments);
It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs. So, for example, the MessageFormat.format method now has this declaration:
public static String format(String pattern,
Object... arguments);
Source: Stackoverflow.com