Close

Java String Formatting

[Last Updated: Nov 30, 2017]

java.util.Formatter is an interpreter for getting C language printf-style formatted strings. In Java, we usually use following methods to format console output which internally use Formatter class:

System.out.printf(String format, Object... args)
System.out.printf(Locale l, String format, Object... args)

We can also use following methods of java.lang.String to get formatted strings:

String format(String format, Object... args)
String format(Locale l, String format, Object... args)

The 'format' parameter in above methods, usually consists of one or multiple formatting specifier. A formatting specifier starts with %, which is a way to specify various formatting attributes to get the desired results.

In following examples we will quickly go through different formatting options available.

n - line terminator

 System.out.printf("abc%n456%n");
 abc
 456

s or S - a String

 System.out.printf("%s%n", "this is my string");
System.out.printf("%S%n", "this is my string");
System.out.printf("%s%n", null);
System.out.printf("%s%n", 100);
System.out.printf("%s%n", new Object());
System.out.printf("'This is the example of %s.....'%n", "string");
 this is my string
 THIS IS MY STRING
 null
 100
 java.lang.Object@247507be
 'This is the example of string.....'

b or B - true/false

It will convert null/false to false , everything else to true

 System.out.printf("%b%n", null);
System.out.printf("%b%n", false);
System.out.printf("%B%n", false);
 false
 false
 FALSE
 System.out.printf("%b%n", true);
System.out.printf("%b%n", "true");
System.out.printf("%b%n", "false");
System.out.printf("%b%n", "test");
System.out.printf("%b%n", 1);
System.out.printf("%b%n", 'c');
System.out.printf("%b%n", new Object());
 true
 true
 true
 true
 true
 true
 true

c or C - a char

 System.out.printf("%c%n", 'a');
System.out.printf("%C%n", 'a');
System.out.printf("%c%n", 100);
System.out.printf("%c%n", null);
 a
 A
 d
 null
For invalid char:
 System.out.printf("%c%n", "aString");
 java.util.IllegalFormatConversionException: c != java.lang.String
 	at java.base/java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4331)
 	at java.base/java.util.Formatter$FormatSpecifier.printCharacter(Formatter.java:2922)
 	at java.base/java.util.Formatter$FormatSpecifier.print(Formatter.java:2810)
 ......

Formatting with padding

For left padding, an integer is used between % and the conversion specifier:

 System.out.printf("Result: %20s%n", "example");
 Result:              example
For right padding additional - is used.
 System.out.printf("Result: %-20s%n", "example");
System.out.printf("%-20s result%n", "example");
 Result: example
 example              result
Good for formatting multiple lines in columns:
 for (int i = 7; i < 300; i += 50) {
System.out.printf("[Item:%4s %-4s]%n", i, i * 10);
}
 [Item:   7  70  ]
 [Item:  57  570 ]
 [Item: 107  1070]
 [Item: 157  1570]
 [Item: 207  2070]
 [Item: 257  2570]

Precision

This is used to limit chars.
Syntax: x.y where x= padding (width) and y= number of chars.
(For floating numbers y is used for decimal places - next sections.)

 System.out.printf("%2.2s%n", "Hi there!");
System.out.printf("[%6.4s]%n", "What's up?");
System.out.printf("[%-6.4s]%n", "What's up?");
 Hi
 [  What]
 [What  ]

d - byte/short/int/long/BigInteger formatting

 System.out.printf("%d%n", 2);
System.out.printf("%d%n", (byte) 2);
System.out.printf("%d%n", 2L);
System.out.printf("%d%n", BigInteger.valueOf(2L));
 2
 2
 2
 2
Invalid input (strings and other objects are also invalid):
 System.out.printf("%d%n", '2');
 java.util.IllegalFormatConversionException: d != java.lang.Character
 	at java.base/java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4331)
 	at java.base/java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2846)
 	at java.base/java.util.Formatter$FormatSpecifier.print(Formatter.java:2800)
 ......

Padding with zeros

0 is used just after % and then an int for padding (as we saw in 'Formatting with padding' above).

 System.out.printf("%04d", 2);
 0002
Right zero padding is not possible. Using '%0-4d' or '%-04d' will throw exception:
 System.out.printf("%0-4d", 2);
 java.util.IllegalFormatFlagsException: Flags = '-0'
 	at java.base/java.util.Formatter$FormatSpecifier.checkNumeric(Formatter.java:3084)
 	at java.base/java.util.Formatter$FormatSpecifier.checkInteger(Formatter.java:3039)
 	at java.base/java.util.Formatter$FormatSpecifier.(Formatter.java:2782)
 ......

Comma formatted numbers

A comma is used between % and d

 System.out.printf("%,d", 1000000);
 1,000,000
For different locale
 System.out.printf(Locale.GERMAN, "%,d", 1000000);
 1.000.000

Always include + sign

 for (int i = 1; i < 4; i++) {
System.out.printf("%+d%n", i);
}
 +1
 +2
 +3

Always include parentheses for negative numbers

 for (int i = 1; i < 4; i++) {
System.out.printf("%(d%n", -i);
}
 (1)
 (2)
 (3)

Always include leading space for positive numbers

Only one space is allowed:

 for (int i = 1; i < 4; i++) {
System.out.printf("[% d]%n", i);
}
 [ 1]
 [ 2]
 [ 3]

Precision cannot be applied to integers

 System.out.printf("%6.4d", 123456);
 java.util.IllegalFormatPrecisionException: 4
 	at java.base/java.util.Formatter$FormatSpecifier.checkInteger(Formatter.java:3041)
 	at java.base/java.util.Formatter$FormatSpecifier.(Formatter.java:2782)
 	at java.base/java.util.Formatter.parse(Formatter.java:2621)
 ......

