Table of contents
1.
Introduction
2.
Converting String to Boolean in Java
2.1.
Explanation
2.2.
Java String to boolean Example: Boolean.parseBoolean()
2.3.
Java String to boolean Example: Boolean.valueOf() method
3.
Converting String to Boolean in JavaScript
3.1.
Using the Identity Operator
3.2.
Using the Regular Expressions (RegEX)
3.3.
Using the Boolean Wrapper Class
3.4.
Using Double Not
3.5.
Space and Time Complexity
4.
Frequently Asked Questions
4.1.
Can you convert a string to a boolean?
4.2.
How to pass string to boolean?
4.3.
How to convert string false to boolean?
4.4.
What is the string format for a boolean?
5.
Conclusion
Last Updated: Mar 27, 2024
Medium

Java Convert String to Boolean

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Welcome Ninjas! There are times when we often need to convert a string to a boolean value during programming. There are built-in methods that can help us achieve the same. Converting a string to a boolean refers to transforming a string representation of a value into its corresponding boolean value.

Do you want to know how to convert string to boolean across different languages? Don’t worry. We got you covered!

Java Convert String to boolean

This article intends to help you get the hang of the concepts related to converting string to Boolean.

Also see, Swap Function in Java

Converting String to Boolean in Java

In this section, we will see how to convert the string to a boolean in Java. In Java, use Boolean.parseBoolean(string) to convert a String to a boolean. However, use the Boolean.valueOf(string) method if you wish to convert a String to a Boolean object function.

Explanation

  • False is the boolean equivalent of false(irrespective of case).
     
  • True is the boolean equivalent of true(irrespective of case).
     
  • The boolean equivalent of any other string is false since the given value is not equal to true.

Java String to boolean Example: Boolean.parseBoolean()

The method parseBoolean() turns a string to boolean primitive.

The parseBoolean() is the static method of the Boolean class. The signature of the parseBoolean() function is as follows:

public static int parseBoolean(String s);
You can also try this code with Online Java Compiler
Run Code


Here we present a simple example:

