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