Java Program to convert boolean variables into string

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Convert boolean to string using valueOf()

class Main {
  public static void main(String[] args) {

    // create boolean variables
    boolean booleanValue1 = true;
    boolean booleanValue2 = false;

    // convert boolean to string
    // using valueOf()
    String stringValue1 = String.valueOf(booleanValue1);
    String stringValue2 = String.valueOf(booleanValue2);

    System.out.println(stringValue1);    // true
    System.out.println(stringValue2);    // true
  }
}

In the above example, we have used the valueOf() method of String class to convert the boolean variables into strings.


Example 2: Convert boolean to String using toString()

We can also convert the boolean variables into strings using the toString() method of the Boolean class. For example,

class Main {
  public static void main(String[] args) {

    // create boolean variables
    boolean booleanValue1 = true;
    boolean booleanValue2 = false;

    // convert boolean to string
    // using toString()
    String stringValue1 = Boolean.toString(booleanValue1);
    String stringValue2 = Boolean.toString(booleanValue2);

    System.out.println(stringValue1);    // true
    System.out.println(stringValue2);    // true
  }
}

In the above example, the toString() method of Boolean class converts the boolean variables into strings. Here, Boolean is a wrapper class. To learn more, visit the Java Wrapper Class.

Did you find this article helpful?