This example shows how to convert boolean to string in Java using valueOf, toString, and + operator. It also shows the best way to convert boolean to string in Java.
How to convert boolean to String in Java?
There are several ways in which a primitive boolean can be converted to a string in Java.
1) Convert boolean to string using the string class
Use the valueOf
static method of the String class to convert.
1 |
static String valueOf(boolean b) |
The valueOf
method returns a string representation of the boolean argument.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.javacodeexamples.basic; public class BooleanToStringExample { public static void main(String[] args) { boolean b = true; String str = String.valueOf(b); System.out.println("String value: " + str); } } |
Output
1 |
String value: true |
2) Using the Boolean wrapper class
Use the toString
method of the Boolean wrapper class to convert.
1 |
public static String toString(boolean b) |
This method returns a string representation of the boolean value passed as a parameter.
1 2 3 4 |
boolean b = true; String str = Boolean.toString(b); System.out.println("String value: " + str); |
Output
1 |
String value: true |
3) Using string concatenation
String concatenation can be indirectly used to convert any Java primitive value to a string as given below.
1 2 3 4 |
boolean b = true; String str = "" + b; System.out.println("String value: " + str); |
Output
1 |
String value: true |
What is the best way to convert?
The valueOf
method of the String class internally calls the toString
method of the Boolean wrapper class to convert from boolean to a string value. Using either of the methods is equally efficient in terms of performance. The preferred way is to use the toString
method of the 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 the append method of the StringBuffer or StringBuilder class. So the code,
1 |
String str = "" + b; |
Will be executed like,
1 2 3 4 5 6 |
StringBuilder sb = new StringBuilder(); sb.append(""); sb.append(b); String str = sb.toString(); |
This example is a part of the Java Basic Examples and Java Type conversion Tutorial.
Please let me know your views in the comments section below.