Friday, October 12, 2007

I fell in the trap of Boolean.getBoolean()

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.

10 comments :

  1. Thanks for the post. I just mindlessly wandered into the same trap as you.

    ReplyDelete
  2. hello Fabien.

    use
    Boolean.parseBoolean("true")

    instead of
    Boolean.valueOf("true").booleanValue()

    Boolean.parseBoolean() will return primative type boolean not Boolean helper class. :-)

    ReplyDelete
  3. Thanks. I am also facing the same problem. It helped me a lot.

    ReplyDelete
  4. Yeah - same thing just happened to me. You'd think I'd know better by now.

    Incidentally - 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")

    ReplyDelete
  5. Thanks! I was wondering why passing a string equal to "true" was being evaluated to false. The naming was confusing as you have said.

    http://cjcdeleon.blogspot.com/

    ReplyDelete
  6. Wow, it's 2011, and I fell for that trap 2. Thanks

    ReplyDelete
  7. Andrew McCrea just fell for it muhahaha

    ReplyDelete
  8. boolean andrewmccreaeverlearn = false

    ReplyDelete
  9. it's 2012, and I fell for that trap 2. Thanks :)

    ReplyDelete
  10. Yey! it's 2013, and I fell for that trap 2. Thanks :)

    ReplyDelete