Convert String to Boolean in Java

1. Introduction

Converting a string to a boolean in Java is a straightforward process that is often required when parsing configurations, user inputs, or other data sources. In Java, this can be done using the Boolean.parseBoolean() method, which returns a primitive boolean value. This tutorial will demonstrate how to convert a string into a boolean using this method.

Key Points

- Boolean.parseBoolean(String s) converts a string to a primitive boolean.

- It returns true if the string argument is not null and is equal, ignoring case, to the string "true".

- Any string other than "true" (ignoring case) will result in boolean false.

2. Program Steps

1. Define a string that needs to be converted.

2. Use Boolean.parseBoolean() to convert the string to a boolean.

3. Print the output to verify the conversion.

3. Code Program

public class StringToBooleanExample {
    public static void main(String[] args) {
        // String to be converted to boolean
        String trueString = "true";
        String falseString = "false";

        // Convert strings to boolean values
        boolean trueBool = Boolean.parseBoolean(trueString);
        boolean falseBool = Boolean.parseBoolean(falseString);

        // Print the results
        System.out.println("String 'true' to boolean: " + trueBool);
        System.out.println("String 'false' to boolean: " + falseBool);
    }
}

Output:

String 'true' to boolean: true
String 'false' to boolean: false

Explanation:

1. String trueString = "true" and String falseString = "false": Declares and initializes strings meant to be converted to boolean values.

2. boolean trueBool = Boolean.parseBoolean(trueString) and boolean falseBool = Boolean.parseBoolean(falseString): Converts the strings "true" and "false" to their respective boolean values using Boolean.parseBoolean().

3. System.out.println("String 'true' to boolean: " + trueBool) and System.out.println("String 'false' to boolean: " + falseBool): Prints the boolean values to the console, demonstrating that the strings have been correctly converted to booleans.


Comments