Java boolean to String

In Java, converting a boolean to a String is quite simple. There are a few standard ways to perform this conversion:

1. Using String.valueOf(boolean) method

The most common and recommended way to convert a boolean to a String is by using the String.valueOf() method.


boolean boolValue = true;
String str = String.valueOf(boolValue);
System.out.println(str);  // Output: "true"

boolValue = false;
str = String.valueOf(boolValue);
System.out.println(str);  // Output: "false"

Explanation: The String.valueOf(boolean) method returns a String that represents the boolean value. If the boolean is true, it returns “true”, and if the boolean is false, it returns “false”.

2. Using Boolean.toString(boolean) method

Boolean.toString(boolean) is specifically designed to convert a boolean to a String.


boolean boolValue = true;
String str = Boolean.toString(boolValue);
System.out.println(str);  // Output: "true"

boolValue = false;
str = Boolean.toString(boolValue);
System.out.println(str);  // Output: "false"

Explanation: The Boolean.toString() method is a static method from the Boolean class that returns a string representation of the boolean value (“true” or “false”).

3. Using Ternary Operator

If you need a more customized string representation, you can use a ternary operator:


boolean boolValue = true;
String str = (boolValue) ? "Yes" : "No";
System.out.println(str);  // Output: "Yes"

boolValue = false;
str = (boolValue) ? "Yes" : "No";
System.out.println(str);  // Output: "No"

Explanation: This allows you to use a custom string (like “Yes” and “No”) based on the boolean value.

4. Using String.format() for Custom Formatting

If you want to create a formatted string, you can use String.format():


boolean boolValue = true;
String str = String.format("The value is %b", boolValue);
System.out.println(str);  // Output: "The value is true"

boolValue = false;
str = String.format("The value is %b", boolValue);
System.out.println(str);  // Output: "The value is false"

Explanation: The %b format specifier is used to convert a boolean value to a string. If the boolean is true, it will display “true”, and if it’s false, it will display “false”.

5. Concatenating with an Empty String

You can also convert a boolean to a String by concatenating it with an empty string:


boolean boolValue = true;
String str = boolValue + "";  // Concatenate with empty string
System.out.println(str);  // Output: "true"

boolValue = false;
str = boolValue + "";  // Concatenate with empty string
System.out.println(str);  // Output: "false"

Explanation: This method works because Java automatically converts the boolean to its string representation when you concatenate it with an empty string.