Why this does work OK?:
String f = "Mi name is %s %s.";
System.out.println(String.format(f, "John", "Connor"));
And this doesnt?:
String f = "Mi name is %s %s.";
System.out.println(String.format(f, (Object)new String[]{"John","Connor"}));
If the method String.format takes a vararg Object?
It compiles OK but when I execute this the String.format() takes the vararg Object as a single an unique argument (the toString() value of the array itself), so it throws a MissingFormatArgumentException because it cannot match with the second string specifier (%s).
How can I make it work? Thanks in advance, any help will be greatly appreciated.
In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Parameter: The locale value to be applied on the format() method.
str = compose( formatSpec , A ) formats data values from the input array, A , using formatting operators specified by formatSpec and returns the resulting text in str . The compose function formats values from A in column order. If formatSpec is a string array, then so is the output array str .
We can have an array with strings as its elements. Thus, we can define a String Array as an array holding a fixed number of strings or string values. String array is one structure that is most commonly used in Java.
To pass an array as an argument to a method, you just have to pass the name of the array without square brackets. The method prototype should match to accept the argument of the array type. Given below is the method prototype: void method_name (int [] array);
Use this : (I would recommend this way)
String f = "Mi name is %s %s.";
System.out.println(String.format(f, (Object[])new String[]{"John","Connor"}));
OR
String f = "Mi name is %s %s.";
System.out.println(String.format(f, new String[]{"John","Connor"}));
But if you use this way, you will get following warning :
The argument of type
String[]
should explicitly be cast toObject[]
for the invocation of thevarargs
methodformat(String, Object...)
from typeString
. It could alternatively be cast toObject
for avarargs
invocation.
The problem is that after the cast to Object
, the compiler doesn't know that you're passing an array. Try casting the second argument to (Object[])
instead of (Object)
.
System.out.println(String.format(f, (Object[])new String[]{"John","Connor"}));
Or just don't use a cast at all:
System.out.println(String.format(f, new String[]{"John","Connor"}));
(See this answer for a little more info.)
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