How to build a formatted string in Java?
Asked Answered
M

4

17

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.

Mockingbird answered 30/3, 2011 at 0:37 Comment(0)
B
39
String s = String.format("x:%d, y:%d, z:%d", x, y, z);

Java Howto - Format a string

Bourne answered 30/3, 2011 at 0:42 Comment(2)
@macek np. I almost always have to look it up myself, I keep mixing up java and c# syntax.Bourne
this functionality is based on java.util.Formatter, which you can use directly for extended formatting.Aloft
A
6

Yes, it is possible. The String class contains the format() method, which works like you expect. Example:

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

Here you have more details about formatting: formatter syntax

Akin answered 30/3, 2011 at 0:47 Comment(0)
F
3

Since JDK 15:

var s = "x:%d, y:%d, z:%d".formatted(x, y, z);
Frerichs answered 5/1, 2021 at 0:48 Comment(0)
H
1

You can do interpolation using Java's String Templates feature. It is described in JEP 430, and it appears in JDK 21 as a preview feature. Here is an example use:

String info = STR."x:\{x}, y:\{y}, z:\{z}";
Harte answered 4/8, 2023 at 22:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.