How to build a formatted string in Java?

maček picture maček · Mar 30, 2011 · Viewed 21.9k times · Source

I am somewhat new to Java but I dislike the heavy use of string concatenation I'm seeing in my textbook.

For example, I'd like to avoid doing this:

String s = "x:"+x+"," y:"+y+", z:"+z;

Is it possible to build a string using a notation similar to this:

String s = new String("x:%d, y:%d, z:%d", x, y, z);

Input

x = 1
y = 2
z = 3

Output

"x:1, y:2, z:3"

Note: I understand I can output formatted strings using System.out.printf() but I want to store the formatted string in a variable.

Answer

xecaps12 picture xecaps12 · Mar 30, 2011
String s = String.format("x:%d, y:%d, z:%d", x, y, z);

Java Howto - Format a string