Java String.format ()

Die Methode format () formatiert einen String mit einem Format String und Argumenten. Zum Beispiel werden die Zeichen 's' und 'S' zu 'null' ausgewertet, wenn das Argument arg null ist.

Wenn arg Formattable implementiert, wird die Methode Formattable, die Methode arg.formatTo () aufgerufen. Andernfalls wird das Ergebnis durch Aufrufen von arg.toString () ausgewertet.

Weitere Informationen zum Formatieren finden Sie unter Javadoc .

Verfügbare Unterschriften

public static String format(String format, Object... args)
public static String format(Locale l, String format, Object... args)

Beispiel

@Test
public void whenFormat__thenCorrect() {
    String value = "Baeldung";
    String formatted = String.format("Welcome to %s!", value);

    assertEquals("Welcome to Baeldung!", formatted);
}

wirft

  • IllegalFormatException - Wenn das Format String ein ungültiges Format enthält

Syntax.

@Test(expected = IllegalFormatException.class)
public void whenInvalidFormatSyntax__thenIllegalFormatExceptionThrown() {
    String value = "Baeldung";
    String formatted = String.format("Welcome to %x!", value);
}

Nächster "

  • "** Bisherige