Java Program to convert string to boolean

March 28, 2022, Learn eTutorial

Here we are explaining how to write a java program to convert a string to a boolean.

How to convert a string into a boolean in java?

In java, a string can be converted into a boolean by using Boolean.ValueOf() function.An example is shown below.

 Boolean B=Boolean.valueOf(str);

The function receives a string as an argument and returns the boolean value. If the string contains 'true' in uppercase or lowercase then the function returns the true value. Else return false.

How to implement the java program to convert string to boolean in java?

First, we have to declare the class StoB. Create an object of the scanner class as sc. Read the string from the user into the variable s using sc.nextLine(). Then convert the string s to boolean using Boolean.valueOf(s). If the string contains 'true' then it will return true else return false. Then display the boolean equivalent of s as b using System.out.println().


STEP 1: Declare the class StoB with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Create an object of the scanner class as sc.

STEP 4: Read the string from the user into the string variable s.

STEP 5: Convert the string variable s to boolean as Boolean b=Boolean.valueOf(s).

STEP 6: Display the boolean value of string s as b.

Java Source Code

                                          import java.util.Scanner;
public class StoB{  
   public static void main(String args[]){  
   Scanner sc = new Scanner(;
   System.out.println("Enter any string");
    String s = sc.nextLine(); 
    Boolean b=Boolean.valueOf(s);   
  System.out.println("The boolean equivalent of "+s+ " is "+b);  


Enter any string
The boolean equivalent of TRue is true