f - float/double formatting

 System.out.printf("%f%n", 1.33f);
System.out.printf("%f%n", 1.33d);
System.out.printf("%f%n", Double.valueOf(1.33d));
System.out.printf("%f%n", BigDecimal.valueOf(1.33d));
 1.330000
 1.330000
 1.330000
 1.330000

Applying precisions:

Syntax: x.y, where x is width (padding) and y is decimal places. Sometimes value of x is ignored, if it's smaller than the necessary chars (including the decimal) to display. Remember x is not to limit width but to add padding (spaces); y is to decrease/increase decimal places.

 System.out.printf("[%4.2f]%n", 12.34567);
System.out.printf("[%5.2f]%n", 12.34567);
System.out.printf("[%6.2f]%n", 12.34567);
System.out.printf("[%7.2f]%n", 12.34567);
System.out.printf("[%-7.2f]%n", 12.34567);
System.out.printf("[%7.4f]%n", 12.3);
System.out.printf("[%8.4f]%n", 12.3);
 [12.35]
 [12.35]
 [ 12.35]
 [  12.35]
 [12.35  ]
 [12.3000]
 [ 12.3000]

Always display decimal with # flag

The integer portion of the result always ends with a
decimal point ('.'), even if the fractional portion is zero.

 System.out.printf("[%#1.0f]%n", 1234d);
System.out.printf("[%1.0f]%n", 1234d);
 [1234.]
 [1234]

e or E - Scientific notation

Syntax: x.ye => y=precision and x=total width (padding)

 System.out.printf("%1.2e%n", 123.45);
System.out.printf("[%10.2e]%n", 123.45);
System.out.printf("[%-10.1e]%n", 123.45);
System.out.printf("%5.2E%n", 123.45);
 1.23e+02
 [  1.23e+02]
 [1.2e+02   ]
 1.23E+02

g or G - Scientific notation

It depends on precision and rounding.

 System.out.printf("%1.2g%n", 123.45);
System.out.printf("[%10.2g]%n", 123.45);
System.out.printf("[%-10.1g]%n", 123.45);
System.out.printf("[%-10.1G]%n", 123.45);
 1.2e+02
 [   1.2e+02]
 [1e+02     ]
 [1E+02     ]

Index based references

A variable reference can be used as X$ just after %, where X is the index.

Following example is without referencing an index:
 String test = "myString";
System.out.printf("%1.2s - %1.4s", test, test);
 my - mySt

Using the reference:

 String test2 = "myString";
System.out.printf("%1$1.2s - %1$1.4s", test2);
 my - mySt

Using multiple references:

 System.out.printf("%2$s | %3$1.4f | %1$,d", 1333, "hello", 5.4444);
 hello | 5.4444 | 1,333

t or T - Date time formatting

 System.out.printf("Hours: %tH%n", new Date());
System.out.printf("Mins: %tM%n", new Date());
System.out.printf("Secs: %tS%n", new Date());
 Hours: 22
 Mins: 09
 Secs: 08
 Date date = new Date();
System.out.printf("%tH:%tM:%tS%n", date, date, date);
//using index references
System.out.printf("%1$tH:%1$tM:%1$tS%n", date);
 22:09:08
 22:09:08
T can be used for %tH:%tM:%tS% format (last example):
 System.out.printf("%tT", new Date());
 22:09:08

Time in am/pm format

I - for 12 hr clock
p - for am or pm

 System.out.printf("%1$tI:%1$tM %1$tp", new Date());
 10:09 pm

Time in milli/nanoseconds

L - milliseconds
N - nanoseconds

 System.out.printf("%1$tT %1$tL %1$tN", new Date());
 22:09:08 357 357000000

TimeZone info

z - timezone offset
Z - timezone id

 System.out.printf("%1$tT %1$tz%n", new Date());
System.out.printf("%1$tT %1$tZ%n", new Date());
 22:09:08 -0600
 22:09:08 CST

Time since epoch

s - epoch seconds
Q - epoch millis

 System.out.printf("epoch sec: %1$ts%n", new Date());
System.out.printf("epoch millis: %1$tQ%n", new Date());
 epoch sec: 1512014948
 epoch millis: 1512014948440

Month

B - full month name
b - abbreviated month name
m - year of month number 01 - 12

 Date dt = Date.from(ZonedDateTime.of(LocalDate.of(2017, 2, 1).atStartOfDay(),
ZoneId.systemDefault()).toInstant());
System.out.printf("%tB%n", dt);
System.out.printf("%tb%n", dt);
System.out.printf("%tm%n", dt);
 February
 Feb
 02

Day

A - full name
a - abbreviated
d - day of month, 01 - 31

 System.out.printf("%tA%n", new Date());
System.out.printf("%ta%n", new Date());
System.out.printf("%td%n", new Date());
 Wednesday
 Wed
 29

Year

Y - four digit year
y - two digit year

 System.out.printf("%tY%n", new Date());
System.out.printf("%ty%n", new Date());
 2017
 17

Common formats shortcuts

R - %tH:%tM
T - %tH:%tM:%tS
r - %tI:%tM:%tS %Tp
D - %tm/%td/%ty
F - %tY-%tm-%td
c - %ta %tb %td %tT %tZ %tY, e.g. Sun Jul 20 16:17:00 EDT 1969.

 System.out.printf("%tR%n", new Date());
System.out.printf("%tT%n", new Date());
System.out.printf("%tr%n", new Date());
System.out.printf("%tD%n", new Date());
System.out.printf("%tF%n", new Date());
System.out.printf("%tc%n", new Date());
 22:09
 22:09:08
 10:09:08 PM
 11/29/17
 2017-11-29
 Wed Nov 29 22:09:08 CST 2017

See Also