Omar Kooheji Omar Kooheji - 1 year ago 52
Java Question

Is it better practice to use String.format over string Concatenation in Java?

Is there a perceptible difference between using

and string concatenation in Java?

I tend to use
but occasionally will slip and use a concat. I was wondering if one was better than the other.

The way I see it,
gives you more power in "formatting" the string; and concatenation means you don't have to worry about accidentally putting in an extra %s or missing one out.

is also shorter.

Which one is more readable depends on how your head works.

Answer Source

I'd suggest that it is better practice to use String.format(). The main reason is that String.format() can be more easily localised with text loaded from resource files whereas concatenation can't be localised without producing a new executable with different code for each language.

If you plan on your app being localisable you should also get into the habit of specifying argument positions for your format tokens as well:

"Hello %1$s the time is %2$t"

This can then be localised and have the name and time tokens swapped without requiring a recompile of the executable to account for the different ordering. With argument positions you can also re-use the same argument without passing it into the function twice:

String.format("Hello %1$s, your name is %1$s and the time is %2$t", name, time)