Search code examples
javastringstring-interpolation

How to build a formatted string in Java?


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.


Solution

  • String s = String.format("x:%d, y:%d, z:%d", x, y, z);
    

    Java Howto - Format a string