360

How to convert String object to Boolean object?

3
  • 3
    What is the value of the String? Oct 8, 2009 at 16:09
  • 3
    What's your expectation of how a string should be converted to a boolean?
    – Steve Kuo
    Oct 8, 2009 at 16:38
  • 1
    myvartypeboolean = !!valuetoconvert
    – user2818054
    Sep 26, 2013 at 5:31

16 Answers 16

574

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 reuses the two instances of either Boolean.TRUE or Boolean.FALSE.
  • boolean: no instance is needed, you use the primitive type.

The official documentation is in 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.

5
  • 1
    wouldn't assigning Boolean.valueOf to boolaen2 be auto-unboxed anyway? I'm not seeing the difference to parseBoolean here. Oct 8, 2009 at 16:54
  • 13
    The biggest problem is that Boolean will not exception out when it sees something it shouldn't accept. It will return true for anything it sees as "true" and will return false for everything else. If you're trying to enforce matching a string to an appropriate boolean value, you'll have to add extra logic to catch illegal cases manually. Jan 17, 2011 at 17:40
  • what if i use boolean boolean2 = Boolean.valueOf("true"); Mar 6, 2013 at 10:12
  • 1
    if String object is null then Boolean.valueOf(String) will return false .But Boolean can hold null value also .can you provide any help for this.
    – amit kate
    Jul 10, 2015 at 3:59
  • Because this is the top answer, could you update it to warn people not to use these dangerous methods? (I'm not aware of any good implementation in common libraries unfortunately.)
    – ddekany
    Apr 9, 2021 at 12:07
103

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
}
3
  • 11
    This is the best example I've seen and what should have been implemented in the Boolean type to begin with. Throwing an exception for invalid Boolean value is important for many applications. Jan 17, 2011 at 17:41
  • 2
    No thats not totally true. here is the underlying implementation of parseBoolean public static boolean parseBoolean(String s) { return ((s != null) && s.equalsIgnoreCase("true")); } Feb 13, 2016 at 8:51
  • Heh... If you need to write such code, then you don't need to call Boolean.valueOf. Instead you can simple restructure this if statement so it will do what you want ;-)
    – user2266462
    Jun 8, 2019 at 13:49
23
Boolean b = Boolean.valueOf(string);

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

20

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... :-))

1
  • 1
    What about -1 and 0 ;o)
    – Minty
    Jun 28, 2022 at 16:34
11
boolean b = string.equalsIgnoreCase("true");
11

Well, as now in Jan, 2018, the best way for this is to use apache's BooleanUtils.toBoolean.

This will convert any boolean like string to boolean, e.g. Y, yes, true, N, no, false, etc.

Really handy!

6
public static boolean stringToBool(String s) {
        s = s.toLowerCase();
        Set<String> trueSet = new HashSet<String>(Arrays.asList("1", "true", "yes"));
        Set<String> falseSet = new HashSet<String>(Arrays.asList("0", "false", "no"));

        if (trueSet.contains(s))
            return true;
        if (falseSet.contains(s))
            return false;

        throw new IllegalArgumentException(s + " is not a boolean.");
    }

My way to convert string to boolean.

1
6

Use the Apache Commons library BooleanUtils class:

String[] values= new String[]{"y","Y","n","N","Yes","YES","yes","no","No","NO","true","false","True","False","TRUE","FALSE",null};
for(String booleanStr : values){
    System.out.println("Str ="+ booleanStr +": boolean =" +BooleanUtils.toBoolean(booleanStr));
}

Result:

