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". The "format string" link points to the complete official spec, but for simple cases, this much shorter documentation may be helpful for an introduction to format specifiers even though it's outdated and about Lava. The most commonly used ones are:
- %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:
String.format("The {0} is repeated again: {0}", "word");
... without actually repeating the parameter passed to printf/format. (see The Scrum Meister's comment below)
If you just want to print the result directly, you may find System.out.printf (PrintStream.printf) to your liking.
Answer from Martin Törnwall on Stack OverflowTake 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". The "format string" link points to the complete official spec, but for simple cases, this much shorter documentation may be helpful for an introduction to format specifiers even though it's outdated and about Lava. The most commonly used ones are:
- %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:
String.format("The {0} is repeated again: {0}", "word");
... without actually repeating the parameter passed to printf/format. (see The Scrum Meister's comment below)
If you just want to print the result directly, you may find System.out.printf (PrintStream.printf) to your liking.
In addition to String.format, also take a look java.text.MessageFormat. The format less terse and a bit closer to the C# example you've provided and you can use it for parsing as well.
For example:
int someNumber = 42;
String someString = "foobar";
Object[] args = {new Long(someNumber), someString};
MessageFormat fmt = new MessageFormat("String is \"{1}\", number is {0}.");
System.out.println(fmt.format(args));
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:
String formatString = "there were {0} {0,choice,0#objects|1#object|1<objects}";
MessageFormat fmt = new MessageFormat(formatString);
fmt.format(new Object[] { new Long(numberOfObjects) });
Videos
Make sure you use a good IDE so that you have easy access to browse into JDK source code. In Eclipse say, use F3 to open to any declaration. IntelliJ IDEA has similar feature.
If you view the source code for both methods, you can see these calls are identical except that variables this is interchanged with format when comparing the instance vs static method:
public String formatted(Object... args) {
return new Formatter().format(this, args).toString();
}
public static String format(String format, Object... args) {
return new Formatter().format(format, args).toString();
}
So as you've observed: String.format(str, args) is same as str.formatted(args)
Text Blocks were finalized and permanently added in JDK 15 and some additional methods added to support text blocks. One of this methods is:
String::formatted(Object... args)
And I know the functions of two codes below are the same.
As you mentioned in your question both methods do the same job and return same results. The goal of introducing such a method is:
simplify value substitution in the Text Block.
Based on JEP (JDK Enhancement Proposals) 378:
Text blocks do not directly support string interpolation. Interpolation may be considered in a future JEP. In the meantime, the new instance method
String::formattedaids in situations where interpolation might be desired.
As an example you consider this code segment:
String code = String.format("""
public void print(%s o) {
System.out.println(Objects.toString(o));
}
""", type);
We can change it using formatted method as:
String source = """
public void print(%s object) {
System.out.println(Objects.toString(object));
}
""".formatted(type);
Which is cleaner.
Also consider these minor differences between them when using the methods:
public static String format(String format, Object... args)
- Returns a formatted string using the format string and arguments.
- It's a static method of
Stringclass. - It's introduced in Java SE 5 [since 2004].
public String formatted(Object... args)
- Formats using this string as the format string, and the supplied arguments.
- It's an instance method of
Stringclass. - It's introduced in Java SE 15 (JDK 15) [since 2020].
- This method is equivalent to
String.format(this, args)