Java String Format With Examples

Java String format allows us to put things in particular way or order. There are many ways for string formatting but it’s not so popular because most of the time we need simple conversions that can be done with string concatenation. Today we will look into java string format examples.

Java String Format

The formatted String concept started with C, Java also provides the feature of formatted printing using the class known as java.util.Formatter. In fact, formatted String concept of Java is inspired by C’s sprintf concept.

Let us look at how a simple String format method looks like.

Above one liner code will output as:

The same thing can be achieved as "My name is "+"John" and here we don’t even have to remember all the different specifiers. However String formatter is a better approach because of following reasons:

  • String concatenation is a costly affair.
  • If formatted string is long then string concatenation cause readability issues.
  • With String concatenation we have to do the conversion between different objects to strings.
  • String Formatter benefit is clearly visible where the format string is read from a property file.

The String.format() method returns the formatted String based on the format String and the arguments provided to the method.

In the example above, “My name is %s” is the format string. It contains a format specifier “%s” which tells how the argument should be processed and where it will be placed in the output.

The format method also uses locale for formatting a string. If the locale is not specified in String.format() method, it uses default locale by calling Locale.getDefault() method.

Java String Format Example

There are situation and scenarios when we would like to have formatted string appear on the console; the usage of it can vary from debugging to better readable code. In order to get formatted strings on console we need to use the following methods.

  1. System.out.printf()
  2. System.err.printf()

printf() and format() methods behave in the same way. The examples for the above mentioned methods are provided below.

    1. System.out.printf(): Most commonly used for printing on console for debugging purpose or for printing an output on the screen.


    1. System.err.printf(): Mostly used to print an error on console. Also to provide a custom error messages on console.


Java String Fromatter with StringBuffer and StringBuilder

We can use formatter with StringBuffer and StringBuilder as well.


Java String Format Conversion Specifiers

Java String Format conversion specifiers are the ones which plays a major role in String formatting. As the specifiers are the ones that tells how the conversion has to be processed and where to add the arguments in the text.

Lets take a look at the available conversion specifiers along with their examples.

Conversion Specifier Applies
Description Example Code Output
%a,%A Floating point The result is a hexadecimal representation of the floating point number String.format(“Hex is %a”,32.33434); Hex is 0x1.02acba732df5p5
%b, %B All the types If the argument arg is null, then the result is “false”. If arg is a boolean or Boolean, then the result is the string returned by String.valueOf(arg). Otherwise, the result is “true”. String.format(“value is %b”,”a”.equals(“a”)); value is true
%c, %C Character Results in a Unicode character String.format(“Unicode is %C”,’T’); Unicode is T
%d byte, Byte, short, Short, int, Integer, long, Long and BigInteger Results in decimal integer String.format(“Number is %d”, 2*3); Number is 6
%e, %E Floating point Results in decimal number in computerized scientific notation String.format(“Number is %e”, 2*3.0); Number is 6.000000e+00
%f Floating point Results in decimal number String.format(“Number is %f”, 2*3.0); Number is 6.000000
%g, %G Floating point Format is based on computerized scientific notation or decimal format, depending on the precision and the value after rounding. String.format(“Number is %g”, 2*3.0); Number is 6.000000
%h, %H Any type Results in hex string based on the output of hashCode() method String.format(“Hex is %h”,”Jay”); Hex is 12202
%n Line separator Results in platform specific line separator String.format(“My name is %s. %n I know Java “,”John”); My name is John.
I know Java
%o byte, Byte, short, Short, int, Integer, long, Long and BigInteger Results in an octal integer String.format(“Number is %o”, 3*3); Number is 11
%s Any type Results in a string String.format(“My name is %s”,”John”); My name is John
%t, %T Date and Time These are prefix for date and time conversion characters String.format(“Local time: %tT”, Calendar.getInstance()); Local time: 17:52:40
%x, %X byte, Byte, short, Short, int, Integer, long, Long and BigInteger Results in a hexadecimal integer String sf1=String.format(“Number is %x”, 23); Number is 17

