19

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.

mevqz
  • 653
  • 3
  • 9
  • 19

2 Answers2

21

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 to Object[] for the invocation of the varargs method format(String, Object...) from type String. It could alternatively be cast to Object for a varargs invocation.

nclark
  • 1,022
  • 1
  • 11
  • 16
Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
11

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

although that might generate a compiler warning. (See this answer for a little more info.)

The cleanest, I think, would be to avoid a String[] in the first place:

System.out.println(String.format(f, new Object[]{"John","Connor"}));
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • 2
    Thanks, it works with Object[] cast. The cast is necessary to avoid a compilation warning. Thanks again. – mevqz Jul 18 '12 at 06:02
  • 3
    @Dragurne - To avoid the compiler warning and the cast, you could use `new Object[]{"John","Connor"}`. – Ted Hopp Jul 18 '12 at 06:16