Write a Java Program to convert string type variables into boolean

Converting a string variable to a boolean in Java is a common task that is useful in various scenarios.

In this tutorial, we will go through a simple Java program to convert string type variables into boolean.


First, let’s define the problem.

We have a string variable, and we want to convert it to a boolean variable.

The string variable can have the value “true” or “false” (case insensitive).

We can achieve this by using the Boolean.parseBoolean() method provided by Java.

Here’s an example program that takes a string variable and converts it to a boolean:

public class StringToBoolean {
    public static void main(String[] args) {
        String strBool = "true";
        boolean boolValue = Boolean.parseBoolean(strBool);
        System.out.println(boolValue); // prints true
    }
}

In this program, we first define a string variable strBool with the value “true”.

Then we use the Boolean.parseBoolean() method to convert the string variable to a boolean variable.

Finally, we print the boolean value to the console.

If we want to convert a string variable that contains “false”, we can simply replace the string value “true” with “false” in the above program.

public class StringToBoolean {
    public static void main(String[] args) {
        String strBool = "false";
        boolean boolValue = Boolean.parseBoolean(strBool);
        System.out.println(boolValue); // prints false
    }
}

In conclusion, converting a string variable to a boolean in Java is a simple task that can be achieved using the Boolean.parseBoolean() method.

This method is useful in various scenarios, such as when reading configuration files or user input.