English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Neste programa, vamos aprender como converter uma variável do tipo String em booleano no Java.
Para entender este exemplo, você deve saber o seguinteProgramação JavaTema:
class Main { public static void main(String[] args) { //Create string variable String str1 = "true"; String str2 = "false"; //Convert string to boolean //Usar parseBoolean() boolean b1 = Boolean.parseBoolean(str1); boolean b2 = Boolean.parseBoolean(str2); //Print boolean value System.out.println(b1); // true System.out.println(b2); // false } }
No exemplo acima, usamos o método parseBoolean() da classe Boolean para converter uma variável de string em valor lógico.
Aqui, Boolean é uma classe wrapper do Java. Para obter mais informações, acesseClasse Wrapper do Java.
Ainda podemos usar o método valueOf() para converter uma variável de string em booleano (valor lógico). Por exemplo,
class Main { public static void main(String[] args) { //Create string variable String str1 = "true"; String str2 = "false"; //Convert string to boolean //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 is automatically converted to the primitive type. In Java, this is called unboxing. Learn more, visitJava Auto-boxing and Unboxing.
That is,
//valueOf() returns a boolean object //Object conversion to boolean value boolean b1 = Boolean obj = Boolean.valueOf(str1)