A nicer example takes advantage of the varargs and autoboxing improvements in Java 1.5 and turns the above into a one-liner:

MessageFormat.format("String is \"{1}\", number is {0}.", 42, "foobar");

MessageFormat is a little bit nicer for doing i18nized plurals with the choice modifier. To specify a message that correctly uses the singular form when a variable is 1 and plural otherwise, you can do something like this:

MessageFormat is for localization purposes, so take care when using it. For example the following code MessageFormat.format("Number {0}", 1234)); depending on default locale can produce Number 1,234 instead of Number 1234.
–
pavel_kazlouDec 4 '12 at 10:25

@ataylor : Hello, Sorry but I am little confused. I want to something like that I ll pass Class object that has data & when {0} it ll take firstname, when {1} then lastname, like so. Is it possible like {0,choice,0.getFirstName()} or something like that ?
–
user3145373 ツDec 8 '14 at 7:07

Ok fine, I have refer one .Net project like that I want, codeproject.com/Articles/42310/…, refer this project I am looking like this. If you know any project or packages available like that then please tell me. Thank you
–
user3145373 ツDec 10 '14 at 9:54

Take a look at String.format. Note, however, that it takes format specifiers similar to those of C's printf family of functions -- for example:

String.format("Hello %s, %d", "world", 42);

Would return "Hello world 42". You may find this helpful when learning about the format specifiers. Andy Thomas-Cramer was kind enough to leave this link in a comment below, which appears to point to the official spec. The most commonly used ones are most likely:

%s - insert a string

%d - insert a signed integer (decimal)

%f - insert a real number, standard notation

This is radically different from C#, which uses positional references with an optional format specifier. That means that you can't do things like:

Another option is java.text.MessageFormat, which does accept the {1} style format symbols. String.format()'s format symbols can be similar to C's printf() format symbols -- but can also differ. See download.oracle.com/javase/6/docs/api/java/util/… for the full syntax.
–
Andy ThomasJun 21 '11 at 21:11

If you choose not to use String.format, the other option is the + binary operator

String str = "Step " + a + " of " + b;

This is the equivalent of

new StringBuilder("Step ").append(String.valueOf(1)).append(" of ").append(String.valueOf(2);

Whichever you use is your choice. StringBuilder is faster, but the speed difference is marginal. I prefer to use the + operator (which does a StringBuilder.append(String.valueOf(X))) and find it easier to read.

1) In response to a question on string formatting, you explain how the + operator works. 2) Your explanation isn't even accurate. + is equivalent to using StringBuilder, not String.concat. (Way too much info on this.)
–
Søren LøvborgSep 4 '12 at 8:01