Java Basic Examples

Java convert boolean to String example

This example shows how to convert boolean to String in Java. This example also shows how to convert boolean to String using several methods and the best way among them.

How to convert boolean to String in Java?

There are several ways in which primitive boolean can be converted to String in Java.

1) Convert boolean to String using String class

Use valueOf static method of String class to convert boolean to String.

valueOf method returns String representation of boolean argument.

Output

2) Convert boolean to String using Boolean wrapper class

Use toString method of Boolean wrapper class to convert from boolean to String in Java.

This method returns String representation of boolean value passed as a parameter.

Output

3) Convert boolean to String using String concatenation

String concatenation can be indirectly used to convert Java primitive values to String as given below.

Output

What is the best way to convert boolean to String?

valueOf method of String class internally calls the toString method of Boolean wrapper class to convert from boolean to String value. Using either of the methods is equally efficient in terms of the performance. Preferred way is to use toString method of Boolean wrapper class.

String concatenation should be avoided mainly for the conversion purpose because,

a) It is difficult to visually understand that the purpose of the code is conversion.

b) String concatenation operation creates unnecessary temporary objects during the conversion process. String concatenation is achieved using StringBuffer’s or StringBuilder’s append method. So the code,

Will be executed like,

Please let us know your views in the comments section below.

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

Tags