[java] How can I create a Java method that accepts a variable number of arguments?

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 answer is


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.

  1. There can be only one variable argument in the method.
  2. Variable argument (varargs) must be the last argument.

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);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to methods

String method cannot be found in a main class method Calling another method java GUI ReactJS - Call One Component Method From Another Component multiple conditions for JavaScript .includes() method java, get set methods includes() not working in all browsers Python safe method to get value of nested dictionary Calling one method from another within same class in Python TypeError: method() takes 1 positional argument but 2 were given Android ListView with onClick items

Examples related to overloading

What is the difference between dynamic and static polymorphism in Java? TypeScript function overloading Constructor overload in TypeScript What is the difference between method overloading and overriding? Differentiate between function overloading and function overriding How do I use method overloading in Python? How can I create a Java method that accepts a variable number of arguments? Python function overloading PHP function overloading What is function overloading and overriding in php?