Java - Including variables within strings?

Gray Adams picture Gray Adams · Mar 10, 2012 · Viewed 190k times · Source

Ok, so we all should know that you can include variables into strings by doing:

String string = "A string " + aVariable;

Is there a way to do it like:

String string = "A string {aVariable}";

In other words: Without having to close the quotation marks and adding plus signs. It's very unattractive.

Answer

Hovercraft Full Of Eels picture Hovercraft Full Of Eels · Mar 10, 2012

You can always use String.format(....). i.e.,

String string = String.format("A String %s %2d", aStringVar, anIntVar);

I'm not sure if that is attractive enough for you, but it can be quite handy. The syntax is the same as for printf and java.util.Formatter. I've used it much especially if I want to show tabular numeric data.