Javia1492
Javia1492

Reputation: 892

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

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?

Upvotes: 3

Views: 1882

Answers (1)

Thilo
Thilo

Reputation: 262714

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

Upvotes: 7

Related Questions