Java String.format ()

La méthode format () formate une String en utilisant un format String et des arguments. Par exemple, les caractères "s" et "S" ont la valeur "null" si l’argument arg est null.

Si arg implémente Formattable, alors la méthode Formattable, alors la méthode arg.formatTo () est appelée. Sinon, le résultat est évalué en appelant arg.toString () .

Pour plus d’informations sur le formatage, visitez le site Javadoc .

Signatures disponibles

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

Exemple

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

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

Lance

  • IllegalFormatException - Si le format String contient un invalide

syntaxe.

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

Suivant "

  • "** Précédent