132

I am trying to convert boolean to string type...

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

or

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

which one of above would be more efficient?

3
  • Have you looked at the source code of these two methods? Commented Sep 16, 2013 at 16:38
  • 1
    I prefer ""+b. Its slower but more efficient for the developer. If you want top performance you can write the data to/from a direct ByteBuffer, i.e. change what you do with the String so you don't need it. Commented Sep 16, 2013 at 16:47
  • Also, if you want to treat null as false, you can use String.format("%b", b) Commented Jan 12, 2020 at 3:38

7 Answers 7

174

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a great answer, just one caveat to lookout for: the String.valueOf(null) will return the String "null" and not an actual null value. This was problematic for me when working with DTOs, because I didn't want to set the value "null" as a String if the Boolean is null.
32

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";
}

Otherwise, check for null yourself before calling this.
Or, if you want to get the literal string "null" if it's null instead of checking for null yourself beforehand, 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.

Comments

3
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
--------------

1 Comment

Try to format correctly your code, and to give some explanations.
3

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();

Comments

3

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

Comments

3

If you see implementation of both the method, they look same.

String.valueOf(b)

public static String valueOf(boolean b) {
        return b ? "true" : "false";
    }

Boolean.toString(b)

public static String toString(boolean b) {
        return b ? "true" : "false";
    }

So both the methods are equally efficient.

Comments

2

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.

2 Comments

Can you please elaborate why you don't recommend using for production usage? Can it fail in some scenario?
@lazyvab In all honesty I have no idea! I don't write Java anymore but I can only presumable it was something I must have heard. I've been programming in other languages for the past few years but can't see why using this in production would hurt. Besides System.out.println is for debugging anyway, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.