English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce programme, nous allons apprendre comment convertir une variable entière (int) en chaîne de caractères en Java.
Pour comprendre cet exemple, vous devriez comprendre ce qui suitJava programmationSujet :
class Main { public static void main(String[] args) { // Create int variable int num1 = 36; int num2 = 99; // convertir int en chaîne de caractères // en utilisant valueOf() String str1 = String.valueOf(num1); String str2 = String.valueOf(num2); //afficher la variable de chaîne System.out.println(str1); // 36 System.out.println(str2); // 99 } }
Dans l'exemple ci-dessus, nous avons utilisé la méthode valueOf() de la classe String pour convertir la variable int en chaîne de caractères.
Remarque:C'est la meilleure méthode pour convertir une variable int en chaîne de caractères en Java.
Nous pouvons également utiliser la méthode toString() de la classe pour convertir la variable int en chaîne de caractères Integer. Par exemple,
class Main { public static void main(String[] args) { // Create int variable int num1 = 476; int num2 = 78656; // convertir int en chaîne de caractères // en utilisant toString() String str1 = Integer.toString(num1); String str2 = Integer.toString(num2); //afficher la variable de chaîne System.out.println(str1); // 476 System.out.println(str2); // 78656 } }
Dans l'exemple ci-dessus, nous avons utilisé la méthode toString() de la classe Integer pour convertir la variable int en chaîne de caractères.
ici, Integer est une classe de paquet. Pour plus d'informations, veuillez visiterJava classes de paquet.
class Main { public static void main(String[] args) { // Create int variable int num1 = 3476; int num2 = 8656; //convertir int en chaîne de caractères // en utilisant + sign String str1 = "" + num1; String str2 = "" + num2; //afficher la variable de chaîne System.out.println(str1); // 3476 System.out.println(str2); // 8656 } }
Note this line,
String str1 = "" + num1;
Here, we use string concatenation operations to convert an integer to a string. For more information, please visitJava string concatenation.
class Main { public static void main(String[] args) { // Create int variable int num = 9999; //Use format() to convert int to string String str = String.format("%d", num); System.out.println(str); // 9999 } }
Here, we use the format() method to format the specified int variable into a string. For more information on string formatting, please visitJava String format().