In this guide, we will see how to convert a String to a boolean with the help of examples.
When converting a String to a boolean value, if the string contains the value “true” (case doesn’t matter) then the boolean value after the conversion would be true, if the string contains any other value other than “true” then the converted boolean value would be “false”.
Java String to boolean conversion using Boolean.parseBoolean() method example
Here we have three Strings str1, str2 and str3 and we are converting them into boolean value using the Boolean.parseBoolean() method, this method accepts String as an argument and returns boolean value true or false. If the value of the string is “true” (in any case uppercase, lowercase or mixed) then this method returns true, else it returns false.
public class JavaExample{ public static void main(String args[]){ String str1 = "true"; String str2 = "FALSE"; String str3 = "Something"; boolean bool1=Boolean.parseBoolean(str1); boolean bool2=Boolean.parseBoolean(str2); boolean bool3=Boolean.parseBoolean(str3); System.out.println(bool1); System.out.println(bool2); System.out.println(bool3); } }
Output:
Java String to boolean using Boolean.valueOf() example
Here we will see another method which we can use for string to boolean conversion. Similar to Boolean.parseBoolean() method, the Boolean.valueOf() method accepts string as an argument and returns a boolean value true or false.
public class JavaExample{ public static void main(String args[]){ String str1 = "true"; String str2 = "TRue"; String str3 = "Something"; boolean bool1=Boolean.valueOf(str1); boolean bool2=Boolean.valueOf(str2); boolean bool3=Boolean.valueOf(str3); System.out.println(bool1); System.out.println(bool2); System.out.println(bool3); } }
Output:
Leave a Reply