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().

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);
}

Throws

  • IllegalFormatException – If the format String contains an invalid syntax.
@Test(expected = IllegalFormatException.class)
public void whenInvalidFormatSyntax_thenIllegalFormatExceptionThrown() {
    String value = "Baeldung";
    String formatted = String.format("Welcome to %x!", value);
}
Next »
Java String.getBytes()
« Previous
Java String.endsWith()
Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.