English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Base Tutorial

Contrôle de flux Java

Java Tableau

Java Orienté objet (I)

Java Orienté objet (II)

Java Orienté objet (III)

Java Exception Handling

Java Liste (List)

Java Queue (file d'attente)

Java Map de collections

Java Set de collections

Java Entrée/Sortie (I/O)

Reader Java/Writer

Autres sujets Java

Le programme Java convertit une variable de type String en int

Java example complete list

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 :

Example1:Programme Java utilisant parseInt() pour convertir une chaîne en int

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
  }
}

Example2:Le programme Java utilise valueOf() pour convertir une chaîne en int

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)

  Java example complete list