Java's String
type has a format
method, but calling it ignores everything inside the template and only returns the first argument.
String s = "name: %s, age: %d".format("bob", 42);
assertEquals("name: bob, age: 42", s); // fails, s.equals("bob")
Even with an empty template, the first argument is returned:
s = "".format("alice", 21); // returns "alice"
Java 8 and Java 11 both exhibit the same problematic behavior.
The same code works in Python:
s = 'name: {}, age: {}'.format('bob', 42)
s == 'name: bob, age: 42' # True
Why is that? There's no compilation error and the program runs without exception. It is very not obvious why it behaves this way. How to properly use the format
method of a string?
I read somewhere that in object-oriented languages, the object is the first argument of a method. Does that play a role here?
The method String.format(String format, Object... args)
(docs.oracle.com
) is a static method; we use it like this:
String s1 = String.format("name: %s, age: %d", "bob", 42);
Alternatively we can use the instance-method String.formatted(Object... args)
, which was introduced with Java 15 (docs.oracle.com
):
String s2 = "name: %s, age: %d".formatted("bob", 42);