Why does String.format accept ints in place of %s?

Javia1492 :

Looking at a couple of references for Java String.format(), I see they mention it has the following format:

public static String format(String format, Object... args)

So it allows me to write the following:

String newStr = String.format("%s,%s,%s", 1, 2, 3);

But I cannot do this:

String newStr = String.format("%d,%d,%d", "1", "2", "3");

Why can i use ints in place of %s but not vice-versa? Is it doing type-conversion from int to string itself?

Thilo :

Yes. For %s it calls toString on whatever you set in there. That works for everything in Java (may produce funny output though).

For %d you need to give an integral type (like Integer, Long or BigInteger). No automatic conversion is attempted.

You can read more about it in the Javadoc (look at the section about Conversions).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11671&siteId=1