Week 29 — What is a "Format String", and how do you use one?

Question of the Week #29
What is a "Format String", and how do you use one?
8 Replies
Eric McIntyre
Eric McIntyre2y ago
A format string in Java is a string that contains placeholders (formatting strings) that can later be replaced by actual values. It is a very useful concept because it allows you to define a desired formatting for the output of variables. For example, you can specify a certain number of decimal places for a floating point number, or leading zeros for an integer. As an example, let's look at formatting an integer with leading zeros. Let's say we have a number 42 and we want to format it so that the output is always three digits, including leading zeros if necessary. We can do this with a format string like %03d.
int number = 42;
String formattedNumber = String.format("%03d", number);
System.out.println(formattedNumber);
int number = 42;
String formattedNumber = String.format("%03d", number);
System.out.println(formattedNumber);
This would produce the output 042, with a leading zero added to make the number three digits. The %03d in the format string indicates that the number should be formatted to three digits with leading zeros. The d indicates that the number is an integer. Let's look at another example.
int time = 12;
String name = "Java Community";
String message = String.format("Hello %s, it's %d o'clock.", name, time);
System.out.println(message);
int time = 12;
String name = "Java Community";
String message = String.format("Hello %s, it's %d o'clock.", name, time);
System.out.println(message);
This code shows how to use a format string in Java to create a personalised message. You can use the String.format() method to create a formatted string by replacing placeholders (format strings) with actual values. In this example we have a format string Hello %s, it's %d o'clock. with two placeholders: %s for a string value and %d for an integer value. The String.format() method takes two arguments: the format string and the values to replace the placeholders. In this case, we enter "Java Community" and 12 as the values to replace %s and %d. The output of this code would be: Hello Java Community, it's 12 o'clock.
⭐ Submission from stormofgalaxy#0000
Eric McIntyre
Eric McIntyre2y ago
Java allows using so-called "format strings" to create Strings containing data from variables. Without format strings, one would need to use string concatenation for that:
int i = 123;
String s = "abc";
String together = "i="+i+", s="+s;//i=123, s=abc
int i = 123;
String s = "abc";
String together = "i="+i+", s="+s;//i=123, s=abc
Format strings allow to use placeholders for the variables and then supply the variables in the same order. The method String.format can generate a String like that. Alternatively, String#formatted can be used the same way
int i = 123;
String s = "abc";
String together = String.format("i=%d, s=%s",i,s); //i=123, s=abc
String usingFormatted = "i=%d, s=%s".formatted(i,s);//i=123, s=abc
int i = 123;
String s = "abc";
String together = String.format("i=%d, s=%s",i,s); //i=123, s=abc
String usingFormatted = "i=%d, s=%s".formatted(i,s);//i=123, s=abc
The formatted text can also be directly written to System.out (or any other PrintStream) using the System.out.printf:
int i = 123;
String s = "abc";
System.out.printf("i=%d, s=%s",i,s);//i=123, s=abc
int i = 123;
String s = "abc";
System.out.printf("i=%d, s=%s",i,s);//i=123, s=abc
This also works together with text blocks:
int i = 123;
String s = "abc";
String together = """
i=%d
s=%s
""".formatted(i,s);
int i = 123;
String s = "abc";
String together = """
i=%d
s=%s
""".formatted(i,s);
Format strings support various ways of displaying. For example, it's possible to add paddings to variables or configure the number of decimal points:
int i=123;
double d=13.37;
System.out.printf("|%4d|%7.1f|%n",i,d); //| 123| 13,4|
System.out.printf("|%-4d|%-7.1f|%n",i,d); //|123 |13,4 |
int i=123;
double d=13.37;
System.out.printf("|%4d|%7.1f|%n",i,d); //| 123| 13,4|
System.out.printf("|%-4d|%-7.1f|%n",i,d); //|123 |13,4 |
Eric McIntyre
Eric McIntyre2y ago
Java 21 will introduce a new preview feature called String Templates which will allow to directly embed the variables: For this, one needs to reference a template processor (e.g. STR or FMT) followed by a . and a String literal where \{expression} can be used as a placeholder with arbitrary expressions.
int i=123;
double d=13.37;
String text = STR."i=\{i}, s=\{s}"; //i=123, s=abc
String formatted = FMT."|%-4d\{i}|%-7.1f\{d}|";//|123 |13,4 |
int i=123;
double d=13.37;
String text = STR."i=\{i}, s=\{s}"; //i=123, s=abc
String formatted = FMT."|%-4d\{i}|%-7.1f\{d}|";//|123 |13,4 |
It is also possible to define custom template processors. String templates are described in JEP 430.
⭐ Submission from dan1st#0000
Eric McIntyre
Eric McIntyre2y ago
String.format help for formatting the String. With this format can be concatenate the Strings at the same time and so on. For example to print out two diffrent variables in one String: System.out.println( String.format("My car is %s and has %d doors",myCar.getColor(),myCar.getDoors()));
Eric McIntyre
Eric McIntyre2y ago
Example 2: with only two decimal print out perimeter of a square which is sides are double: System.out.println(String.format("%.2f",square.calculatePerimeter()));
Submission from Sefali#1230
Eric McIntyre
Eric McIntyre2y ago
String name = “ashish”; String sf1 = String.format(“name is %s”,name); System.out.println(sf1);
Eric McIntyre
Eric McIntyre2y ago
The Java string format() method returns the formatted string by given locale, format and arguments
Submission from coder_ashishpatel007#0000
Eric McIntyre
Eric McIntyre2y ago
A format string is a specifically crafted string, that values can be inserted into. Think of it like a string template that specifies multiple placeholders for datatypes, and specifies their formatting in that string.
String format = "Hello %s, did you know that PI rounded to 4 decimals is %.4f?"; // A simple format string
String output = String.format(format, "World", Math.PI);
System.out.println(output); // Hello World, did you know that PI rounded to 4 decimals is 3,1416?
// Note the comma for the decimal point, String.format uses the system locale per default
String outputInEnglish = String.format(Locale.ENGLISH, format, "World", Math.PI);
// ^ "Hello World, did you know that PI rounded to 4 decimals is 3.1416?"
String format = "Hello %s, did you know that PI rounded to 4 decimals is %.4f?"; // A simple format string
String output = String.format(format, "World", Math.PI);
System.out.println(output); // Hello World, did you know that PI rounded to 4 decimals is 3,1416?
// Note the comma for the decimal point, String.format uses the system locale per default
String outputInEnglish = String.format(Locale.ENGLISH, format, "World", Math.PI);
// ^ "Hello World, did you know that PI rounded to 4 decimals is 3.1416?"
There are several placeholders that modify how data is formatted. As an example: the x placeholder prints an inputted number in lowercase hex. A X placeholder would print it in uppercase hex. h and H follow the same convention, but print the hashcode of the object passed in instead of its value. The s placeholder is maybe the most important placeholder. It stringifies the input value literally. If the input object implements Formattable, the formatTo method is called. Otherwise, it is toStringed. There are many more placeholders and modifiers to those placeholders, the Formatter javadoc explains all of them.
⭐ Submission from 0x150#0000
Want results from more Discord servers?
Add your server