In this tutorial/Program, you’ll be learning how to convert a String to a boolean with the help of the below examples.
Let’s first see how many boolean values are present 1. true 2. false.
In this Program When converting a String to a boolean, if the string contains the value “true” 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()
public class JavaExample{ public static void main(String args[]){ String str1 = "FALSE"; String str2 = "InsertAnything"; String str3 = "TRUE"; 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
true false false
We have used 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 the 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.
Java String to boolean using Boolean.valueOf()
public class JavaExample{ public static void main(String args[]){ String str1 = "InsertAnything"; String str2 = "true"; String str3 = "TruE"; 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
true true false
Here we will see another method which we can use for a string to boolean conversion. Similar to Boolean.parseBoolean() method, the Boolean.valueOf() method accepts a string as an argument and returns a boolean value true or false.
Related Programs
- Java Program to Convert Milliseconds to Minutes and Seconds
- Java Program to Calculate Standard Deviation
- Java Program to Check Armstrong Number
- Java Program to Calculate Average Using Arrays
- Java Program to search a number using linear search
- Java Program to reverse the Array
Ask your questions about Java Program for decimal to hexadecimal conversion in Java and clarify your/others doubts by commenting. Documentation.
Please write to us at [email protected] to report any issue with the above content or for feedback.