How To Format A String in Java

Formatted is the new kid in town

Dieter Jordens
Kwal-IT

--

Photo by Aditya Wardhana on Unsplash

You probably think Java String formatting is not new for me. But actually, a lot has happened in the past versions of Java. Therefore, it is essential to re-evaluate the ‘best’ way to format a String. A lot has happened since java 8. You will see the latest and the fastest way of formatting a string for Java 17.

Most readable: "Hello %s".formatted("John")

We now have three options:

  • Java String formatted (since Java 15)
  • Java String format
  • Java plus operator

Since Java 15, you can now format a String with a new method, formatted. This method is the same as the well know static String format method. From a readability perspective, this is the same as String.format.

This newly added method will also be easier to test as the static alternative. Technically, you can now mock it with mockito. In practice, of course, you won’t be doing that very often. But it gives you some more possibilities, which is always lovely.

Could the readability be further improved in the future? One of the most readable String format methods I know is the f-string in Python. Let’s see what Java comes up within the end. We’re moving in the right direction.

Fastest: “Hello “ + “John”

Since Java 9, the plus operator symbol is faster than the StringBuilder. The plus operator was almost 40 times as fast as the static String format.

But as Java kept improving, this further reduced. The plus operator is still the fastest as of today. Among other performance updates to the Java ecosystem, the String format method is now three times faster than Java 9.

We’re talking about a negligible difference here. Choosing the plus operator for execution speed over readability is no longer a good argument for your daily applications. You will only notice this in billions of executions, so you should not lose any sleep over it.

Conclusion

Java keeps improving every day. The Java String format methods are changing and are improving in execution speed. You’ve seen that the plus operator is the fastest as of today. But it might not stay that way.

The chances are low that they will surpass the Java plus operator, but from a readability perspective, they are the winner. What do you think? Will the following java versions bring change?

Want personal training or coaching on this subject? Mail me at info@kwal-it.be or visit our site for our other services.

--

--

Owner of https://kwal-it.be - Your expert in the domain of Software Development, Coaching and Content Management