Signup/Sign In
PUBLISHED ON: AUGUST 21, 2021

Java String format() Method

The format() method of the String class uses a Locale, a formatting string, and arguments to format a string. It is a static method and returns a String. The String class contains two overloaded format() methods.

public static String format(String formatString, Object... args)
public static String format(Locale locale, String formatString, Object... args)

Both of the overloaded methods take variable Object-type arguments. Let's learn more about this method and how to use it to format strings.

Formatting String

The formatting string formats the given arguments and produces a String using them. A formatting string contains an argument index, flags, width definition, precision modifier, and conversion characters.

It may include additional Strings that we want to add in the final formatted String. The following shows the general structure of the formatting string.

%[argument-index$][flags][width][.precision][conversion-character]

Conversion Character

The conversion character is a mandatory part of the formatting String. Different conversion characters exist for data types.

Let's try to format a string using the String.format() method. In the code below, %s formats string type, %d formats integer types, and %f formats the floating data types. %n character adds a new line.

public class Demo
{	
	public static void main(String[] args)
	{
		String name = "Justin";
		int regno = 1001;
		double marks = 15.21;
		String summary = String.format("Student Name: %s %nReg.No: %d %nMarks: %f", name, regno, marks);
		System.out.print(summary);
	}
}


Student Name: Justin
Reg.No: 1001
Marks: 15.210000

Using Argument Index

Each argument passed to the format() method can be accessed by using an index. The index starts from 1, and a dollar sign($) follows it. This indexing helps us to access the same argument multiple times in the formatting string.

In the code below, we are accessing the second argument(name) twice. Then, we are accessing the first argument(marks).

public class Demo
{	
	public static void main(String[] args)
	{
		String name = "Justin";
		double marks = 15.21;
		String s = String.format("Name: %2$s Name: %2$s Marks: %1$f", marks, name);
		System.out.print(s);
	}
}


Name: Justin Name: Justin Marks: 15.210000

Precision Modifier

We can use the precision modifier to round off floating-point numbers. A dot(.) followed by the number of precision digits is used for this. Let's round off the value of Pi to four decimal places.

public class Demo
{	
	public static void main(String[] args)
	{
		double pi = 3.14159265359;
		String s = String.format("PI: %.4f", pi);
		System.out.print(s);
	}
}


PI: 3.1416

For other data types, it restricts the number of characters to be included in the final String.

public class Demo
{
	public static void main(String[] args)
	{
		String str1 = String.format("Precision with Strings Number: %.5s", "Hello World");
		String str2 = String.format("Precision with Boolean: %.3b", false);
		
		System.out.println(str1);
		System.out.println(str2);
	}
}


Precision with Strings Number: Hello
Precision with Boolean: fal

Width

Width denotes the minimum number of spaces that the argument should take. If an argument takes less space, then whitespaces are added.

We can add paddings by using an integer value with the formatting string.

For example, in the code below, integer 13 denotes the total length of the returned string. If the original arguments take up less space, then additional padding is added to the left.

public class Demo
{	
	public static void main(String[] args)
	{
		String name = "Justin";
		String s = String.format("%13s", name);//A padding of 7(13 - name.length()) is added
		System.out.print("||" + s + "||");
	}
}


|| Justin||

Flags

A Flag is a character used for modifying and formatting the output. We can use the minus(-) sign to left justify text. A comma(,) can be used as a flag to add thousands-separator.

public class Demo
{
	public static void main(String[] args)
	{
		String str1 = String.format("Left Justify:%-15d", 1000000000);
		String str2 = String.format("Thousands-separator: %,d", 1000000000);
		
		System.out.println("||" + str1 + "||");
		System.out.println(str2);
	}
}


||Left Justify:1000000000 ||
Thousands-separator: 1,000,000,000

Using Locales

If no Locale is mentioned, the format() method uses the default one by calling the Locale.getDefault() method. Let's try to use some other Locales to format an integer with the thousands separator.

import java.util.Locale;

public class Demo
{	
	public static void main(String[] args)
	{
		int million = 1000000;
		String s1 = String.format(Locale.GERMAN, "%,d", million);
		System.out.println(s1);
		
		String s2 = String.format(Locale.US, "%,d", million);
		System.out.print(s2);
	}
}


1.000.000
1,000,000

Formatting Date and Time

Date and time classes like LocalDate and LocalTime can also be formatted and converted to strings using the format() method.

All the conversion characters for formatting date and time include 't' or 'T'. We can format a LocalDate by using %tD. Similarly, we can use %tr to format LocalTime.

import java.time.*;

public class Demo
{
	public static void main(String[] args)
	{
		LocalDate date = LocalDate.now();
		String strDate = String.format("The Date is: %tD", date);
		
		LocalTime time = LocalTime.now();
		String strTime = String.format("The Time is: %tr", time);
		
		System.out.println(strDate);
		System.out.print(strTime);
	}
}


The Date is: 08/20/21
The Time is: 09:19:39 AM

We can also extract different components from a LocalDate. We can use %tA to fetch the day name, %tB to fetch the month name, %tC to get the century part of the year.

import java.time.*;

public class Demo
{
	public static void main(String[] args)
	{
		LocalDate date = LocalDate.now();
		
		String day = String.format("The Day is: %tA", date);
		String month = String.format("The Month is: %tB", date);
		String century  = String.format("The Century part of year is: %tC", date);
		
		System.out.println(day);
		System.out.println(month);
		System.out.print(century);
	}
}


The Day is: Friday
The Month is: August
The Century part of year is: 20

