Java String Format

Filed Under: Java

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

java string format, java Formatter class

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.


String formattedString = String.format("My name is %s","John");

Above one liner code will output as:


My name is John

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.
  2. 
    int num1 = 2;
    int num2 = 3;
    int  result = num1 * num2;
    
    System.out.printf("The result of %d * %d = %d", num1,num2,result);
    

    Output:

    
    The result of 2 * 3 = 6
    
  3. System.err.printf(): Mostly used to print an error on console. Also to provide a custom error messages on console.
  4. 
    try {
    		int num1 = 2;
    		int num2 = 0;
    		int  result = num1 / num2;
    		System.out.printf("The result of %d / %d = %d", num1,num2,result);
    	} catch(Exception ex) {
    		System.err.printf("Error occurred with cause: %s", ex.getMessage());		
    	}
    

    Output:

    
    Error occurred with cause: / by zero
    

Java String Fromatter with StringBuffer and StringBuilder

We can use formatter with StringBuffer and StringBuilder as well.


StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
Formatter.format("value is %f",32.33434); 
System.out.print(sb.toString());

Output:


value is 32.334340

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 SpecifierApplies
To
DescriptionExample CodeOutput
%a,%AFloating pointThe result is a hexadecimal representation of the floating point numberString.format(“Hex is %a”,32.33434);Hex is 0x1.02acba732df5p5
%b, %BAll the typesIf 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, %CCharacterResults in a Unicode characterString.format(“Unicode is %C”,’T’);Unicode is T
%dbyte, Byte, short, Short, int, Integer, long, Long and BigIntegerResults in decimal integerString.format(“Number is %d”, 2*3);Number is 6
%e, %EFloating pointResults in decimal number in computerized scientific notationString.format(“Number is %e”, 2*3.0);Number is 6.000000e+00
%fFloating pointResults in decimal numberString.format(“Number is %f”, 2*3.0);Number is 6.000000
%g, %GFloating pointFormat 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, %HAny typeResults in hex string based on the output of hashCode() methodString.format(“Hex is %h”,”Jay”);Hex is 12202
%nLine separatorResults in platform specific line separatorString.format(“My name is %s. %n I know Java “,”John”);My name is John.
I know Java
%obyte, Byte, short, Short, int, Integer, long, Long and BigIntegerResults in an octal integerString.format(“Number is %o”, 3*3);Number is 11
%sAny typeResults in a stringString.format(“My name is %s”,”John”);My name is John
%t, %TDate and TimeThese are prefix for date and time conversion charactersString.format(“Local time: %tT”, Calendar.getInstance());Local time: 17:52:40
%x, %Xbyte, Byte, short, Short, int, Integer, long, Long and BigIntegerResults in a hexadecimal integerString 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 SpecifierDescription
AFull name of the day of the week, like “Sunday”, “Monday”
aShort name of the day of the week, like “Mon”, “Tue”
BFull month name like “January”, “February”.
bShort name of the month like “Jan”, “Feb”.
CLast two digits of the year, starting from 00 to 99
cDate and time formatted as “%ta %tb %td %tT %tZ %tY”, like “Mon Jan 01 16:17:00 CST 2018”
DDate formatted as “%tm/%td/%ty”, like “12/31/17”
dDay represented in two digits with leading zeros where necessary, starting from 01 to 31.
eDay of month represented in two digits, like 1 – 31.
FDate formatted in ISO 8601 format as “%tY-%tm-%td” like “2017-12-31”
HHour representation in 24 hours format with a leading zero as necessary i.e. 00 – 23.
hShort name of the month like “Jan”, “Feb”.
IHour represented in 12 hour format, formatted as two digits with a leading zero as necessary, i.e. 01 – 12.
jDay of the year out of 366 days (considering leap year), represented with leading 0s i.e. “001” to “366”.
kHour representation in 24 hour format without a leading 0 starting from “0” to “23”.
lHour representation in 12-hour format without a leading 0 like “1” to “12”.
LMillisecond within the second formatted represented in three digits with leading zeros starting from 000 to 999.
MMinute within the hour formatted leading zero starting from “00” to “59”.
mMonth formatted with a leading zero like “01” to “12”.
NNanosecond with in the second represented in 9 digits and leading 0s like “000000000” to “999999999”.
pLocale specific morning or afternoon specifier like “am” or “pm” marker.
QMilliseconds since the start of epoch Jan 1 , 1970 00:00:00 UTC.
RTime represented in 24-hours format i.e. “%tH:%tM” like “20:00”
rTime represented,in 12-hours format i.e “%tI:%tM:%tS %Tp”.
SSeconds within the minute represented in 2 digits like “00” to “60”. “60” is required to support leap seconds.
sSeconds since the start of epoch Jan 1, 1970 00:00:00 UTC.
TTime represented in 24 hours format along with seconds as “%tH:%tM:%tS”
YYear represented in four digits starting from,”0000″ to “9999”
yYear represented in two digits starting from “00” to “99”
ZTime zone representation in string like “IST”, “CST” etc.
zNumeric 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.


// Width for Integer
String s = String.format("{%10d}", 2017);
System.out.print(s);

// Width for String
String s1 = String.format("{%20s}", "Hello Format");
System.out.print(s1);

Output:


{      2017}
{        Hello Format}

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.


String s = String.format("{%.8s}", "Hello Format");

System.out.print(s);

Output:


{Hello Fo}

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.


String s = String.format("{%3$s %2$s %1$s}", "a","b","c");
System.out.print(s);

Output:


{c b a}

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.
  2. 
    String s = String.format ("{%4s}", "a");
    System.out.print(s);
    

    Output:

    
    {   a}
    
  3. Right alignment of a text.
  4. 
    String s = String.format ("{%-4s}", "a");
    System.out.print(s);
    

    Output:

    
    {a   }
    
  5. Locale specific number format representation.
  6. 
    String s = String.format ("{%,d}", 1000000);
    System.out.print(s);
    

    Output:

    
    {1,000,000}
    
  7. Padding with zero.
  8. 
    String s = String.format ("{%05d}", 99);
    System.out.print(s);
    

    Output:

    
    {00099}
    

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

Comments

  1. Jeremy Gordon Flowers says:

    Love the info you’ve gathered here. But I think I’ve spotted a correction you need to make. If you are trying to pass a boolean into a position where there is a %d placeholder you get a number format exception.

  2. Asim Husain says:

    Hello Pankaj,

    kindly correct this

    String s = String.format (“{%5d}”, 99);
    System.out.print(s);

    it should be as below

    String s = String.format (“{%05d}”, 99);
    System.out.print(s);

    Thanks for sharing nice tutorial. Keep sharing!

    1. Pankaj says:

      Thanks for noticing the error, looks like it got missed in copy paste of the code.

  3. Fruitson says:

    missing ‘”‘ in the “Java String Fromatter with StringBuffer and StringBuilder” section.

    >> Formatter.format(“value is %f”,32.33434);

    thanks for good article. 🙂

    1. Pankaj says:

      Thanks for pointing it out, I have fixed it.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages