Java | String format()
La méthode java string format() renvoie une chaîne formatée en utilisant les paramètres fournis. La méthode format() en Java est comme la fonction sprintf() en langage C et la méthode printf() en langage java.
Syntaxe
public static String format(String format, Object...args)
Paramètres
- format(Obligatoire) : format de la chaîne.
- args(Obligatoire) : Arguments pour la chaîne format.
Valeur de retour
Cette méthode renvoie une chaîne formatée.
Exemple 1:
Le code suivant montre l’utilisation de la méthode format() en Java:
public class Main { public static void main(String args[]) { String str = "WayToLearnX"; // Concaténation de deux chaînes String str1 = String.format("Welcome to %s", str); System.out.println(str1); // Afficher jusqu'à 2 décimales String str2 = String.format("Valeur = %.2f", 89.9681024); System.out.println(str2); } }
Sortie:
Welcome to WayToLearnX Valeur = 89.97
Exemple 2:
public class Main { public static void main(String args[]) { String name = "Thomas"; int age = 25; //%1$ premier argument, %2$ deuxième argument String str = String.format("My name: %1$s, My age: %2$d", name, age); System.out.println(str); } }
Sortie:
My name: Thomas, My age: 25