Boolean to String in Java

  1. Convert Primitive boolean to String Using String.valueOf(boolean) in Java
  2. Convert a Boolean Object to a String Using toString() in Java
  3. Concatenate Primitive boolean or Boolean Object to a String in Java

This article will introduce multiple methods to convert a primitive boolean or a Boolean object to a string in Java. We will use a few examples that explain the topic very clearly.

Convert Primitive boolean to String Using String.valueOf(boolean) in Java

The first method, valueOf(), is a method of the String class. This function takes multiple data types as an argument, and boolean is one of them.

In the example, there is a primitive boolean value that we can convert to a string by passing it to String.valueOf(value).

public class BooleanToString {
    public static void main(String[] args) {
        boolean a = true;

        String b = String.valueOf(a);
        System.out.println(b);

    }
}

Output:

true

Convert a Boolean Object to a String Using toString() in Java

The next example shows how we can convert a Boolean object to a string. Here, we can use the toString() method to convert the Boolean value to a string directly.

public class BooleanToString {
    public static void main(String[] args) {
        Boolean a = false;

        String b = a.toString();
        System.out.println(b);

    }
}

Output:

false

Another way of using toString() is to directly call it from the Boolean class. Then we can pass the string to the toString() as an argument.

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

        Boolean a = false;

        String b = Boolean.toString(a);
        System.out.println(b);
        
    }
}

Output:

false

Concatenate Primitive boolean or Boolean Object to a String in Java

The last method includes concatenating the boolean and Boolean values to a string. It is a simple trick which joins the string and boolean values to return a new string. As shown in the example below, we have concatenated a and b with two strings, c and d, which resulted in a new string displayed in the output.

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

        boolean a = true;
        Boolean b = false;

        String c = "Primitive: " + a;
        String d = "Object: " + b;
        System.out.println(c);
        System.out.println(d);
    }
}

Output:

Primitive: true
Object: false

Related Article - Java Boolean

  • String to Boolean in Java
  • Related Article - Java String

  • Convert an Arraylist to a String in Java
  • Capitalize the First Letter of a String in Java