Java provides String.format()
with various options to format both text and numbers.
There is no need for additional libraries, it is a built-in feature.
The syntax is very similar to your example. Basically, to print a String, you can use the %s
placeholder. For decimal numbers, use %d
. See my link above to get a full list of all possible types.
String name = "Saskia";
int age = 23;
String formattedText = String.format("%s is %d years old.", name, age);
You can add flags for additional padding and alignment, if you want a column-like output.
String formattedText = String.format("%-10s is %-5d years old.", name, age);
In %-10s
the %s
defines the type String, the -
is used for left-alignment and the 10
defines the width of the padding.