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.

Output

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.

Output

Pin It on Pinterest

Share This