java puzzlers at the java sig

I got to see Josh Bloch and Bob Lee perform 9 Java Puzzlers.  That’s right.  I said perform.  They were funny, dynamic and had great banter.  It felt so natural.  And it was educational on top of all that.

I’m not going to try to transcribe the puzzlers.  You can read the book for many like this.  What I am going to do is mention my favorite 3 things I learned.

1) Double.MIN_VALUE isn’t what you think

Integer.MIN_VALUE is the smallest possible Integer.  So clearly Double.MIN_VALUE is the smallest possible Double.  Nope!  Double.MIN_VALUE is the smallest positive number that can be represented as a double.  4.9E-324.  Double.NEGATIVE_INFINITY is the smallest possible Double.

2) Compile time “constants” can change

System.out.println(Const.A + ” ” + Const.B);

If you compile and run this println against

interface Const {

String A = “a”;

String B = null;

}

it prints “a null”.

Then if you change it to run against

interface Const {

String A = “A”;

String B = “B”;

}

it prints “a B”.  That’s right.  The “a” is remembered because compile time constants are compiled in.  Whereas null isn’t a compile time constant so the new value is used.  Same for enums – not a compile time constant.

3) Autoboxing is a minefield

Ok.  So this one I knew already.  But it’s really important.  When comparing Integer objects, == is used.  Not autoboxing.  And JDKs are free to have the cutoff for where Integer objects are cached for autoboxing in different places.  So it is important not to rely on this.