public class StringtoBoolean {
    public static void main(String args[]) {
        String string_1 = "true";
        String string_2 = "TRue";
        String string_3 = "ok";
        String string_4 = "Good Morning";
        boolean boolean_1 = Boolean.parseBoolean(string_1);
        boolean boolean_2 = Boolean.parseBoolean(string_2);
        boolean boolean_3 = Boolean.parseBoolean(string_3);
        boolean boolean_4 = Boolean.parseBoolean(string_4);
        System.out.println(boolean_1);
        System.out.println(boolean_2);
        System.out.println(boolean_3);
        System.out.println(boolean_4);
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

Java Output 1

Java String to boolean Example: Boolean.valueOf() method

Boolean.valueOf() converts a string to a Boolean object. Let's look at a simple Java code to convert String to Boolean.

public class StringtoBooleanObject{
    public static void main(String args[]) {
        String string_1 = "false";
        String string_2 = "1";
        String string_3 = "Hello World";
        String string_4 = "TRue";
        boolean boolean_1 = Boolean.valueOf(string_1);
        boolean boolean_2 = Boolean.valueOf(string_2);
        boolean boolean_3 = Boolean.valueOf(string_3);
        boolean boolean_4 = Boolean.valueOf(string_4);
        System.out.println(boolean_1);
        System.out.println(boolean_2);
        System.out.println(boolean_3);
        System.out.println(boolean_4);
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

Java Output 2

Also see, Duck Number in Java and Hashcode Method in Java.

Converting String to Boolean in JavaScript

In this section, we will see converting string to boolean in Javascript. There are different methods in Javascript to do so. Let’s explore them one by one.

Using the Identity Operator

The identity operator is denoted by (===). The identity operator is also known as a strict equality operator. It returns true if both values are compared and are of the same type and have the same value. It sees if the value on the left-hand side is equal to the value on the right-hand side and returns true if it is and false if it is not. We can also use it to change a string to a boolean.

Essentially, we will compare our string to the " true " string. As a result, the output we get will be a boolean true only if our string is "true". Any other string will result in the function returning a false boolean value.

let sampleString1 = "true"; 
let booleanOutput1 = (sampleString1 === "true"); 	// This returns true

let sampleString2 = "Test";
let booleanOutput2 = (sampleString2 === "true"); 	// This returns false
You can also try this code with Online Javascript Compiler
Run Code

Using the Regular Expressions (RegEX)

Regular expressions (RegEx) are basically patterns used to match and test string character combinations.

For this blog, we'll utilize the most basic version of regular expressions in JavaScript - we'll write a simple regex that matches "true" and compare it to our text using the test() method.

This is case-sensitive, as it will return false if there is any tiny case inconsistency. To correct this, add /i to the end of the regular expression to ensure a case-insensitive match:

let stringValue = "true"; 
let boolValue = (/true/).test(stringValue); 	//This returns true

let stringValue = "True"; 
let boolValue = (/true/).test(stringValue); 	// This returns false

let stringValue = "True"; 
let boolValue = (/true/i).test(stringValue); // This returns true
You can also try this code with Online Javascript Compiler
Run Code

Using the Boolean Wrapper Class

For storing boolean values, JavaScript includes a built-in Boolean object. It's an object wrapper for boolean values, wrapping around other objects and transforming them into legal boolean values. This is accomplished by testing an object's true-false value. In general, empty items are assessed as false and non-empty objects as true.

Using the Boolean wrapper, any string that isn't an empty string will evaluate as true.

let String1 = Boolean('true'); 		// This returns true
let String2 = Boolean(''); 			// This returns false
let String3 = Boolean('false'); 		// This returns true
let String4 = Boolean('True'); 		// This returns true
You can also try this code with Online Javascript Compiler
Run Code


There are two key concerns at stake here:

  • The first is that this function will return true for an empty string containing at least one blank character (space, tab, etc.), which is why we must be cautious when using it.
     
  • Second, transforming "false" to a boolean value of false fails because every non-empty string converts to true.

Using Double Not

  • The double NOT operator (!!) is equivalent to employing the logical NOT operator (!) twice, inverting the result of the single NOT operator.
     
  • When we use the double NOT operator, the values are flipped, resulting in a pure boolean conversion.
     
  • The double NOT (!!) operator is shorter but functions the same as the Boolean wrapper. It is, however, more difficult to read if you are unfamiliar with the logical NOT (!) operator.
     
  • We must also be cautious while using this approach because an empty string with at least one blank character will still return true, and attempting to convert a string of "false" to a boolean value of false will likewise fail (just as Boolean Object).
     
let myString1 = !'hello’; 		// This returns false
let myString2 = !''; 			// This returns true
 
let myString1 = !!'hello'; 		// This returns true
let myString2 = !!''; 			// This returns false
You can also try this code with Online Javascript Compiler
Run Code

Space and Time Complexity

The time and space complexity both are O(1) and O(1) respectively in all the ways mentioned to convert string to boolean. 

Check out this problem - Longest Common Prefix

Must Read: Java System Out Println

Frequently Asked Questions

Can you convert a string to a boolean?

Yes, we can convert a string to a boolean in java by using methods such as Boolean.parseBoolean() or Boolean.valueOf(). 

How to pass string to boolean?

We can pass a string to boolean by using Boolean.parseBoolean() or Boolean.valueOf() method in java. This method accepts a string argument and returns a boolean value. The string is converted to ‘true’ or ‘false’.

How to convert string false to boolean?

We can use parseBoolean() method or compare the string to the lowercase string “false” using the equals() method to assign boolean values to convert string “false” to boolean value of “false”. For storing boolean values, JavaScript includes a built-in Boolean object. It's an object wrapper for boolean values, wrapping around other objects and transforming them into legal boolean values.

What is the string format for a boolean?

The format specifers %b or %B are used for formatting boolean expressions with String#printf(). These format specifers format the boolean value as a string. The resulting string will be “true” for a `true` value and “false” for a `false` value. `%b` format secifier gives result in lowercase string while `%B` gives the values in uppercase letters.

Conclusion

In this article, we have discussed the conversion of string to boolean in detail. We started with a basic introduction to strings and boolean values. Then we discussed the conversion in two programming languages, Java and JavaScript. In Java, we discussed two methods: Boolean.parseBoolean() and Boolean.valueOf(). In JavaScript, we discussed four ways (Using Identity operator, RegEx, boolean wrapper class, and double not)  to change string to boolean.

To explore more interesting coding-related articles refer to the following links:

Recommended problems -

Please refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. And also, enroll in our courses and refer to the mock test and problems available. Have a look at the interview experiences and interview bundle for placement preparations.

Keep learning, and Keep Growing!

Happy Learning!

Live masterclass