Conversions denoted by upper-case character (i.e. ‘B’, ‘H’, ‘S’, ‘C’, ‘X’, ‘E’, ‘G’, ‘A’, and ‘T’) are the same as those for the corresponding lower-case conversion characters only difference is that the result is converted to upper case according to the rules of the locale.

Java String Formatting Date and Time Conversions

The following date and time conversion characters are used as suffix along with ‘t’ and ‘T’ for date and time conversion.

Example: %tA will result in full name of the day of the week.

Conversion Specifier Description
A Full name of the day of the week, like “Sunday”, “Monday”
a Short name of the day of the week, like “Mon”, “Tue”
B Full month name like “January”, “February”.
b Short name of the month like “Jan”, “Feb”.
C Last two digits of the year, starting from 00 to 99
c Date and time formatted as “%ta %tb %td %tT %tZ %tY”, like “Mon Jan 01 16:17:00 CST 2018”
D Date formatted as “%tm/%td/%ty”, like “12/31/17”
d Day represented in two digits with leading zeros where necessary, starting from 01 to 31.
e Day of month represented in two digits, like 1 – 31.
F Date formatted in ISO 8601 format as “%tY-%tm-%td” like “2017-12-31”
H Hour representation in 24 hours format with a leading zero as necessary i.e. 00 – 23.
h Short name of the month like “Jan”, “Feb”.
I Hour represented in 12 hour format, formatted as two digits with a leading zero as necessary, i.e. 01 – 12.
j Day of the year out of 366 days (considering leap year), represented with leading 0s i.e. “001” to “366”.
k Hour representation in 24 hour format without a leading 0 starting from “0” to “23”.
l Hour representation in 12-hour format without a leading 0 like “1” to “12”.
L Millisecond within the second formatted represented in three digits with leading zeros starting from 000 to 999.
M Minute within the hour formatted leading zero starting from “00” to “59”.
m Month formatted with a leading zero like “01” to “12”.
N Nanosecond with in the second represented in 9 digits and leading 0s like “000000000” to “999999999”.
p Locale specific morning or afternoon specifier like “am” or “pm” marker.
Q Milliseconds since the start of epoch Jan 1 , 1970 00:00:00 UTC.
R Time represented in 24-hours format i.e. “%tH:%tM” like “20:00”
r Time represented,in 12-hours format i.e “%tI:%tM:%tS %Tp”.
S Seconds within the minute represented in 2 digits like “00” to “60”. “60” is required to support leap seconds.
s Seconds since the start of epoch Jan 1, 1970 00:00:00 UTC.
T Time represented in 24 hours format along with seconds as “%tH:%tM:%tS”
Y Year represented in four digits starting from,”0000″ to “9999”
y Year represented in two digits starting from “00” to “99”
Z Time zone representation in string like “IST”, “CST” etc.
z Numeric time zone offset based on RFC 822 like “-0530”

Java String Format Width

The minimum number of characters required as the output is considered as the width. An exception will be thrown for line separator conversion as width is not applicable or it.


Java String Format Precision

Precision is the maximum number of characters to be written to the output for integer and String.

The floating-point conversions ‘a’, ‘A’, ‘e’, ‘E’, and ‘f’ have precision as the number of digits after the decimal. If the conversion is ‘g’ or ‘G’, then the precision is the total number of digits in the resulting magnitude after rounding.

An exception is thrown for character, integral, and date/time argument types and the percent and line separator conversions as precision is not applicable for these types.


Java String Format Argument Index

The argument index is a decimal integer starting after “%” sign and ending with “$” sign. The position of the argument in the argument list is decided based on the value of the integer.


Miscellaneous String Formatting Examples

Till now we have observed the various conversion specifiers and the usage of them. In this last section let us check some additional miscellaneous conversions.

    1. Left alignment of a text.


    1. Right alignment of a text.


    1. Locale specific number format representation.


    1. Padding with zero.


That’s all for Java String format examples, for more information on java string format please visit Formatter API Doc.

By admin

Leave a Reply

%d bloggers like this: