[java] How to convert String object to Boolean Object?

How to convert String object to Boolean object?

This question is related to java string boolean

The answer is


Boolean b = Boolean.valueOf(string);

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


This is how I did it:

"1##true".contains( string )

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


boolean b = string.equalsIgnoreCase("true");

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
}

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

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


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.


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


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


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

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

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

Use .isBool in your String value. It work for me

your_string.isBool

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!


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to boolean

Convert string to boolean in C# In c, in bool, true == 1 and false == 0? Syntax for an If statement using a boolean Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() Ruby: How to convert a string to boolean Casting int to bool in C/C++ Radio Buttons ng-checked with ng-model How to compare Boolean? Convert True/False value read from file to boolean Logical operators for boolean indexing in Pandas