Consider the method declaration:
String.format(String, Object ...)
The Object ...
argument is just a reference to an array of Object
s. Is there a way to use this method with a reference to an actual Object
array? If I pass in an Object
array to the ...
argument - will the resultant argument value be a two-dimensional array - because an Object[]
is itself an Object
:
Object[] params = ....; // Make the array (for example based on user-input) String s = String.format("%S has %.2f euros", params);
So the first component of the array (Which is used in the String.format
method), will be an array and he will generate:
[class.getName() + "@" + Integer.toHexString(hashCode())]
and then an error because the array size is 1.
The bold sequence is the real question.
This is a second question: Does a ...
array/parameter have a name?
Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments. Variable Arguments in Java simplifies the creation of methods that need to take a variable number of arguments.
Rules for varargs:There can be only one variable argument in the method. Variable argument (varargs) must be the last argument.
Varargs are useful for any method that needs to deal with an indeterminate number of objects. One good example is String. format . The format string can accept any number of parameters, so you need a mechanism to pass in any number of objects.
Variable argument or varargs in Java allows you to write more flexible methods which can accept as many arguments as you need. variable arguments or varargs were added in Java 1.5 along with great language features like Java Enum, Generics, autoboxing and various others.
From the docs on varargs:
The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.
So you can pass multiple arguments or an array.
The following works just fine:
class VarargTest { public static void main(String[] args) { Object[] params = {"x", 1.2345f}; String s = String.format("%s is %.2f", params); System.out.println(s); // Output is: x is 1.23 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With