tags:

views:

345

answers:

5

hi how to convert String object to Boolean Object

+6  A: 

Try (depending on what result type you want):

    Boolean boolean1 = Boolean.valueOf("true");
    boolean boolean2 = Boolean.parseBoolean("true");

Advantage :

  • Boolean : this does not create new instances of Boolean, so performance is better (and less garbage-collection). It reuse the two instances Boolean.TRUE or Boolean.FALSE.
  • boolean : not instance is needed, you use the primitive type.

The official documentation is the Javadoc.


UPDATED :

Autoboxing could also be used, but it has a performance cost.
I suggest to use it only when you would have to cast yourself, not when the cast is avoidable.

KLE
You might want to use different variable names... :-)
Laurence Gonsalves
@Laurence Updated to comply with your opinion. :-)
KLE
wouldn't assigning Boolean.valueOf to boolaen2 be auto-unboxed anyway? I'm not seeing the difference to parseBoolean here.
Alex Feinman
+3  A: 

Boolean b = Boolean.valueOf(string);

The value of b is true if string is not null and equal to "true" (ignoring case).

CJS
+1  A: 

You have to be carefull when using Boolean.valueOf(string) or Boolean.parseBoolean(string). The reason for this is that the methods will always return false if the String is not equal to "true" (the case is ignored).

For example:

Boolean.valueOf("YES") -> false

Because of that behaviour I would recommend to add some mechanism to ensure that the string which should be translated to a Boolean follows a specified format.

For instance:

if (string.equalsIgnoreCase("true") || string.equalsIgnoreCase("false")) {
    Boolean.valueOf(string)
    // do something   
} else {
    // throw some exception
}
zlajo
+1  A: 

Beside the excellent answer of KLE, we can also make something more flexible:

boolean b = string.equalsIgnoreCase("true") || string.equalsIgnoreCase("t") || 
        string.equalsIgnoreCase("yes") || string.equalsIgnoreCase("y") || 
        string.equalsIgnoreCase("sure") || string.equalsIgnoreCase("aye") || 
        string.equalsIgnoreCase("oui") || string.equalsIgnoreCase("vrai");

(inspired by zlajo's answer... :-))

PhiLho
+1  A: 
boolean b = string.equalsIgnoreCase("true");
Zed