In Java, one option is to use printf
:
String nome = "Fulano";
int idade = 20;
System.out.printf("%s tem %d anos\n", nome, idade); // Fulano tem 20 anos
The format string syntax is inspired by C, so you should indicate the type of each information being displayed (in the above case, %s
indicates a string and %d
indicates an integer). View documentation for more details.
It is worth remembering that printf
is more than just concatenating, since you can choose alignment and fill options (for example, printing the text aligned to the right, occupying 20 positions, or printing the number with zeros to the left, including determining the quantity, etc.). For example, %05d
would cause the number above to be printed as 00020
.
Finally, to see all the options, see the aforementioned documentation. It is a more powerful mechanism than simple concatenation, so you should choose the one that is most suitable for your case (do not use as a criterion "is shorter" or "tires less", use what makes the most sense for what you need to do).
But if instead of printing, you want to generate a string with the result of concatenation/formatting, then you can use String.format
, whose syntax is similar:
String mensagem = String.format("%s tem %d anos", nome, idade);
Another option is to use java.text.MessageFormat
, whose syntax resembles a little more the format
python:
String mensagem = MessageFormat.format("{0} tem {1} anos", nome, idade);
But this class has some interesting options, such as setting the text to singular and plural:
String mensagem = MessageFormat.format("{0} tem {1} {1,choice,1#ano|1<anos}", nome, idade);
So if age is 1
, the message will be Fulano tem 1 ano
, but if it’s different from 1
(for example, 20
), there will be Fulano tem 20 anos
. Again, be sure to see on documentation all available options.