Java Program to Convert Boolean Variable to String

In this java program, we will learn how to convert a boolean variable to string. We can convert boolean to String in java using String.valueOf(boolean) method or by using Boolean.toString(boolean) method.

To understand this java program, you should have understanding of the following Java programming concepts:


Convert boolean to string using valueOf() method

The String.valueOf() method converts boolean value to String. The valueOf() is the static method of String class. The syntax of String.valueOf() method is as follows:

public static String valueOf(boolean b)
Pass the boolean value as argument to String.valueOf() function, and the function returns a String object.

public class BooleanToString {
  public static void main(String[] args) {
    // Initialize boolean variables
    boolean trueVal = true;
    boolean falseVal = false;

    String trueStr = String.valueOf(trueVal);
    String falseStr = String.valueOf(falseVal);

    System.out.println(trueStr);
    System.out.println(falseStr);
  }
}
Output
true
false

Convert boolean to String using toString() method

A static method in the Boolean class called toString() returns a string object that represents the given boolean value. The toString() function requires the boolean value as an input. The syntax of Boolean.toString() method is as follows:

public static String toString(boolean b)

public class BooleanToString2 {
  public static void main(String[] args) {
    // Initialize boolean variables
    boolean trueVal = true;
    boolean falseVal = false;

    String trueStr = Boolean.toString(trueVal);
    String falseStr = Boolean.toString(falseVal);

    System.out.println(trueStr);
    System.out.println(falseStr);
  }
}
Output
true
false

In the above program, the toString() method of Boolean class converts the boolean variables into a string.


Convert Boolean to String using String Concatenation

We can convert a boolean value to string by concatenating an empty string("") to it. This is the most easiest way to convert an boolean value to a string.

public class BooleanToString3 {
  public static void main(String[] args) {
    // Initialize boolean variables
    boolean trueVal = true;
    boolean falseVal = false;

    String trueStr = trueVal + "";
    String falseStr = falseVal + "";

    System.out.println(trueStr);
    System.out.println(falseStr);
  }
}
Output
true
false