Java Program to convert boolean to string


September 26, 2021, Learn eTutorial
610

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

How to convert boolean to string in java?

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

 String s = new Boolean(bln).toString();

Here bln is the boolean variable and s is the string variable. The boolean variable bln is converted into the string variable s.

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

First, we have to declare the class BtoS. Create an object of the scanner class as sc. Read the boolean variable from the user into the variable bn.Convert bn to string by using Boolean().toString() function in java.The function returns the string value equivalent to the boolean variable bn. Then display the boolean value bn using the system.out.println() in java.

ALGORITHM

STEP 1: Declare the class BtoS 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 boolean value from the user into the variable bn using sc.nextBoolean().

STEP 5: Convert the boolean to string using Boolean(bn).toString().

STEP 6: Display the string equivalent of bn as str.

Java Source Code

                                          import java.util.Scanner;
public class BtoS{  
   public static void main(String args[]){  
   Scanner sc = new Scanner(System.in);
   System.out.println("Enter the boolean value");
   boolean bn = sc.nextBoolean();
   String str = new Boolean(bn).toString();
    
 System.out.println("The string equivalent of "+bn+ " is "+str);  
   }
}
                                      

OUTPUT

Enter the boolean value
true
The string equivalent of true is true