English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, we will learn how to convert a String type variable to a boolean in Java.
To understand this example, you should understand the followingJava programmingTopic:
class Main { public static void main(String[] args) { //Create String Variable String str1 ="true"; String str2 ="false"; //Convert String to Boolean //Use parseBoolean() boolean b1 = Boolean.parseBoolean(str1); boolean b2 = Boolean.parseBoolean(str2); //Printing Boolean Value System.out.println(b1); // true System.out.println(b2); // false } }
In the above example, we use the parseBoolean() method of the Boolean class to convert a string variable to a Boolean value.
Here, Boolean is a wrapper class in Java. For more information, please visitJava Wrapper class.
We can also use the valueOf() method to convert a string variable to a boolean (Boolean value). For example,
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); //Printing 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 atJava Auto-boxing and Unboxing.
That is,
//valueOf() returns a Boolean object //Object to Boolean Conversion boolean b1 Boolean obj = Boolean.valueOf(str1)