Java string format


Java String String.fomatViews 2653

Java string format String.format() method in Java returns a formatted string value based on locale, format, and arguments passed. If we do not specify the locale, it takes the default locale from Locale.getDefault(). The extra arguments will be ignored if more arguments are passed.

This method is similar to sprintf() method of the C language and printf() method of Java Print stream.

String format() Syntax in Java

We can use the String format() method in below 2 ways:

Without  using Locale

public static String format(String format, Object… args)

Using Locale

public static String format(Locale locale, String format, Object… args)

locale – locale which needs to be applied on format() method

format – required string format

args – the arguments for the format string. It can be zero or more.

String format() Exceptions

The Java String format() method throws below 2 exceptions:

NullPointerException – when  the format is null

IllegalFormatException or IllelagFormatConversionException – when the specified format is illegal or incompatible

MissingFormatArgumentException – when the argument is missing for the specified format.

Java String format Types

We can use the below string format types to convert into String

Format TypeData TypeOutput
%aFloating pointHexadecimal value of floating point number
%bAny type“True” if not null and “False” if null
%cCharacterUnicode character
%dIntegerDecimal integer
%eFloating pointDecimal number in scientific notation
%fFloating pointDecimal number
%gFloating pointDecimal number in scientific notation based on precision and value
%hAny typeHex String value from hashCode() method
%nNonePlatform specific line separator
%oIntegerOctal number
%sAny typeString
%tDate/TimeThis is the prefix for date/time conversion. Refer below table for more details
%xIntegerHex string

Java String format examples

public class Democlass {

  public static void main(String[] args) {
    formatString();
    
  }
  
  public static void formatString()
  {
    System.out.println("Output of %a is " + String.format("%a", 1.5));
    System.out.println("Output of %b is " + String.format("%b", false));
    System.out.println("Output of %B is " + String.format("%B", true));
    System.out.println("Output of %c is " + String.format("%c", 'd'));
    System.out.println("Output of %d is " + String.format("%d", 101));
    System.out.println("Output of %e is " + String.format("%e", 5.6));
    System.out.println("Output of %f is " + String.format("%f", 5.6));
    System.out.println("Output of %g is " + String.format("%g", 5.6));
    System.out.println("Output of %h is " + String.format("%h", 10));
    System.out.println("Output of %n is " + String.format("%n"));
    System.out.println("Output of %o is " + String.format("%o", 8));
    System.out.println("Output of %s is " + String.format("%s", "Java"));
    System.out.println("Output of %x is " + String.format("%x", 10));
  }
}


Output:
Output of %a is 0x1.8p0
Output of %b is false
Output of %B is TRUE
Output of %c is d
Output of %d is 101
Output of %e is 5.600000e+00
Output of %f is 5.600000
Output of %g is 5.60000
Output of %h is a
Output of %n is 

Output of %o is 10
Output of %s is Java
Output of %x is a

String format Date Time Types

As mentioned in the above table, we use %t as a prefix for date-time conversions in the Java String format method. When we use an upper case character along with %t, we get output in uppercase. Similarly, when we use lower case character along with %t, we get output in lowercase.

Format TypeOutput
%tAFull name of weekday, Eg: Sunday
%taShort name of weekday, Eg: Sun
%tBFull name of month, Eg: January
%tbShort name of month, Eg: Jan
%tCYear formatted with 2 digits, Eg: 00 to 99
%tcDate and Time in format “%ta %tb %td %tT %tZ %tY”, Eg: Sat May 23 21:25:46 IST 2020
%tDDate in the format “MM/DD/YY”, Eg: 05/23/20”
%tdDay of the month in 2 digit, Eg: 01 to 31
%teDay of the month without leading 0, Eg: 1 to 31
%tFFormatted date in “YYYY-MM-DD
%tHHour of day in 24 hours format
%thSame as %tb
%tIHour of day in 12 hours format
%tjDay of the year with leading 0. Eg: 001 to 366
%tkHour of the day in 24 hours format without leading 0, Eg: 0 to 23
%tlHour of the day in 12 hours format without leading 0, Eg: 0 to 12
%tMMinute of hour with leading 0, Eg: 00 to 59
%tmMonth formatted with leading 0, Eg: 01 to 12
%tNNanosecond of time formatted with 9 digits and leading 0, Eg: 000000000 to 999999999
%tpLocale specific based on time, Eg: am or pm
%tQMilliseconds
%tRTime in 24 hours format as “HH:MM”
%trTime in 12 hours format as “HH:MM:SS AM/PM”
%tSSeconds of the minute formatted with 2 digits, Eg: 00 to 59
%tsSeconds
%tTTime in 24 hours format as “HH:MM:SS”
%tYYear in 4 digits format as “YYYY”
%tyYear in 2 digits format as “YY”
%tZTime zone abbreviation, Eg: IST, UTC
%tzTime zone offset from GMT, Eg: +0530

Java String format example with Date-Time

In the below example, we can see how we can retrieve any part of the date or time using the format() method.

import java.util.Calendar;

public class Democlass {

  public static void main(String[] args) {
    formatDateTimeString();
    
  }
  
