Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Java String Format Examples

This document serves as a comprehensive guide to Java String formatting, detailing various format specifiers and their applications. It covers methods such as String.format(), printf(), and Formatter, along with examples for formatting numbers, strings, and dates. Additionally, it provides a quick reference for conversion specifiers and formatting flags to enhance the usability of string formatting in Java.

Uploaded by

480
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java String Format Examples

This document serves as a comprehensive guide to Java String formatting, detailing various format specifiers and their applications. It covers methods such as String.format(), printf(), and Formatter, along with examples for formatting numbers, strings, and dates. Additionally, it provides a quick reference for conversion specifiers and formatting flags to enhance the usability of string formatting in Java.

Uploaded by

480
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Java String Format Examples

Always forgetting the Java String formatting specifiers? Or maybe you never
took the time to learn. Here's a reference of the various flags you can use.

Join the DZone community and get the full member experience.
Join For Free

When you purchase through links on our site, we may receive an affiliate commission.

Have you tried to read and understand Java’s String format documentation? I have and found it nearly
impenetrable. While it does include all the information, the organization leaves something to be desired.

This guide is an attempt to bring some clarity and ease the usage of string formatting in Java. You may also
want to take a look at What's New in Java 8 from Pluralsight or 38 Java String-Related Techniques
Making Your Life Easier, a course on Udemy.

String Formatting
The most common way of formatting a string in java is using String.format(). If there were a “java sprintf”
then this would be it.
1
1
String output = String.format("%s = %d", "joe", 35);

For formatted console output, you can use printf() or the format() method of System.out and System.err
PrintStreams.
1
1
System.out.printf("My name is: %s%n", "joe");

Create a Formatter and link it to a StringBuilder. Output formatted using the format() method will be
appended to the StringBuilder.
5
1
StringBuilder sbuf = new StringBuilder();
2
Formatter fmt = new Formatter(sbuf);
3
fmt.format("PI = %f%n", Math.PI);
4
System.out.print(sbuf.toString());
5
// you can continue to append data to sbuf here.
Format Specifiers
Here is a quick reference to all the conversion specifiers supported:

Specifier Applies to Output

%a floating point (except BigDecimal) Hex output of floating point number

%b Any type “true” if non-null, “false” if null

%c character Unicode character

%d integer (incl. byte, short, int, long, Decimal Integer


bigint)

%e floating point decimal number in scientific notation

%f floating point decimal number

%g floating point decimal number, possibly in scientific notation


depending on the precision and value.

%h any type Hex String of value from hashCode() method.

%n none Platform-specific line separator.

%o integer (incl. byte, short, int, long, Octal number


bigint)

%s any type String value

%t Date/Time (incl. long, Calendar, %t is the prefix for Date/Time conversions. More
Date and TemporalAccessor) formatting flags are needed after this. See
Date/Time conversion below.

%x integer (incl. byte, short, int, long,


bigint) Hex string.

Date and Time Formatting

Note: Using the formatting characters with “%T” instead of “%t” in the table below makes the output
uppercase.

Flag Notes

%tA Full name of the day of the week, e.g. “Sunday“, “Monday“
Flag Notes

%ta Abbreviated name of the week day e.g. “Sun“, “Mon“, etc.

%tB Full name of the month e.g. “January“, “February“, etc.

%tb Abbreviated month name e.g. “Jan“, “Feb“, etc.

%tC Century part of year formatted with two digits e.g. “00” through “99”.

%tc Date and time formatted with “%ta %tb %td %tT %tZ %tY”

%tD Date formatted as “%tm/%td/%ty“

%td Day of the month formatted with two digits. e.g. “01” to “31“.

%te Day of the month formatted without a leading 0 e.g. “1” to “31”.

%tF ISO 8601 formatted date with “%tY-%tm-%td“.

%tH Hour of the day for the 24-hour clock e.g. “00” to “23“.

%th Same as %tb.

%tI Hour of the day for the 12-hour clock e.g. “01” – “12“.

