This example shows how to convert string to boolean in Java using the parseBoolean method of the Boolean wrapper class including the empty and null values.
How to convert String to boolean in Java?
To convert a string to a boolean primitive value, use the parseBoolean
method of the Java Boolean wrapper class.
1 |
public static boolean parseBoolean(String strBoolean) |
This method returns a boolean primitive value by parsing the input string value.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.javacodeexamples.basic; public class StringToBooleanExample { public static void main(String[] args){ String strBoolean = "true"; boolean b = Boolean.parseBoolean(strBoolean); System.out.println("String to boolean: " + b); } } |
Output
1 |
String to boolean: true |
Important Note:
The parseBoolean
method returns true if the string value is not null and contains “true” ignoring the case. For every other value, the parseBoolean
method returns a false boolean value.
Here are some of the example string values and their possible boolean outputs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
//true System.out.println( Boolean.parseBoolean("true") ); //true System.out.println( Boolean.parseBoolean("TrUe") ); //true System.out.println( Boolean.parseBoolean("TRUE") ); //false System.out.println( Boolean.parseBoolean("false") ); //false System.out.println( Boolean.parseBoolean("123") ); //false System.out.println( Boolean.parseBoolean("432.324") ); //false System.out.println( Boolean.parseBoolean("yes") ); //false System.out.println( Boolean.parseBoolean("no") ); //false System.out.println( Boolean.parseBoolean("") ); //false System.out.println( Boolean.parseBoolean(null) ); |
Please note that the parseBoolean
method returns a false boolean value even for an empty string value (“”) and a null value.
This example is a part of the Java Basic Examples and Java Type conversion Tutorial.
Please let me know your views in the comments section below.