VOOZH about

URL: https://dzone.com/articles/java-string-format-examples

⇱ Java String Format Examples: 2021 Edition


Related

  1. DZone
  2. Data Engineering
  3. Data
  4. Java String Format Examples

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.

By Updated Jul. 11, 21 Β· Tutorial
Likes
Comment
Save
3.7M Views

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.

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.

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.

StringBuilder sbuf = new StringBuilder();
Formatter fmt = new Formatter(sbuf);
fmt.format("PI = %f%n", Math.PI);
System.out.print(sbuf.toString());
// 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, bigint) Decimal Integer
%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, bigint) Octal number
%s any type String value
%t Date/Time (incl. long, Calendar, Date and TemporalAccessor) %t is the prefix for Date/Time conversions. More 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β€œ
 %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.
%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.

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:

String.format("%d", 93); // prints 93


Specifying a width:

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


Left-justifying within the specified width:

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


Pad with zeros:

String.format("|%020d|", 93); // prints: |00000000000000000093|


Print positive numbers with a β€œ+”:

 (Negative numbers always have the β€œ-” included):

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


A space before positive numbers.

A β€œ-” is included for negative numbers as per normal.

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


Use locale-specific thousands separator:

For the US locale, it is β€œ,”:

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


Enclose negative numbers within parentheses (β€œ()”) and skip the "-":

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


Octal output:

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


Hex output:

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β€œ.

String.format("|%#o|", 93);
// prints: 0135

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

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


String and Character Conversion

Default formatting:

Prints the whole string.

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


Specify Field Length

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


Left Justify Text

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


Specify Maximum Number of Characters

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


Field Width and Maximum Number of Characters

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.

Data Types Strings Java (programming language)

Published at DZone with permission of Jay Sridhar. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Long Road to Java Virtual Threads
  • Exploring Exciting New Features in Java 17 With Examples
  • Proper Java Exception Handling
  • Generics in Java and Their Implementation

Partner Resources

Γ—

Comments

The likes didn't load as expected. Please refresh the page and try again.

Let's be friends: