How to Convert boolean to String in Java
There are two methods to convert boolean to String.
- Using valueOf(boolean) method
- Using toString(boolean) method
For both the above methods, if the passes Boolean value is true, then returned string will be “true,” similarly for false, the return value will be “false.”
In the above methods, Boolean value true is not the same as True or TRUE.
Using String.valueOf(boolean) method
The valueOf(boolean) is a static method of the String class. It accepts Boolean value as an argument and returns the string representation of Boolean value. The signature of the method is given below.
public static String valueOf(boolean b)
Where b represent the Boolean variable which we want to convert.
Example
In the following example, there are two variables str1 and str2 of type String that stores the converted value. The String is a class. The valueOf() method parses the boolean value true and false respectively and returns the string representation of boolean value. The first println statement prints the string value of the variable str1 and the second println statement prints the string value of the variable str2.
1 2 3 4 5 6 7 8 9 10 11 12 |
public class booleanToStringExample { public static void main(String args[]) { String str1=String.valueOf(true); String str2=String.valueOf(false); System.out.println("The string value of str1 is: "+str1); System.out.println("The string value of str2 is: "+str2); } } |
Output
1 2 3 4 |
The string value of str1 is: true The string value of str2 is: false |
Using Boolean.toString(boolean) method
The toString(boolean) is a static method of the Boolean class. It converts the specified Boolean value to String. It returns the string representation of Boolean value. The signature of the method is given below.
public static toString (boolean b)
Where b represent the Boolean variable which we want to convert.
Example
In the following example, there are two variables str1 and str2 of type String that stores the converted value. The String is a class. The valueOf() method parses the boolean value false and true respectively and returns the string representation of boolean value. The first println statement prints the string value of the variable str1 and the second println statement prints the string value of the variable str2.
1 2 3 4 5 6 7 8 9 10 11 12 |
public class booleanToStringExample1 { public static void main(String args[]) { String str1=Boolean.toString(false); String str2=Boolean.toString(true); System.out.println("The string value of str1 is: "+str1); System.out.println("The string value of str2 is: "+str2); } } |
Output
1 2 3 4 |
The string value of str1 is: false The string value of str2 is: true |