Write Java program to Convert string to Boolean


This is a Java program that demonstrates how to convert a string to a boolean value.

  • The program first declares a Scanner object input to read user input from the console. It then prompts the user to enter a string using the print method.
  • The program reads the user input using the next() method of the Scanner class and stores it in the str variable.
  • It then converts the string to a boolean value using the constructor of the Boolean class. The constructor takes a string parameter and returns a boolean value that is equivalent to the string. If the string is equal to "true" (ignoring case), the constructor returns true. Otherwise, it returns false.
  • The resulting boolean value is stored in the bool variable, which is then output to the console using the println method.

Note that the Boolean constructor can also take a boolean value as a parameter and return a Boolean object that represents the same value. Additionally, the String class provides a static method valueOf that can be used to convert a string to a boolean value, which returns a primitive boolean rather than a Boolean object.

Source Code

import java.util.Scanner;
public class String_toBoolean 
{
	public static void main(String[] args) 
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the String : ");
		String str = input.next();
 
		// Convert string to boolean using constructor
		Boolean bool = new Boolean(str);
		System.out.println("Boolean value is : " +bool);
	}  
}

Output

Enter the String : Java
Boolean value is : false