Similarly, we can use %tI to get the hours part from a LocalTime instance. Use %tM to fetch the minutes and %tS to fetch the seconds.

import java.time.*;

public class Demo
{
	public static void main(String[] args)
	{
		LocalTime time = LocalTime.now();
		
		String hour = String.format("The Hour is: %tI", time);
		String minute = String.format("The Month is: %tM", time);
		String seconds  = String.format("The Century part of year is: %tS", time);
		
		System.out.println("Time is: " + time);
		System.out.println(hour);
		System.out.println(minute);
		System.out.print(seconds);
	}
}


Time is: 11:34:22.275791700
The Hour is: 11
The Month is: 34
The Century part of year is: 22

Formatting Uppercase and Lowercase

We can format certain data types like String, char, boolean in uppercase or lowercase. For uppercase, we can use the Uppercase conversion characters. For example, %S will convert the String to uppercase, %C will transform a char to uppercase.

public class Demo
{
	public static void main(String[] args)
	{
		String str1 = String.format("Boolean Uppercase: %B", false);
		String str2 = String.format("String Uppercase: %S", "Hello World");
		String str3 = String.format("String Uppercase: %C", 'c');
		
		System.out.println(str1);
		System.out.println(str2);
		System.out.println(str3);
	}
}


Boolean Uppercase: FALSE
String Uppercase: HELLO WORLD
String Uppercase: C

No conversion character can convert uppercase to lowercase. For example, %s will not convert "HELLO WORLD" to lowercase.

public class Demo
{
	public static void main(String[] args)
	{
		String str1 = String.format("String: %s", "HELLO WORLD");
		String str2 = String.format("Character: %c", 'C');
		
		System.out.println(str1);
		System.out.println(str2);
	}
}


String: HELLO WORLD
Character: C

Formatting Numerics and Floating Points

We can use numeric conversion characters to format data types like int, short, byte, and long.

  • %d formats for decimal numbers(base 10).
  • %o converts to octal representation(base 8).
  • %x converts to hexadecimal number(base 16). %X will change the characters to uppercase.
public class Demo
{
	public static void main(String[] args)
	{
		String decimal = String.format("Decimal: %d", 43);
		String octal = String.format("Octal: %o", 43);
		String hexaUppercase = String.format("Hexadecimal(Uppercase): %X", 43);
		String hexaLowercase = String.format("Hexadecimal(Lowercase): %x", 43);
		
		System.out.println(decimal);
		System.out.println(octal);
		System.out.println(hexaUppercase);
		System.out.println(hexaLowercase);
	}
}


Decimal: 43
Octal: 53
Hexadecimal(Uppercase): 2B
Hexadecimal(Lowercase): 2b

%f conversion character is used for floating-point data types like double or float. We can also format in scientific notation by using %e or %E(for uppercase 'E' character).

public class Demo
{
	public static void main(String[] args)
	{
		String str1 = String.format("Floating Point: %f", 102301.12022);
		String str2 = String.format("Scientific Notation: %e", 102301.12022);
		String str3 = String.format("Scientific Notation(Uppercase): %E", 102301.12022);
		
		System.out.println(str1);
		System.out.println(str2);
		System.out.println(str3);
	}
}


Floating Point: 102301.120220
Scientific Notation: 1.023011e+05
Scientific Notation(Uppercase): 1.023011E+05

Exceptions Thrown

The String.format() method throws the NullPointerException when the formatting string is null.

public class Demo
{	
	public static void main(String[] args)
	{
		double marks = 15.21;
		String s = String.format(null, marks);
		System.out.print(s);
	}
}


Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.regex.Matcher.getTextLength(Matcher.java:1770)
at java.base/java.util.regex.Matcher.reset(Matcher.java:416)
at java.base/java.util.regex.Matcher.<init>(Matcher.java:253)
at java.base/java.util.regex.Pattern.matcher(Pattern.java:1135)
at java.base/java.util.Formatter.parse(Formatter.java:2700)
at java.base/java.util.Formatter.format(Formatter.java:2655)
at java.base/java.util.Formatter.format(Formatter.java:2609)
at java.base/java.lang.String.format(String.java:3302)
at Demo.main(Demo.java:6)

This method also throws the IllegalFormatException or a subclass of this exception. This exception occurs when the formatting string is of invalid syntax. The code below demonstrates this.

public class Demo
{	
	public static void main(String[] args)
	{
		double marks = 15.21;
		try {
		String s = String.format("%y", marks);
		}
		catch(Exception e){
			System.out.print(e.getClass().getSuperclass().getName());
		}
	}
}


java.util.IllegalFormatException

The actual exception thrown by the above code is UnknownFormatConversionException. It is a subclass of the IllegalFormatException.

public class Demo
{	
	public static void main(String[] args)
	{
		double marks = 15.21;
		String s = String.format("%y", marks);
	}
}


Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'y'
at java.base/java.util.Formatter$FormatSpecifier.conversion(Formatter.java:2839)
at java.base/java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2865)
at java.base/java.util.Formatter.parse(Formatter.java:2713)
at java.base/java.util.Formatter.format(Formatter.java:2655)
at java.base/java.util.Formatter.format(Formatter.java:2609)
at java.base/java.lang.String.format(String.java:3302)
at Demo.main(Demo.java:6)

Summary

String.format() is a convenient method to concatenate different arguments into a single String. It takes a formatting String and a varargs Object as parameters and an optional Locale. It uses a default Locale if no explicit Locale is provided. Make sure that the format string is of correct syntax to avoid the IllegalFormatException. A NullPointerException occurs if the formatting String is null.



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.