Welcome to this tutorial on string formatting in Java. String formatting, in simple terms, is the method of adding or altering content within a string. We can do this in three ways – using printf(), MessageFormat, and something called the Formatter class. Most Java developers favour the Formatter class, so that’s what we’ll focus on.
The Formatter class is part of a package in Java known as java.util. This class lets us format strings by swapping placeholders with actual values. It also helps with aligning and justifying the layout. When using this class, we use the String class to provide the locale (which is just the setting we’re applying), the format string (which is the blueprint of the string or the text that has format specifiers), and the argument(s) (these are the values we’re adding to the text). These values are given to the format() method of the String Formatter class. Let’s dive in and learn more about it!
A Quick Example of String. format()
This is an example of the format() method in the Formatter class:
public class Main { public static void main(String[] args) { String str = String.format("Hello %s!", "world"); System.out.println(str); } }
The output of this code would be:
Hello world!
The format specifier “%s” is used to add the string “word” to the text. To change the case of the argument, the specifier can be changed, for example “%S” would change the argument to uppercase.
String Format Specifiers
Text formatting depends on format specifiers. These specify the type of data that is expected to be added to a string. The general syntax for the format specifiers is:
%[argument_index$][flags][width][.precision]conversion
- The argument_index is an integer that shows the value from the argument list that should be used there.
- The flags is a set of characters that are used to modify the format of the output.
- The width is a positive integer that shows the minimum number of characters that will be written to the output.
- The precision is an integer that is used to restrict the number of characters. The behaviour of the precision depends on the conversion.
- The argument_index, flags, width, and precision are optional.
A good example is:
class Main { public static void main(String[] args) { String str = String.format("Hello, %2$s! Welcome to %1$s.", "Apps Developer Blog", "world"); System.out.println(str); } }
In the example above, we use 1$ and 2$ as the argument indices and outputs:
Hello, world! Welcome to Apps Developer Blog.
The mandatory part of the specifiers is the conversion. This is a character that shows how the argument should be formatted. The data type of the argument determines the conversion character used.
Below is a table of conversion characters supported by the String Formatter.
Conversion Character |
Data Type |
%d | Integer |
%c | Character |
%e | Floating-point number in scientific notation |
%f | Floating-point number |
%t | Date/Time |
%s | String |
%a | Hexadecimal floating-point number |
%b | Any type, binary |
%g | Floating-point number in scientific notation, depending on the value and precision |
%h | Any type, hexadecimal |
%n | None. It is a line separator |
%o | Octal integer |
%x | Integer, hex string |
Standard String Formatting
In the example below, we see what standard string formatting looks like using different data types.
class Main { public static void main(String[] args) { String name = "Anna"; Integer age = 23; Float salary = 154560.58f; String str = String.format("My name is %s. I am %d years old. I make USD %.2f.", name, age, salary); System.out.println(str); } }
Output:
My name is Anna. I am 23 years old. I make USD 154560.58.
Date and Time Formatting
As shown in the table above, the conversion character for date and time is %t.
import java.time.LocalDate; class Main { public static void main(String[] args) { LocalDate date = LocalDate.now(); String str = String.format("Today is %teth %tB %tY", date, date, date); System.out.println(str); } }
Output:
Today is 7th May 2023
In the example above, %tB and %tY are used to get the full name of the month and the full year. %te is used to get the day of the month.
Currency Formatting
Formatting of currency values can include adding commas to get a better output. In a previous example, we saw the currency “154560.58”.
class Main { public static void main(String[] args) { float salary = 154560.58f; String str = String.format("The amount is USD %,.2f.", salary); System.out.println(str); } }
Output:
The amount is USD 154,560.58.
The above example shows how the value can be printed with a comma separating the value at the thousands place. This is done using the %,.2f conversion characters.
Final words
As we’ve seen in this tutorial, the Formatter class in Java can be used to format values, currency, dates, etc. This allows for the incorporation of various types of data anywhere in a string. The various types of formatting that can be done using the Formatter class means it is the best way to format strings in Java.
To learn more about Java, check out the Java tutorials page.