Java - Format String

By xngo on February 24, 2019

In Java, formatting string using concatenation is not ideal. It is recommended to use String.format() function with its placeholder. For example, if you want to display a dynamic string (age, qty, count), you would write the code as follows.

// Using string concatenation.
int age=1, qty=2, count=3;
String concat = "("+age+", "+qty+", "+count+")";
System.out.println(concat); // Output: (1, 2, 3)
 
// Using String.format().
String sf = String.format("(%s, %s, %s)", age, qty, count);
System.out.println(sf); // Output: (1, 2, 3)

As you can see, it is much easier to read the code with the String.format() function than with string concatenation. As you want to format more complex string, string concatenation will get much ugly and messier.

Below are examples on how to use the function with its placeholders.

Placeholder to format string

Pre-allocate 10 characters space for each variable.

String sf = String.format("(%10s, %10s, %10s)", age, qty, count);
System.out.println(sf);
 
// Output: (         1,          2,          3)

Right align value using hyphen(-).

sf = String.format("(%-10s, %-10s, %-10s)", age, qty, count);
System.out.println(sf);
 
// Output: (1         , 2         , 3         )

Placeholder to format number

Show only 2 decimal points.

double avg = 3695.32756;
sf = String.format("%.2f", avg);
System.out.println(sf);
 
// Output: 3695.33

Add thousand separator using comma(,).

sf = String.format("%,.2f", avg);
System.out.println(sf);
 
// Output: 3,695.33

Pad zeros so the length is 12 digits long.

sf = String.format("%012d", count);
System.out.println(sf);
 
// Output: 000000000003

Placeholder to format date

Calendar now = Calendar.getInstance();
sf = String.format("ISO 8601 date format: %tF", now);
System.out.println(sf);
 
sf = String.format("Year: %tY", now); 
System.out.println(sf);
 
sf = String.format("Month: %tm", now); 
System.out.println(sf);
 
sf = String.format("Day: %te", now); 
System.out.println(sf);
 
// Output:
//  ISO 8601 date format: 2019-11-23
//  Year: 2019
//  Month: 11
//  Day: 23

Move placeholder position

You can move your placeholder position using the index number followed by the dollar sign($). For example, 1$ and 2$ will refer to the first and second arguments.

sf = String.format("%2$s, %1$s, %2$s, %1$s", "one", "two"); 
System.out.println(sf);
 
// Output: two, one, two, one

Reference

  • https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

Github

  • https://github.com/xuanngo2001/java-small/blob/master/src/net/openwritings/java/string/StringFormat.java

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.