Roman Proshin
Roman Proshin

Reputation: 909

Java 15 String.formatted(args): safe for locale-aware usage?

In Java prior to version 15, the most straightforward way of formatting a string was to use String.format(Locale, String, args) method. It was also considered a best practice to put Locale.ROOT as the locale there (unless you want a specific locale to be used) instead of the default one that could cause issues that are hard to debug.

Now, since Java 15, there is a new method available directly on the String instances: String.formatted(args). The new method, however, doesn't allow passing a locale. Under the hood, it uses the java.util.Formatter class that actually supports locales, but that also uses the default locale (Locale.getDefault(Locale.Category.FORMAT)).

Now I wonder that either something has changed in the JDK that there is no more issues with using the default locale (I doubt this could be true), OR the new method is not even supposed to be used in contexts where locale matters. But then I'm not sure what are the recommendations of when to use the new method (if at all).

Any advises and recommendations are welcome!

UPD: After reading my question one more time, and also considering this answer from @tquadrat, I came to the conclusion that using Locale.ROOT is probably not about having different locales based on the current user, but more like securing the app behavior from random bugs caused by the JVM configured with a "wrong" locale - Locale.ROOT ensures the app will always do string formatting in exactly the same way no matter what is the default locale on the server&JVM. That would be a use-case that becomes impossible to do with the String.formatted. However, as pointed out in comments, this limitation might have been expected by the authors of the JDK - and then String.format with Locale is still the preferred way in cases where the locale is required.

Upvotes: 3

Views: 88

Answers (1)

tquadrat
tquadrat

Reputation: 4034

You use Locale.ROOT where the locale does not matter (or is in fact causing problems) – meaning when you format program internal strings (strings that are not meant to be presented to a human user).

Messages to the users should always use a proper locale (one other than Locale.ROOT), and in most cases, the system locale is appropriate. And we talk about real users, not admins. So it is sufficient that String::formatted does not allow an Locale argument.

In cases you really need a locale when formatting a string, you can still use String::format.

Upvotes: 5

Related Questions