Exercise:
Write a Java Program to convert boolean variables into string.
1.Convert Using Valueof()
Click Here to View the Solution!
public class BoolToString {
public static void main(String[] args) {
boolean boolean1 = true;
boolean boolean2 = false;
String string1 = String.valueOf(boolean1);
String string2 = String.valueOf(boolean2);
System.out.println(string1);
System.out.println(string2);
}
}
Click Here to View the Output!
true false
Click Here to View the Explanation!
- This program deals with turning the values of Boolean variables into string equivalent.
- In the first step, two variables of
boolean
type, by the name ofboolean1
andboolean2
have been initialized with values ‘true’ and ‘false’ respectively. - For the conversion purpose
valueOf()
method ofString
class, is employed. - First the variables are passed to the method, and then the resultant converted values are assigned to
String
type variablesstring1 string2
respectively. - After that the values are displayed on the console.
2.Convert Using toString()
Click Here to View the Solution!
public class BoolToString {
public static void main(String[] args) {
boolean boolean1 =
true;
boolean boolean2 =
false;
String string1 = Boolean.toString(boolean1);
String string2 = Boolean.toString(boolean2);
System.out.println(string1);
System.out.println(string2);
}
}
Click Here to View the Output!
true false
Click Here to View the Explanation!
- In this program method
toString()
is employed for the purpose of Boolean to string conversion. - Two boolean type variables
boolean1
andboolean2
are initialized first. - Then the
Boolean
class methodtoString()
is called, hereboolean1
andboolean2
are passed as arguments one by one. - The converted values are stored in String type variables
string1
andstring2
respectively. - Finally the values are printed.