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

Tutoriel de base Java

Contrôle de flux Java

Java Tableau

Java Orienté Objet (I)

Java Orienté Objet (II)

Java Orienté Objet (III)

Gestion des exceptions Java

Liste Java (List)

Java Queue (file d'attente)

Java Map (dictionnaire)

Java Set (ensemble)

Java Entrée/Sortie (I/)

Reader Java/Writer

Autres sujets Java

Le programme Java convertit les variables de type string (string) en valeur boolean (boolean)

    Java instance complete set

Dans ce programme, nous allons apprendre à convertir une variable de type String en boolean en Java.

Pour comprendre cet exemple, vous devriez comprendre ce qui suitProgrammation JavaSujet :

Example1:Utilisation de parseBoolean() pour convertir une chaîne en valeur booléenne

class Main {
  public static void main(String[] args) {
    //Create string variable
    String str1 = "true";
    String str2 = "false";
    //Convert string to boolean value
    //Utilisation de parseBoolean()
    boolean b1 = Boolean.parseBoolean(str1);
    boolean b2 = Boolean.parseBoolean(str2);
    //Print boolean value
    System.out.println(b1);    // true
    System.out.println(b2);    // false
  }
}

Dans l'exemple ci-dessus, nous utilisons la méthode parseBoolean() de la classe Boolean pour convertir une variable de chaîne en valeur booléenne.

Ici, Boolean est une classe Wrapper dans Java. Pour plus d'informations, veuillez visiterClasse Wrapper Java.

Example2:Utilisation de valueOf() pour convertir une chaîne en valeur booléenne

Nous pouvons également utiliser la méthode valueOf() pour convertir une variable de chaîne en boolean (valeur booléenne). Par exemple,

class Main {
  public static void main(String[] args) {
    //Create string variable
    String str1 = "true";
    String str2 = "false";
    //Convert string to boolean value
    //Using valueOf()
    boolean b1 = Boolean.valueOf(str1);
    boolean b2 = Boolean.valueOf(str2);
    //Print boolean value
    System.out.println(b1);    // true
    System.out.println(b2);    // false
  }
}

In the above example, the valueOf() method of the Boolean class converts the string variable to a boolean value.

Here, the valueOf() method actually returns an object of the Boolean class. However, the object will automatically convert to the primitive type. In Java, this is called unboxing. For more information, please visitJava automatic boxing and unboxing.

That is,

//valueOf() returns a boolean object
//Object conversion to boolean value
boolean b1 = Boolean obj = Boolean.valueOf(str1)

Java instance complete set