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