How to convert a string to a boolean in Java

Overview

We can convert a string to a Boolean value in Java using the Boolean class. We do this by passing the string to its constructor statement.

Syntax

Boolean booleanVariable = new Boolean(string)
The syntax to convert a string to Boolean in Java

Parameters

  • Boolean: This is the Boolean class whose constructor will be used to convert a string to a boolean.
  • booleanVariable: This is the variable's name that will contain the converted string.
  • new: This is the keyword used to create a new instance or the new Boolean value.
  • string: This is the string value we want to convert to a Boolean value.

Return value

The value returned is a Boolean, which is equivalent to the string.

Example

class HelloWorld {
public static void main( String args[] ) {
// create some strings
String str1 = "true";
String str2 = "false";
String str3 = "1";
String str4 = "0";
// Convert using constructor
Boolean bool1 = new Boolean(str1);
Boolean bool2 = new Boolean(str2);
Boolean bool3 = new Boolean(str3);
Boolean bool4 = new Boolean(str4);
// print results
System.out.println("Boolean value is : " +bool1);
System.out.println("Boolean value is : " +bool2);
System.out.println("Boolean value is : " +bool3);
System.out.println("Boolean value is : " +bool4);
}
}

Explanation

  • Lines 4-7: We create some strings.
  • Lines 10-13: We convert the strings to Boolean values.
  • Lines 16-19: We print the results to the console screen.

Free Resources