Overview
In this article, we will cover format() method of string class in java, why and how it is used with ample examples.

String.format()

String.format() is a powerful tool in Java that allows you to format strings in a variety of ways.
You can use it to format numbers, dates, currencies, and other values. You can even use it to create complex strings with multiple lines and placeholders.
Syntax
String.format() accepts two arguments.
1. A string that you want to format.
This string can be anything, but it must contain what are called format specifiers.
Format specifiers are placeholders for variables that you want to insert into the string.

Placeholders are denoted by a % symbol followed by a pre-defined letters. An example of a placeholder is %s, which is used for string values.
2. Values to be inserted into the placeholders in the format string.

String.format() returns a string with placeholders replaced with corresponding values.
String.format() example
Below is a simple example to understand the usage of String.format().

String language = "java";
String unfmt = "Learning %s language";
String fmt = String.format(unfmt, language);
System.out.print(fmt);

Here, the placeholder %s in the first argument is replaced with the second argument value.
This prints

Understanding java language

Formatting multiple values
We can substitute values from multiple variables in a string at once as well.
Also, these values can be of different types as shown below

int number = 123;
double amount = 123.45;
String s = "abc";
String fmt = String.format("Number is %d, " + 
              "String is %s, " +
              "Amount is %f", number, s, amount); 
System.out.println(fmt);

In this example, we replace three different values in a single string.
All these values are of different data types and the string produced by format() is

Number is 123, String is abc, Amount is 123.450000

Notice that it appended 0’s after double value, which is not required.
Also, at times you might want to display values only till specific decimal values.
With format(), you can define the precision of decimal values using point(.) after %, followed by the number of digits to be displayed such as %.2f. Example,

double amt = 123.45;
// remove trailing zeroes
System.out.println(String.format("%.2f", amt));

double large = 123.46564;
// display only 3 decimal places
System.out.println(String.format("%.3f", large));

Output is

123.45
123.465

Below is a list of format options that can be used with String.format()

OptionDescription
b, BFor formatting boolean values, true or false.
If the value to be formatted is null, it returns false.
h, HFor formatting to hexadecimal.
s, SFor formatting values of type string.
dFor formatting integer values.
fFor formatting decimal or floating point values.
x, XFor formatting to hexadecimal but the value to be formatted should be an integer.
oFor formatting to octal.
nAdding platform specific line-separator
t, TFor formatting date/time values.

Lower and upper case letters return result in corresponding case.
This list can be found here.

Formatting hexadecimal values
If the value to be converted to hexadecimal is a string, then use h, H flags.
If the value to be converted to hexadecimal is an integer, then use x or X flags. Examples,

System.out.println(
        String.format("123 in hex is %x", 123));
System.out.println(
        String.format("12g in hex is %h", "12g"));
System.out.println(
        String.format("12g in hex is %H", "12g"));

Output is

123 in hex is 7b
12g in hex is be66
12g in hex is BE66

Formatting to octal
Use o flag with String.format() to format a value to octal. Example,

System.out.println(
           String.format("123 in octal is %o", 123));

Output is

123 in octal is 173

Formatting dates
%t along with D flag is used to format date. The value should be of type java.util.Date.
D flag will format the date in mm/dd/yy format. To convert to other formats, use Y, m and d flags for year, month and day, as shown below

Date d = new Date();
System.out.println(String.format("%tD", d));
System.out.println(String.format("%tY-%tm-%td", d,d,d));

Output is

12/18/22
2022-12-18

To print the last two digits of year, y flag is used.
Formatting time
%t along with T flag is used to format time. The value should be of type java.util.Date.
T flag will format the time in hh:mm:ss format. To convert to other formats, use H, M and S flags for hour, minute and second, as shown below

Date d = new Date();
System.out.println(String.format("%tT", d));
System.out.println(String.format("%tH:%tM", d,d,d));

Output is

12:17:16
12:17

Padding spaces and zeroes
Sometimes you might want to display a value between fixed widths while the value to be displayed is lesser than the width.
In such cases, you need to add empty spaces or 0s before the values. This is called padding.
String.format() provides support to pad a value  with both spaces and 0s simply by providing the width before the appropriate flag as shown below

int number = 123;
System.out.println(
         String.format("Value padded with spaces %5d", number));
System.out.println(
         String.format("Value padded with zeroes %05d", number));

Output is

Value padded with spaces   123
Value padded with zeroes 00123

Local specific formatting
With String.format(), you can format values specific to a locale by providing locale as the first argument.
There is an overloaded format() method which takes 3 arguments as below

public static String format(Locale l, String format, Object… args)

Example is

double amount = 123.4534;
String fmt = String.format("Amount in default locale " + 
              " is %.2f ", amount);
System.out.println(fmt);
fmt = String.format(Locale.FRENCH, 
              "Amount in french locale is %.2f ", amount);
System.out.println(fmt);

Output is

Amount in default locale is 123.45
Amount in french locale is 123,45

Look, the second value is formatted in french locale, since we have , in place of .
Pass values from array
If there are multiple values to be formatted in a single string, then the argument list can become too long as in the below example

int n1 = 47, n2 = 64, n3 = 96;
String text = "Result";
System.out.println(
         String.format("%s: Hex: %x, Octal: %o, " + 
                       " Decimal: %d", text, n1, n2, n3));

This, not only becomes complex but more error prone.

To solve this, format() also accepts an array in place of multiple values as shown below

int n1 = 47, n2 = 64, n3 = 96;
String text = "Result";
// define an array
Object[] arr = {text, n1, n2, n3};
System.out.println(
     String.format("%s: Hex: %x, Octal: %o, Decimal: %d", arr));

Array values are replaced in the order of their indexes. That is, first placeholder will be replaced with first array element and so on.
So, you need to be careful with the order of array elements.

Another way is to define the index of array element along with placeholder using position and $ symbol with format symbol such as %2$s, which references second element. Example,

int n1 = 47, n2 = 64, n3 = 96;
String text = "Result";
Object[] arr = {text, n1, n2, n3};
System.out.println(
    String.format("%1$s: Hex: %2$x, Octal: %3$o, " +
                  " Decimal: %4$d", arr));

That is all on String.format() method in java. Hope the article was useful.