Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 744
maček Avatar asked Mar 30 '11 00:03

maček


People also ask

What is %s and %D in java?

%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"

Are there formatted strings in java?

The Java String. format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.


3 Answers

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

Java Howto - Format a string

like image 79
xecaps12 Avatar answered Sep 18 '22 03:09

xecaps12


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

like image 41
Karol Lewandowski Avatar answered Sep 18 '22 03:09

Karol Lewandowski


Since JDK 15:

var s = "x:%d, y:%d, z:%d".formatted(x, y, z);
like image 28
Eldar Agalarov Avatar answered Sep 21 '22 03:09

Eldar Agalarov