There are two methods by which we can convert a boolean to String:
1) Method 1: Using String.valueOf(boolean b): This method accepts the boolean argument and converts it into an equivalent String value.
Method declaration:
public static String valueOf(boolean b)
parameters:
b – represent the boolean variable which we want to convert
returns:
String representation of b
boolean boovar = true; String str = String.valueOf(boovar);
2) Method 2: Using Boolean.toString(boolean b): This method works same as String.valueOf() method. It belongs to the Boolean class and converts the specified boolean to String. If the passes boolean value is true then the returned string would be having “true” value, similarly for false the returned string would be having “false” value.
Method declaration:
public static String toString(boolean b)
parameters:
b – represent the boolean variable that needs to be converted
returns:
The string representing the passed boolean value.
boolean boovar = false; String str = Boolean.toString(boovar);
Example: Converting boolean to String
This program demonstrates the use of both the above mentioned methods. Here we have two boolean variables and we are converting one of them using String.valueOf() method and other one using Boolean.toString() method.
package com.beginnersbook.string; public class BooleanToString { public static void main(String[] args) { /* Method 1: using valueOf() method * of String class. */ boolean boovar = true; String str = String.valueOf(boovar); System.out.println("String is: "+str); /* Method 2: using toString() method * of Boolean class */ boolean boovar2 = false; String str2 = Boolean.toString(boovar2); System.out.println("String2 is: "+str2); } }
Output:
String is: true String2 is: false
Leave a Reply