  public static void formatDateTimeString()
  {
    System.out.println("Output of %tA is " + String.format("%tA", Calendar.getInstance()));
    System.out.println("Output of %ta is " + String.format("%ta", Calendar.getInstance()));
    System.out.println("Output of %tB is " + String.format("%tB", Calendar.getInstance()));
    System.out.println("Output of %tb is " + String.format("%tb", Calendar.getInstance()));
    System.out.println("Output of %tC is " + String.format("%tC", Calendar.getInstance()));
    System.out.println("Output of %tc is " + String.format("%tc", Calendar.getInstance()));
    System.out.println("Output of %tD is " + String.format("%tD", Calendar.getInstance()));
    System.out.println("Output of %td is " + String.format("%td", Calendar.getInstance()));
    System.out.println("Output of %te is " + String.format("%te", Calendar.getInstance()));
    System.out.println("Output of %tF is " + String.format("%tF", Calendar.getInstance()));
    System.out.println("Output of %tH is " + String.format("%tH", Calendar.getInstance()));
    System.out.println("Output of %th is " + String.format("%th", Calendar.getInstance()));
    System.out.println("Output of %tI is " + String.format("%tI", Calendar.getInstance()));
    System.out.println("Output of %tj is " + String.format("%tj", Calendar.getInstance()));
    System.out.println("Output of %tk is " + String.format("%tk", Calendar.getInstance()));
    System.out.println("Output of %tl is " + String.format("%tl", Calendar.getInstance()));
    System.out.println("Output of %tM is " + String.format("%tM", Calendar.getInstance()));
    System.out.println("Output of %tm is " + String.format("%tm", Calendar.getInstance()));
    System.out.println("Output of %tN is " + String.format("%tN", Calendar.getInstance()));
    System.out.println("Output of %tp is " + String.format("%tp", Calendar.getInstance()));
    System.out.println("Output of %tQ is " + String.format("%tQ", Calendar.getInstance()));
    System.out.println("Output of %tR is " + String.format("%tR", Calendar.getInstance()));
    System.out.println("Output of %tr is " + String.format("%tr", Calendar.getInstance()));
    System.out.println("Output of %tS is " + String.format("%tS", Calendar.getInstance()));
    System.out.println("Output of %ts is " + String.format("%ts", Calendar.getInstance()));
    System.out.println("Output of %tT is " + String.format("%tT", Calendar.getInstance()));
    System.out.println("Output of %tY is " + String.format("%tY", Calendar.getInstance()));
    System.out.println("Output of %ty is " + String.format("%ty", Calendar.getInstance()));
    System.out.println("Output of %tZ is " + String.format("%tZ", Calendar.getInstance()));
    System.out.println("Output of %tz is " + String.format("%tz", Calendar.getInstance()));
  }
}


Output:
Output of %tA is Sunday
Output of %ta is Sun
Output of %tB is May
Output of %tb is May
Output of %tC is 20
Output of %tc is Sun May 24 09:40:28 IST 2020
Output of %tD is 05/24/20
Output of %td is 24
Output of %te is 24
Output of %tF is 2020-05-24
Output of %tH is 09
Output of %th is May
Output of %tI is 09
Output of %tj is 145
Output of %tk is 9
Output of %tl is 9
Output of %tM is 40
Output of %tm is 05
Output of %tN is 650000000
Output of %tp is am
Output of %tQ is 1590293428650
Output of %tR is 09:40
Output of %tr is 09:40:28 AM
Output of %tS is 28
Output of %ts is 1590293428
Output of %tT is 09:40:28
Output of %tY is 2020
Output of %ty is 20
Output of %tZ is IST
Output of %tz is +0530

Argument Index

We can specify the argument index in the String format method for formatting by mentioning between “%” and “$”. The index always starts at 1.

In the below example, the 1st statement prints “Java” 2 times since we are passing the argument index as 1 twice. The 2nd statement prints only the 2nd string which we have passed since the argument index is 2.

Java String format example with an argument index

public class Democlass {

  public static void main(String[] args) {
    String str1 = "Java";
    String str2 = "Tutorial";
    System.out.println(String.format("%1$s %1$s %2$s" , str1,str2));
    System.out.println(String.format("%2$s", "Hello","world"));
  }
}


Output:
Java Java Tutorial
world

Alignment and Padding

We can also use the format() method for left/right alignment and padding the string with 0s.

Formatting integers

We can specify the width/length of a required integer by including space, left align, or right-align an integer, specifying the width of an integer by filling with 0s. The below example illustrates all these formatting types.

public class Democlass {

  public static void main(String[] args) {
    System.out.println(String.format("%d", 100)); //Integer
    System.out.println(String.format("[%5d]", 100)); //Right aligning-Prefixing 2 spaces to get length of integer as 5
    System.out.println(String.format("[%-5d]", 100)); //Left aligning integer of length 5 by suffixing 2 spaces
    System.out.println(String.format("[% d]", 100)); //space before an integer
    System.out.println(String.format("[%05d]", 100)); //Prefixing 2 0s to get length of integer as 5
    
  }
  
}
Output:
100
[  100]
[100  ]
[ 100]
[00100]

Formatting string

We can also format string based on left/right alignment using String format() method. The below example illustrates aligning strings

public class Democlass {

  public static void main(String[] args) {
    System.out.println(String.format("%s", "Java")); //String
    System.out.println(String.format("[%10s]", "Java")); //Right aligning - Prefixing 6 spaces to get string length as 10
    System.out.println(String.format("[%-10s]", "Java"));//Left aligning string of length 10 by suffixing 6 spaces
    System.out.println(String.format("[%.4s]", "Java language"));//Retrieve string based on maximum number of characters specified
  }
  
}
Output:
Java
[      Java]
[Java      ]
[Java]

Locale specific Formatting

We can format an integer value based on a specific locale using the Java String format method. Based on the locale, the format() method formats the numeric value.

import java.util.Locale;
public class Democlass {

  public static void main(String[] args) {
    System.out.println(String.format(Locale.US,"%,d", 1000000));
    System.out.println(String.format(Locale.FRENCH, "%,d",1000000));
    System.out.println(String.format(Locale.GERMAN, "%,d",1000000));
  }
  
}
1,000,000
1?000?000
1.000.000

Conclusion

This tutorial provides in detail all the available formatting methods available in the String class along with examples.

Reference

Translate »