The method format() formats a String using a format String and arguments. For example, characters ‘s’ and ‘S’ evaluate to “null” if the argument arg is null.
If arg implements Formattable, then the method Formattable, then the method arg.formatTo() is invoked. Otherwise, the result is evaluated by invoking arg.toString().
Here are a few additional specifiers commonly used in Java:
- %b: Boolean representation.
- %c: Single character representation.
- %d: Decimal integer representation.
- %x: Hexadecimal integer representation.
- %f: Floating-point numbers (e.g., for formatting doubles).
- %e: Exponential notation.
For more information on formatting, visit the Javadoc.
Available Signatures
public static String format(String format, Object... args)
public static String format(Locale l, String format, Object... args)
Example
@Test
public void whenFormat_thenCorrect() {
String value = "Baeldung";
String formatted = String.format("Welcome to %s!", value);
assertEquals("Welcome to Baeldung!", formatted);
boolean boolValue = true;
String formattedBool = String.format("Boolean: %b", boolValue);
assertEquals("Boolean: true", formattedBool);
char charValue = 'A';
String formattedChar = String.format("Character: %c", charValue);
assertEquals("Character: A", formattedChar);
int intValue = 255;
String formattedInt = String.format("Decimal: %d", intValue);
assertEquals("Decimal: 255", formattedInt);
String formattedHex = String.format("Hex: %x", intValue);
assertEquals("Hex: ff", formattedHex);
double floatValue = 123.456789;
String formattedFloat = String.format("Float: %.2f", floatValue);
assertEquals("Float: 123.46", formattedFloat);
String formattedExponential = String.format("Exponential: %e", floatValue);
assertEquals("Exponential: 1.234568e+02", formattedExponential);
}
The String.format() method also allows multiple format specifiers in one go which produces a single string that contains the formatted values:
String multipleFormat = String.format(
"Boolean: %b, Character: %c, Decimal: %d, Hex: %x, Float: %.2f, Exponential: %e",
boolValue, charValue, intValue, intValue, floatValue, floatValue
);
assertEquals("Boolean: true, Character: A, Decimal: 255, Hex: ff, Float: 123.46, Exponential: 1.234568e+02",
multipleFormat);
Error Handling and Exceptions
The FormatFlagsConversionMismatchException occurs when incompatible flags are provided for a format specifier. For example, using both %+ and %s (string conversion) together is invalid:
@Test
public void whenIncompatibleFlags_thenFormatFlagsConversionMismatchExceptionThrown() {
assertThrows(FormatFlagsConversionMismatchException.class, () -> {
String formatted = String.format("%+s", "Baeldung");
});
}
While IllegalFormatPrecisionException exception occurs when we attempt to use precision with a format type that doesn’t support it such as integers:
@Test
public void whenInvalidPrecisionForType_thenIllegalFormatPrecisionExceptionThrown() {
assertThrows(IllegalFormatPrecisionException.class, () -> {
String formatted = String.format("%.2d", 123);
});
}
The MissingFormatArgumentException exception is thrown when the number of format specifiers exceeds the number of arguments passed to String.format(). For example, if we provide one format specifier but no corresponding argument:
@Test
public void whenMissingFormatArgument_thenMissingFormatArgumentExceptionThrown() {
assertThrows(MissingFormatArgumentException.class, () -> {
String formatted = String.format("Welcome to %s and %s!", "Baeldung");
});
}
Locale-Based Formatting
Locales define different conventions for separating thousands and decimals:
@Test
public void whenNumberFormatWithLocales_thenCorrect() {
String frenchFormatted = String.format(Locale.FRANCE, "%,f", 1234567.89);
assertEquals("1 234 567,890000", frenchFormatted);
String germanFormatted = String.format(Locale.GERMANY, "%,.2f", 1234567.89);
assertEquals("1.234.567,89", germanFormatted);
}
Locales influence how dates are presented, with various ordering of day, month, and year:
@Test
public void whenDateFormatWithLocales_thenCorrect() {
LocalDate date = LocalDate.of(2023, 9, 30);
DateTimeFormatter usFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US);
String usFormatted = date.format(usFormatter);
assertEquals("09/30/2023", usFormatted);
DateTimeFormatter germanFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.GERMANY);
String germanFormatted = date.format(germanFormatter);
assertEquals("30.09.2023", germanFormatted);
}
Local conventions also impact how currency symbols and values are displayed, with different spacing and punctuation:
@Test
public void whenCurrencyFormatWithLocales_thenCorrect() {
NumberFormat usCurrencyFormat = NumberFormat.getCurrencyInstance(Locale.US);
String usFormatted = usCurrencyFormat.format(1000);
assertEquals("$1,000.00", usFormatted);
NumberFormat frenchCurrencyFormat = NumberFormat.getCurrencyInstance(Locale.FRANCE);
String frenchFormatted = frenchCurrencyFormat.format(1000);
assertEquals("1 000,00 €", frenchFormatted);
}