I am trying to convert boolean to string type...
Boolean b = true;
String str = String.valueOf(b);
or
Boolean b = true;
Str
If you are sure that your value is not null you can use third option which is
String str3 = b.toString();
and its code looks like
public String toString() {
return value ? "true" : "false";
}
If you want to be null-safe use String.valueOf(b) which code looks like
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
so as you see it will first test for null and later invoke toString() method on your object.
Calling Boolean.toString(b) will invoke
public static String toString(boolean b) {
return b ? "true" : "false";
}
which is little slower than b.toString() since JVM needs to first unbox Boolean to boolean which will be passed as argument to Boolean.toString(...), while b.toString() reuses private boolean value field in Boolean object which holds its state.
If you're looking for a quick way to do this, for example debugging, you can simply concatenate an empty string on to the boolean:
System.out.println(b+"");
However, I strongly recommend using another method for production usage. This is a simple quick solution which is useful for debugging.
Depends on what you mean by "efficient". Performance-wise both versions are the same as its the same bytecode.
$ ./javap.exe -c java.lang.String | grep -A 10 "valueOf(boolean)"
public static java.lang.String valueOf(boolean);
Code:
0: iload_0
1: ifeq 9
4: ldc #14 // String true
6: goto 11
9: ldc #10 // String false
11: areturn
$ ./javap.exe -c java.lang.Boolean | grep -A 10 "toString(boolean)"
public static java.lang.String toString(boolean);
Code:
0: iload_0
1: ifeq 9
4: ldc #3 // String true
6: goto 11
9: ldc #2 // String false
11: areturn
If this is for the purpose of getting a constant "true" value, rather than "True" or "TRUE", you can use this:
Boolean.TRUE.toString();
Boolean.FALSE.toString();
I don't think there would be any significant performance difference between them, but I would prefer the 1st way.
If you have a Boolean reference, Boolean.toString(boolean) will throw NullPointerException if your reference is null. As the reference is unboxed to boolean before being passed to the method.
While, String.valueOf() method as the source code shows, does the explicit null check:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Just test this code:
Boolean b = null;
System.out.println(String.valueOf(b)); // Prints null
System.out.println(Boolean.toString(b)); // Throws NPE
For primitive boolean, there is no difference.
public class Sandbox {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Boolean b = true;
boolean z = false;
echo (b);
echo (z);
echo ("Value of b= " + b +"\nValue of z= " + z);
}
public static void echo(Object obj){
System.out.println(obj);
}
}
Result -------------- true false Value of b= true Value of z= false --------------