In Java string concatenations with +
are quite common. In most cases the compiler is smart enough to translate concatenations with +
for concatenations using StringBuilder
and append
; in that way +
is usually the most natural language for concatenating strings in Java. In cases where performance is important and the logic is too complex to be optimized by the compiler we can use StringBuilder
directly.
For "advanced" formatting there is the method String.format
that uses formatting strings very similar to the ones used in the function printf
of the C.
String mensagem = String.format("%d %s custam $%0.2f", 6, "bananas", 1.74);
For "basic" formatting there is also the class MessageFormat
who uses Patterns similar to the placeholders positional of format
python.
String mensagem = MessageFormat.format("{0} {1} custam {2,number,currency}", 6, "bananas", 1.74);
Finally, it is also possible to use an external solution such as Better Strings that allows string interpolation in Java projects.
https://docs.oracle.com/javase/10/docs/api/java/lang/String.html#format(java.lang.String,java.lang.Object...)
– Augusto Vasques