Write a Java Program to convert boolean variables into string

In Java, boolean variables can hold only two possible values, which are true or false.

There are times when you might need to convert a boolean variable to a string, for instance, when you are working with user interfaces or when you need to display the value of a boolean variable in a message box.

In this tutorial, we will explore how to convert boolean variables into strings in Java.


One of the simplest ways to convert a boolean variable into a string is to use the toString() method.

This method is available for all Boolean objects and converts a boolean value to its string representation.

Here is an example:

boolean b = true;
String str = Boolean.toString(b);

In the example above, the boolean value ‘b’ is converted into a string using the Boolean.toString() method.

The resulting string ‘str’ will contain the value “true”.

If you have a primitive boolean variable, you can use the String.valueOf() method to convert it into a string.

Here is an example:

boolean b = true;
String str = String.valueOf(b);

In the example above, the boolean value ‘b’ is converted into a string using the String.valueOf() method.

The resulting string ‘str’ will contain the value “true”.

You can also use the ternary operator to convert a boolean variable into a string.

Here is an example:

boolean b = true;
String str = b ? "true" : "false";

In the example above, the ternary operator is used to check the value of the boolean variable ‘b’. If ‘b’ is true, the string “true” is assigned to the variable ‘str’. Otherwise, the string “false” is assigned to the variable ‘str’.


In conclusion, there are different ways to convert boolean variables into strings in Java, including using the Boolean.toString() method, the String.valueOf() method, or the ternary operator.

Choose the one that suits your needs and use it in your Java programs.

Editorial Team
Editorial Team

Programming Cube website is a resource for you to find the best tutorials and articles on programming and coding.