How to convert Boolean to String in Java

In Java, Boolean is a wrapper class that provides an object representation of the primitive type boolean.

The boolean primitive type can hold only one of two possible values, true or false. On the other hand, Boolean is a class that provides a way to represent a boolean value as an object. It also provides various methods to work with boolean values.

Here's an example of how to create a Boolean object in Java:

Boolean b1 = true; // using autoboxing Boolean b2 = new Boolean(false); // using constructor

In Java, there are several ways to convert a boolean value to a string. Here are some examples:

Using the Boolean.toString() method:

boolean b = true; String s1 = Boolean.toString(b); // "true" String s2 = Boolean.toString(!b); // "false"

Table of Content :

Using the String.valueOf() method:

boolean b = true; String s1 = String.valueOf(b); // "true" String s2 = String.valueOf(!b); // "false"

Using a ternary operator:

boolean b = true; String s1 = b ? "true" : "false"; // "true" String s2 = !b ? "true" : "false"; // "false"

Using an if-else statement:

boolean b = true; String s; if (b) { s = "true"; } else { s = "false"; }

All of these methods will convert a boolean value to a string representation. Which one you choose to use depends on your personal preference and the context in which you are working.

In this article, we've have seen various ways to convert boolean values to strings in Java. We've discussed the primitive boolean and object Boolean cases: