Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String object to Boolean

When i tried to convert a String Object to boolean, the result is different.

String strFlag="true";
boolean boolFlag = Boolean.getBoolean(strFlag);

boolFlag ends up having a false value.

like image 245
Mdhar9e Avatar asked Apr 25 '12 10:04

Mdhar9e


People also ask

How can we convert string to boolean?

To convert String to boolean in Java, you can use Boolean. parseBoolean(string). But if you want to convert String to Boolean object then use the method Boolean. valueOf(string) method.

How do you convert string false to boolean false?

The simplest way to do so is to use the strict equality operator to compare our string value to the "true" - if the string is (strictly) equal to "true" , the output will be boolean true . Alternatively, you can use the ternary operator alongside the loose equality operator to achieve the same.

Can you use strings in boolean?

We can convert String to boolean in java using Boolean. parseBoolean(string) method. To convert String into Boolean object, we can use Boolean. valueOf(string) method which returns instance of Boolean class.

How do I cast a string to a boolean in TypeScript?

To convert a string to a boolean in TypeScript, use the strict equality operator to compare the string to the string "true" , e.g. const bool = str === 'true' . If the condition is met, the strict equality operator will return the boolean value true , otherwise false is returned.


2 Answers

Use Boolean.valueOf

boolean boolFlag = Boolean.valueOf(strFlag);

This method returns a Boolean with a value represented by the specified String. The Boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

like image 127
Sergey Kalinichenko Avatar answered Oct 05 '22 08:10

Sergey Kalinichenko


Use Boolean.valueOf(String string) to archieve your goal.

boolean boolFlag = Boolean.valueOf(strFlag);

Returns a Boolean with a value represented by the specified String. The Boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

Example: Boolean.valueOf("True") returns true.

Example: Boolean.valueOf("yes") returns false.

As of java 1.5 there's also Boolean.parseBoolean(String s) which returns the primitive type boolean instead of the boxed type Boolean to spare some CPU cycles in most cases.

like image 20
devsnd Avatar answered Oct 05 '22 07:10

devsnd