Str =N: boolean =false
Str =Yes: boolean =true
Str =YES: boolean =true
Str =yes: boolean =true
Str =no: boolean =false
Str =No: boolean =false
Str =NO: boolean =false
Str =true: boolean =true
Str =false: boolean =false
Str =True: boolean =true
Str =False: boolean =false
Str =TRUE: boolean =true
Str =FALSE: boolean =false
Str =null: boolean =false
4
  • What is BooleanUtils? Nov 28, 2017 at 19:35
  • 2
    org.apache.commons.lang3.BooleanUtils is from Apache commons Lang API.
    – Dhana
    Nov 29, 2017 at 16:11
  • plus for the efforts gathering all use cases.
    – Gaurav
    Dec 19, 2019 at 13:48
  • Beware, BooleanUtils is still wrong (although less so than Boolean methods), as it will not throw exception if the value neither recognized as true, or false. So ture (a typo that someone does somewhere) is still blindly assumed to mean false. I can't find anything in Guava either (like there's no Booleans.stringConverter as of 23.0).
    – ddekany
    Apr 9, 2021 at 11:44
1

This is how I did it:

"1##true".contains( string )

For my case is mostly either 1 or true. I use hashes as dividers.

0

Why not use a regular expression ?

public static boolean toBoolean( String target )
{
    if( target == null ) return false;
    return target.matches( "(?i:^(1|true|yes|oui|vrai|y)$)" );
}
0

We created soyuz-to library to simplify this problem (convert X to Y). It's just a set of SO answers for similar questions. This might be strange to use the library for such a simple problem, but it really helps in a lot of similar cases.

import io.thedocs.soyuz.to;

Boolean aBoolean = to.Boolean("true");

Please check it - it's very simple and has a lot of other useful features

0
boolean status=false;
if (variable.equalsIgnoreCase("true")) {
   status=true;  
   }

This is supported only if the string is 'true' (not case-sensitive). Later you can play with the status variable.

2
  • 1
    Instead of status=Boolean.valueOf(variable) you could simply write status=true, because this line is only executed for values for which that method returns exactly that value.
    – Izruo
    May 12, 2022 at 7:25
  • Ahhh.. i missed that :D (Y) May 12, 2022 at 11:26
0

If you're aiming to just compare this string variable to a "false" or "true" string without hardcoding those two values, as was my case exactly, and you don't want to use Boolean.valueOf() since it will return true for anything it sees as "true" and will return false for everything else, as Brandon pointed out, you can do the following.

if (someStringVariable.equals(Boolean.TRUE.toString())) {
...
}

or similarly,

if (someStringVariable.equals(Boolean.FALSE.toString())) {
...
}
-1

To get the boolean value of a String, try this:

public boolean toBoolean(String s) {
    try {
        return Boolean.parseBoolean(s); // Successfully converted String to boolean
    } catch(Exception e) {
        return null; // There was some error, so return null.
    }
}

If there is an error, it will return null. Example:

toBoolean("true"); // Returns true
toBoolean("tr.u;e"); // Returns null
1
  • 8
    Have you tried this? :) parseBoolean(String s) does not throw an exception, according to the Javadoc.
    – rapt
    Jul 30, 2015 at 18:53
-3

Visit http://msdn.microsoft.com/en-us/library/system.boolean.parse.aspx

This will give you an idea of what to do.

This is what I get from the Java documentation:

Method Detail

parseBoolean

public static boolean parseBoolean(String s)

Parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

Parameters:

s - the String containing the boolean representation to be parsed

Returns: the boolean represented by the string argument

Since: 1.5

1
  • 1
    Although the question's text isn't explicit, this is a question about Java. At least it's tagged that way. This answer can confuse people. Aug 6, 2014 at 9:45
-4

you can directly set boolean value equivalent to any string by System class and access it anywhere..

System.setProperty("n","false");
System.setProperty("y","true");

System.setProperty("yes","true");     
System.setProperty("no","false");

System.out.println(Boolean.getBoolean("n"));   //false
System.out.println(Boolean.getBoolean("y"));   //true   
 System.out.println(Boolean.getBoolean("no"));  //false
System.out.println(Boolean.getBoolean("yes"));  //true
1
  • 1
    This is a very hacky proposal of converting a String into a Boolean and just makes no sense.
    – saw303
    Jul 13, 2018 at 11:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.