Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java-me: Convert String to boolean

I'm developing for BlackBerry and I got stuck with this stupid problem:

I need to convert string values "1" and "0" to true and false, respectively. Nevertheless, Blackberry JDK is based in Java 1.3, so I can't use Boolean.parseBoolean, Boolean.valueOf or Boolean.getValue.

Obviously I can do something like:

if (str.equals("1")) return true;
else if (str.equals("0")) return false;

But this looks very ugly and maybe these string values could change to "true" and "false" later. So, Is there another way to convert between these types (String -> boolean, Java 1.3)?

UPDATED: all the answers of this question was very helpfully but I needed to mark one, so I selected Ishtar's answer.

Even so, my fix was a combination of multiple answers.

like image 475
Jose S Avatar asked Mar 25 '11 05:03

Jose S


People also ask

Can you convert String to boolean in Java?

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 I convert String to boolean?

To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() 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".

Can we use .equals to boolean?

The equals() method of Boolean class is a built in method of Java which is used check equality of two Boolean object. Parameter: It take a parameter ob of type Object as input which is the instance to be compared. Return Type: The return type is boolean.

What can be converted to 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.


1 Answers

public static boolean stringToBool(String s) {
  if (s.equals("1"))
    return true;
  if (s.equals("0"))
    return false;
  throw new IllegalArgumentException(s+" is not a bool. Only 1 and 0 are.");
}

If you later change it to "true/false", you won't accidentally order 28,000 tons of coal. Calling with the wrong parameter will throw an exception, instead of guessing and returning false. In my opinion "pancake" is not false.

like image 93
Ishtar Avatar answered Oct 09 '22 16:10

Ishtar