Java String.format()

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 »

« Previous

Leave a Reply

Your email address will not be published.