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);
x = 1
y = 2
z = 3
"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.
%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"
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With