Question of the Week #29
What is a "Format String", and how do you use one?
10 messages · Page 1 of 1 (latest)
What is a "Format String", and how do you use one?
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);
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);
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.
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
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
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
This also works together with text blocks:
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 |
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 |
It is also possible to define custom template processors.
String templates are described in JEP 430.
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()));
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()));