English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce programme, nous allons apprendre à convertir une variable de type String en entier (int) en Java.
Pour comprendre cet exemple, vous devriez comprendre ce qui suitProgrammation JavaSujet :
class Main { public static void main(String[] args) { //Create a string variable String str1 = "23"; String str2 = "4566"; //Convert string to int //en utilisant parseInt() int num1 = Integer.parseInt(str1); int num2 = Integer.parseInt(str2); //Print int value System.out.println(num1); // 23 System.out.println(num2); // 4566 } }
Dans l'exemple ci-dessus, nous avons utilisé la méthode parseInt() de la classe Integer pour convertir une variable de chaîne en int.
Ici, Integer est une classe enveloppe en Java. Pour plus d'informations, visitezClasse enveloppe Java.
Attention:La variable de chaîne doit représenter une valeur int. Sinon, le compilateur déclenche une exception. Par exemple,
class Main { public static void main(String[] args) { //Create a string variable String str1 = "w3codebox"; //Convert string to int //en utilisant parseInt() int num1 = Integer.parseInt(str1); //Print int value System.out.println(num1); // lève une exception NumberFormatException } }
Nous pouvons également utiliser la méthode valueOf() pour convertir une variable de chaîne en objet Integer. Par exemple,
class Main { public static void main(String[] args) { //Create a string variable String str1 = "643"; String str2 = "1312"; //Convert string to int //Using valueOf() int num1 = Integer.valueOf(str1); int num2 = Integer.valueOf(str2); // Print int value System.out.println(num1); // 643 System.out.println(num2); // 1312 } }
In the above example, the valueOf () method of the Integer class converts the string variable to int.
In this case, the valueOf () method actually returns an Integer class object. However, the object is automatically converted to the primitive type. This is called unboxing in Java. For more information, please visitJava automatic boxing and unboxing.
That is,
// valueOf() returns an Integer object // Object conversion to int int num1 = Integer obj = Integer.valueOf(str1)