Formatting Strings in Java: String.format() Method
Of the three primary ways to format a string in Java – String.format( ), printf( ), or MessageFormat – the String.format( ) is the method most commonly used.
Join the DZone community and get the full member experience.
Join For FreeWhile System.out.println()
is fine for debugging and displaying simple messages, it is not great for formatting strings. Formatted strings not only display the string content, but they also show the content in a specified sequence. For instance, when displaying large integers like 100000000
, you may want to include commas so that it appears as 100,000,000
. Similarly with decimal numbers, you might want to show a specific number of decimal places like 199.53
along with rounding. Programmers will be happy to know that Java offers a few formatting methods with ample support for a variety of data types like Double
, Integer
, and Date
.
Core Java Specialization | Enroll in Free Online Course Today*
*Affiliate link. See Terms of Use.
There are three primary ways to format a string in Java. You can use the String.format()
method, the printf()
method, or the MessageFormat
class for formatting strings. Of these, the String.format()
method is the most commonly used, so we will be covering it in this Java programming tutorial.
String.format() Method Syntax in Java
Java's String.format()
is a static method that returns a formatted String using the given locale, format String
, and arguments. It comes in two flavors, as follows:
public static String format(String format, Object... args)
public static String format(Locale locale, String format, Object... args)
locale
: the locale applied during formatting. However, if it isnull
the localization is not applied.format
: theString
to format.args
: the parameter referenced by format specifiers in the formatString
. If the arguments are more than the format specifiers, the extra arguments are ignored. The number of arguments can vary and may be omitted completely.
Here is an example of how to use String.format()
in Java:
class StringFormatExample {
public static void main(String[] args) {
String name = "Rob Gravelle";
String str = String.format("My name is %s", name);
System.out.println(str); // My name is Rob Gravelle
}
}
The locale argument is especially useful for formatting numbers and dates according to the rules of a given locale. For example, here is a locale value of "France"
that replaces the decimal point with a comma, as per the France number system:
import java.util.*;
class StringFormatLocaleExample {
public static void main(String[] args) {
System.out.format(
Locale.FRANCE,
"The value of the float " + "variable is %f ",
10.3242342
); // The value of the float variable is 10,324234.
}
}
String.format() Exceptions in Java
You should be aware that the String.format()
method throws a couple of exceptions:
NullPointerException
: This exception is thrown if the String argument passed isnull
.IllegalFormatException
: If the format specified is illegal or there are insufficient arguments.
Developers almost never catch these exceptions, as they tend to indicate improper use of the method rather than some kind of expected runtime exception. New to Java? Check out this tutorial on understanding the Java Record
class.
Formatting String Width, Alignment, and Padding in Java
The String.format()
method also allows programmers to set the width, alignment, and padding of the formatted String
. The following class contains examples of each, as well as various combinations:
public class StringFormatWidthAndPaddingExample {
public static void main(String[] args) {
String greeting = "Hi Rob";
// Text width
String.format("|%20s|", greeting);
// | Hi Rob|
System.out.println(greeting);
// Left justify text
String.format("|%-20s|", greeting);
// |Hi Rob |
System.out.println(greeting);
// Maximum number of characters
String.format("|%.3s|", greeting);
// |Hi |
System.out.println(greeting);
// Max. characters with width
String.format("|%20.3s|", greeting);
// | Hi |
System.out.println(greeting);
}
}
Specifying Types with String.Format()
As we saw in the locale argument example above, String.format()
can also be used to convert and format other data types into a string. To do that, Java provides a variety of Format Specifiers. These begin with a percent character (%) and terminate with a typechar "type character"
, which indicates the type of data (int
, float
, etc.) that will be converted, as well as the way in which the data will be represented (decimal
, hexadecimal
, etc.) The full syntax of a Format Specifier in Java is:
% [flags] [width] [.precision] [argsize] typechar
We can see in the program below how various Format Specifiers affect the displaying of data:
import java.util.Date;
public class StringFormatTypesExample {
public static void main(String[] args) {
String str1 = String.format("%d", 2112); // Integer value
String str2 = String.format("%f", 98.7); // Float value
String str3 = String.format("%x", 101); // Hexadecimal value
String str4 = String.format("%o", 023); // Octal value
String str5 = String.format("%tc", new Date()); // Date object
String str6 = String.format("%c", 'Z'); // Char value
System.out.println(str1); // 2112
System.out.println(str2); // 98.700000
System.out.println(str3); // 65
System.out.println(str4); // 23
System.out.println(str5); // Thu Jan 05 20:52:06 GMT 2023
System.out.println(str6); // Z
}
}
Here is the full list of Format Specifiers for the String.format()
method:
%%
- Inserts a "%" sign%x/%X
- Integer hexadecimal%t/%T
- Time and Date%s/%S
- String%n
- Inserts a newline character%o
- Octal integer%f
- Decimal floating-point%e/%E
- Scientific notation%g
- Causes Formatter to use either%f
or%e
, whichever is shorter%h/%H
- Hash code of the argument%d
- Decimal integer%c
- Character%b/%B
- Boolean%a/%A
- Floating-point hexadecimal
Note that some specifiers may be either lowercase or uppercase. The case of the specifier dictates the case of the formatted letters. Other than that, the conversion performed is the same, regardless of case.
Argument Index and String.format()
The String.format()
can accept multiple Objects
to format. The Argument Index is an integer indicating the position of the argument in that list of Objects
. Not to be confused with the Numbered Groups of the String.replace()
function ($1
, $2
, etc.), Argument Indexes place the number BEFORE the dollar sign. Hence, the first argument is referenced by 1$
, the second by 2$
, and so on. Here is a program that formats two pieces of data: a float
and a String
:
public class StringFormatArgumentIndexExample {
public static void main(String[] args) {
String product = "Bread";
double price = 4.99;
String str = String.format("The price of %2$s is CAD $%1$.2f today.", price, product);
// The price of Bread is CAD $4.99 today.
System.out.println(str);
}
}
Final Thoughts on Formatting Strings in Java
Although there are several ways to format a string in Java, the String.format()
method is the most commonly used due to its tremendous versatility. From localization, type conversion, width, alignment and padding, it has got you covered!
Opinions expressed by DZone contributors are their own.
Comments