String variable interpolation Java

cmcculloh picture cmcculloh · Jun 17, 2011 · Viewed 191.3k times · Source

String building in Java confounds me. I abhore doing things like:

url += "u1=" + u1 + ";u2=" + u2 + ";u3=" + u3 + ";u4=" + u4 + ";";
url += "x=" + u1 + ";y=" + u2 + ";z=" + u3 + ";da1=" + u4 + ";";
url += "qty=1;cost=" + orderTotal + ";ord=" + orderId + "?";

Or, using StringBuilder, something like this:

    url.append("u1=");
    url.append(u1);
    url.append(";u2=");
    url.append(u2);
    url.append(";u3=");
    url.append(u3);
    url.append(";u4=");
    url.append(u4);
    url.append(";");
    url.append("x=");
    url.append(u1);
    url.append(";y=");
    url.append(u2);
    url.append(";z=");
    url.append(u3);
    url.append(";da1=");
    url.append(u4);
    url.append(";");
    url.append("qty=1;");
    url.append("cost=");
    url.append(orderTotal);
    url.append(";ord=");
    url.append(orderId);
    url.append("?");

SURELY I'm missing something. There has GOT to be a better way. Something like:

Instead of:

urlString += "u1=" + u1 + ";u2=" + u2 + ";u3=" + u3 + ";u4=" + u4 + ";";

do:

urlString += Interpolator("u1=%s;u2=%s;u3=%s;u4=%s;", u1, u2, u3, u4);

or:

urlStringBuilder.append(Interpolator("u1=%s;u2=%s;u3=%s;u4=%s;", u1, u2, u3, u4));

Answer

Jon Skeet picture Jon Skeet · Jun 17, 2011

If you're using Java 5 or higher, you can use String.format:

urlString += String.format("u1=%s;u2=%s;u3=%s;u4=%s;", u1, u2, u3, u4);

See Formatter for details.