We can convert boolean to String in Java using the following methods:
- String.valueOf() method
- Boolean.toString() method
Convert boolean to String in Java using the String.valueOf() method
There are multiple overloaded versions of the valueOf() method from the String class. We will use the one which accepts boolean.
Example
class Test { public static void main(String[] args) { String str = String.valueOf(true); String str2 = String.valueOf(false); System.out.println(str); System.out.println(str2); } }
Output: true false
Parse boolean to String using the Boolean.toString() method
The toString(boolean b) is the static method of the Boolean class that returns a String object representing the specified boolean.
Example
class Test { public static void main(String[] args) { String str = Boolean.toString(true); String str2 = Boolean.toString(false); System.out.println(str); System.out.println(str2); } }
Output: true false
That’s all about how to convert boolean to String in Java!
It’s also important to know how to convert a Java string to a boolean. For more information on this topic, check out our related tutorial Convert Java String to boolean. By understanding both conversions, you’ll be able to work effectively with Java strings and boolean values in your programs.
Happy coding!