Java String Formatter: A Guide with Examples

In this tutorial, we’ll be looking at how string formatting is done in Java. String formatting is the process of dynamically adding content to a string. There are three ways this can be done, using printf(), MessageFormat, and Formatter class. Using the Formatter class is the most commonly used method of string formatting in Java.

This tutorial will focus on the Formatter class. Java String Formatter is a class that is part of the java.util package. It is used to format strings by replacing placeholders with values. The formatter class provides support for the justification and alignment of the layout. The locale, format string, and argument(s) are provided statically using the String class. The locale is the locale to be applied to the format method. The format string is the format of the string or the static text with format specifiers. The argument(s) is the values to be added to the text. The values are passed as arguments to the format() method of the String Formatter class.

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.

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.