Best article on Java String Format Methods with an example by Codzify.com mentors

Article by: Manish Methani

Last Updated: September 28, 2021 at 8:04am IST
10 min 38 sec

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and manipulate strings.

Topics which we are going to cover in this article today are

  1. How to create a string?
  2. Creating Format String
  3. String Format method example
  4. Date and Time Formatting
  5. Argument Index in Java
  6. Format Integer in java
  7. Specifying a width to format an integer
  8. Padding with zeros to format an integer
  9. String and character conversion methods
  10. Left justify the text to format an integer

How to create a string?

The most common way to create a string in Java is 

String greeting = "Hello world!"

In this case, "hello world" is a string literal also known as a sequence of characters enclosed in double-quotes. Whenever string literals are encountered, a compiler creates a String object with its value.

Creating Format Strings

The string class provides a way to format the strings using the string format() method. The string format() method returns a String object rather than a PrintStream object.

The string format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example instead of 

System.out.printf("The value of float is %f" + 

"The value of integer is %d", floatVar, Intvar );

String fs;

fs = String.format("The value of float is %f" +  "The value of integer is %d", floatVar, Intvar System.out.println(fs);

String format method example

In the given java program, StringBuilder class is created along with Formatter class with the StringBuilder reference. In the next statement, we then used the format() method of formatter to create a formatted string. In the end, using the toString() method of StringBuilder we printed the output.

import java.util.*;
import java.lang.*;
import java.io.*;

class StringFormatMethod
{
public static void main (String[] args) throws java.lang.Exception
{
StringBuilder sbuf = new StringBuilder();
Formatter fmt = new Formatter(sbuf);
fmt.format("PI = %f%n", Math.PI);
System.out.print(sbuf.toString());

}
}

Format Specifiers in Java

Have a quick look at various different format specifiers in java,

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” e.g. “Fri Feb 17 07:45:42 PST 2017
 %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 in Java

Argument indices allow programmers to reorder the output. Let us see an example.

import java.util.*;
import java.lang.*;
import java.io.*;

class ArgumentIndexInjava
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.printf("Before reordering = %s %s %s %s %s %s ", "1", "2", "3", "4", "5", "6" );
      System.out.printf("After reordering = %6$s %5$s %4$s %3$s %2$s %1$s ","1", "2", "3", "4", "5", "6" );
      System.out.printf("Before reordering = %d %d %d ", 101, 201, 301);
      System.out.printf("After reordering = %2$d %3$d %1$d ", 101, 201, 301);

}
}

Output

Before reordering = 1 2 3 4 5 6
After reordering = 6 5 4 3 2 1
Before reordering = 101 201 301
After reordering = 201 301 101

Format Integer in Java

To format integer in Java, usually %d format specifier is used. You can use %d format specifier for all the integer datatypes like byte, short, int, long, BigInteger.

Default Formatting

import java.util.*;
import java.lang.*;
import java.io.*;

class Codzify
{
public static void main (String[] args) throws java.lang.Exception
{
        System.out.println(String.format("%d", 50));     
}
}

Output

50

Specifying a width

String.format("|%20d|", 50); 
import java.util.*;
import java.lang.*;
import java.io.*;

class Codzify
{
public static void main (String[] args) throws java.lang.Exception
{
        System.out.println(String.format("|%10d|", 50));     
}
}

Output

| 50|

Left justify with given width

String.format("|%-10d|", 50)
import java.util.*;
import java.lang.*;
import java.io.*;

class Codzify
{
public static void main (String[] args) throws java.lang.Exception
{
        System.out.println(String.format("|%-10d|", 50));     
}
}

Output

|50 |

Padding with zeros

String.format("|%010d|", 50);
import java.util.*;
import java.lang.*;
import java.io.*;

class Codzify
{
public static void main (String[] args) throws java.lang.Exception
{
   System.out.println(String.format("|%010d|", 50));     

 

} }

Output

|0000000050|

String and Character Conversion

By default, strings can be printed using %s format specifier. Have a look at the given java program, we have printed a string "Hello World" using %s format specifier.

import java.util.*;
import java.lang.*;
import java.io.*;

class StringToCharacterConversionExample
{
public static void main (String[] args) throws java.lang.Exception
{
        System.out.println(String.format("|%s|", "Hello World"));     
}
}

Output

|Hello World|

After specifying a width,

import java.util.*;
import java.lang.*;
import java.io.*;

class Codzify
{
public static void main (String[] args) throws java.lang.Exception
{
        System.out.println(String.format("|%20s|", "Hello World"));     
}
}

Output

| Hello World|

Left Justify the text

import java.util.*;
import java.lang.*;
import java.io.*;

class Codzify
{
public static void main (String[] args) throws java.lang.Exception
{
        System.out.println(String.format("|%-20s|", "Hello World"));     
}
}

Output

|Hello World |

Print only given number of characters,

import java.util.*;
import java.lang.*;
import java.io.*;

class Codzify
{
public static void main (String[] args) throws java.lang.Exception
{
        System.out.println(String.format("|%.5s|", "Hello World"));     
}
}

Output

|Hello|

With given width and number of characters,

import java.util.*;
import java.lang.*;
import java.io.*;

class Codzify
{
public static void main (String[] args) throws java.lang.Exception
{
        System.out.println(String.format("|%20.5s|", "Hello World"));     
}
}

Output

| Hello|

I hope you got a better understanding of how do string formatting in java works. Check out our related articles section to find more interesting articles to read. Keep coding :)

Watch Video Tutorials at Codzify YouTube Channel:

Codzify Logo

Terms and Conditions    Cookie Policy   Refund Policy   Adsense Disclaimer

Contact: teamcodzify@gmail.com