Java Convert String To Boolean Example

In this article, we will show you how to convert Java String to wrapper Boolean class or primitive type boolean code examples. There are different ways we can convert Java String to Boolean. This is a common scenario to convert String to Boolean in java programming language.
In this post, we will demonstrate converting String to Boolean in 3 ways.
  1. Convert using Boolean.parseBoolean()
  2. Convert using Boolean.valueOf()
  3. Convert using new Boolean(String).booleanValue()
Please refer the comments in below program are self descriptive.
/**
 * ConvertStringToBooleanExamples
 * @author javaguides.net
 *
 */
public class ConvertStringToBooleanExamples {
    public static void main(String[] args) {
     // Convert using Long.parseLong()
     String numberAsString = "true";
     boolean b = Boolean.parseBoolean(numberAsString);
     System.out.println("Convert using Boolean.parseBoolean() :: " + b);

     // Convert using Boolean.valueOf()
     boolean b1 = Boolean.valueOf(numberAsString);
     System.out.println("Convert using Boolean.valueOf() :: " + b1);

     // Convert using new Long(String).longValue()
     Boolean longObject = new Boolean(numberAsString);
     boolean b3 = longObject.booleanValue();
     System.out.println("Convert using new Boolean(numberAsString).booleanValue() :: " + b3);  }
}
Output:
Convert using Boolean.parseBoolean() :: true
Convert using Boolean.valueOf() :: true
Convert using new Boolean(numberAsString).booleanValue() :: true

Comments