I was struggling to find a bug in a very simple application, it ended up being something as simple as using the damned Boolean.getBoolean("true") call instead of Boolean.valueOf("true").booleanValue() call.
The Boolean.getBoolean method is something you almost never need to use, as it checks if a particular system property is true or false. There is a similar method for Integer.getInteger, and a quick google search shows I am not the only one to think those method should never have been part of the basic API for Boolean/Integer. It is too easy to confuse with parseBoolean/parseInt, especially as parseBoolean does not exist in JDKs prior to JDK 1.5 (parseInt is older).
I can not imagine the improductivity this method has produced given its part of one of the most used class in the world.
Thanks for the post. I just mindlessly wandered into the same trap as you.
ReplyDeletehello Fabien.
ReplyDeleteuse
Boolean.parseBoolean("true")
instead of
Boolean.valueOf("true").booleanValue()
Boolean.parseBoolean() will return primative type boolean not Boolean helper class. :-)
Thanks. I am also facing the same problem. It helped me a lot.
ReplyDeleteYeah - same thing just happened to me. You'd think I'd know better by now.
ReplyDeleteIncidentally - in recent versions of Java (I think since 1.5) you can use primitive types and wrapper types interchangeably, so these are all equivalent:
Boolean.parseBoolean("true")
Boolean.valueOf("true")
Boolean.valueOf("true").booleanValue()
new Boolean("true")
Thanks! I was wondering why passing a string equal to "true" was being evaluated to false. The naming was confusing as you have said.
ReplyDeletehttp://cjcdeleon.blogspot.com/
Wow, it's 2011, and I fell for that trap 2. Thanks
ReplyDeleteAndrew McCrea just fell for it muhahaha
ReplyDeleteboolean andrewmccreaeverlearn = false
ReplyDeleteit's 2012, and I fell for that trap 2. Thanks :)
ReplyDeleteYey! it's 2013, and I fell for that trap 2. Thanks :)
ReplyDelete