Convert Boolean to String in Java

In Java, converting a boolean value to its equivalent String representation can be done using the Boolean.toString() method or by concatenating with an empty string. Let's explore both methods with examples. 

1. Using Boolean.toString() Method 

The Boolean.toString(boolean b) method is a simple and direct way to convert a boolean value to its String representation. 

Example:

public class BooleanToStringExample {
    public static void main(String[] args) {
        boolean boolValue = true;
        String stringValue = Boolean.toString(boolValue);

        System.out.println("Boolean Value: " + boolValue);
        System.out.println("String Value: " + stringValue);
    }
}

Output:

Boolean Value: true
String Value: true

2. Concatenation with an Empty String 

As with other primitive types, you can also convert a boolean to a String by concatenating it with an empty string. 

Example:

public class BooleanToStringExample {
    public static void main(String[] args) {
        boolean boolValue = false;
        String stringValue = "" + boolValue;

        System.out.println("Boolean Value: " + boolValue);
        System.out.println("String Value: " + stringValue);
    }
}

Output:

Boolean Value: false
String Value: false

Conclusion 

Converting a boolean to a String in Java is a straightforward task, and you have multiple methods available to do it. Whether you use Boolean.toString() or concatenation with an empty string, you will obtain a String representation of the original boolean value.

Related String Conversion Examples

Comments