%tj Day of the year formatted with leading 0s e.g. “001” to “366“.

%tk Hour of the day for the 24 hour clock without a leading 0 e.g. “0” to “23“.

%tl Hour of the day for the 12-hour click without a leading 0 e.g. “1” to “12“.

%tM Minute within the hour formatted a leading 0 e.g. “00” to “59“.

%tm Month formatted with a leading 0 e.g. “01” to “12“.

%tN Nanosecond formatted with 9 digits and leading 0s e.g. “000000000” to “999999999”.

%tp Locale specific “am” or “pm” marker.

%tQ Milliseconds since epoch Jan 1 , 1970 00:00:00 UTC.

%tR Time formatted as 24-hours e.g. “%tH:%tM“.

%tr Time formatted as 12-hours e.g. “%tI:%tM:%tS %Tp“.

%tS Seconds within the minute formatted with 2 digits e.g. “00” to “60”. “60” is required to
support leap seconds.
Flag Notes

%ts Seconds since the epoch Jan 1, 1970 00:00:00 UTC.

%tT Time formatted as 24-hours e.g. “%tH:%tM:%tS“.

%tY Year formatted with 4 digits e.g. “0000” to “9999“.

%ty Year formatted with 2 digits e.g. “00” to “99“.

%tZ Time zone abbreviation. e.g. “UTC“, “PST“, etc.

%tz
Time Zone Offset from GMT e.g. “
-0800

“.

Argument Index
An argument index is specified as a number ending with a “$” after the “%” and selects the specified
argument in the argument list.
1
1
String.format("%2$s", 32, "Hello"); // prints: "Hello"

Formatting an Integer
With the %d format specifier, you can use an argument of all integral types including byte, short, int, long
and BigInteger.

Default formatting:
1
1
String.format("%d", 93); // prints 93

Specifying a width:
1
1
String.format("|%20d|", 93); // prints: | 93|

Left-justifying within the specified width:


1
1
String.format("|%-20d|", 93); // prints: |93 |
Pad with zeros:
1
1
String.format("|%020d|", 93); // prints: |00000000000000000093|

Print positive numbers with a “+”:

(Negative numbers always have the “-” included):


1
1
String.format("|%+20d|', 93); // prints: | +93|

A space before positive numbers.

A “-” is included for negative numbers as per normal.


1
String.format("|% d|", 93); // prints: | 93| String.format("|% d|", -36); // prints: |-36|

Use locale-specific thousands separator:

For the US locale, it is “,”:


1
1
String.format("|%,d|", 10000000); // prints: |10,000,000|

Enclose negative numbers within parentheses (“()”) and skip the "-":
1
1
String.format("|%(d|", -36); // prints: |(36)|

Octal output:
1
1
String.format("|%o|"), 93); // prints: 135

Hex output:
1
1
String.format("|%x|", 93); // prints: 5d
Alternate representation for octal and hex output:

Prints octal numbers with a leading “0” and hex numbers with leading “0x“.
​x
1
String.format("|%#o|", 93);
2
// prints: 0135
3

4
String.format("|%#x|", 93);
5
// prints: 0x5d
6

7
String.format("|%#X|", 93);
8
// prints: 0X5D

String and Character Conversion


Default formatting:

Prints the whole string.


1
1
String.format("|%s|", "Hello World"); // prints: "Hello World"

Specify Field Length


1
1
String.format("|%30s|", "Hello World"); // prints: | Hello World|

Left Justify Text


1
1
String.format("|%-30s|", "Hello World"); // prints: |Hello World |

Specify Maximum Number of Characters


1
1
String.format("|%.5s|", "Hello World"); // prints: |Hello|
Field Width and Maximum Number of Characters
1
1
String.format("|%30.5s|", "Hello World"); | Hello|

Summary
This guide explained String formatting in Java. We covered the supported format specifiers. Both numeric
and string formatting support a variety of flags for alternative formats. If you want more content on Java
Strings, check out the Do's and Don'ts of Java Strings.

You might also like