I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

This article is part of a series:
• Java String.String()
• Java String.format()
• Java String.codePointCount()
• Java String.codePointAt()
• Java String.concat()
• Java String.contains()
• Java String.copyValueOf()
• Java String.endsWith()
• Java String.format()
• Java String.getBytes()
• Java String.indexOf()
• Java String.intern()
• Java String.isEmpty()
• Java String.lastIndexOf()
• Java String.regionMatches()
• Java String.replace()
• Java String.replaceAll()
• Java String.split()
• Java String.startsWith()
• Java String.subSequence()
• Java String.substring()
• Java String.toLowerCase()
• Java String.toUpperCase()
• Java String.trim()
• Java String.valueOf()

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

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS