O'Really?

July 23, 2009

Josh the Java Junkie

Joshua Bloch at scifooOne of the people I enjoyed seeing at Science Foo Camp this year was Joshua Bloch. Josh is a Java Junkie [1,2,3] and software engineer at Google. When he wasn’t playing harmonica around the foo camp fire (see picture right), he was giving interesting talks about optical illusions, some of which can be found in his book Java Puzzlers. So I bought the book, and have been doing a puzzle a day to keep the doctor away. Most of the puzzles in this book are short Java programs that behave in ways you would not expect. The one below is a nice example:

public class Indecisive {
    public static void main(String[] args) {
        System.out.println(decision());
    }

    static boolean decision() {
        try {
            return true;
        } finally {
            return false;
        }
    }
}

What does this program do? Return true or false? Perhaps it does both or something else completely? Does it even compile? Can’t decide? Welcome to public class Indecisive…

References

  1. Joshua Bloch and Neal Gafter (2005). Java Puzzlers: Traps, Pitfalls, and Corner Cases (isbn:032133678X) Addison-Wesley
  2. Joshua Bloch (2006). How to design a good API and why it matters OOPSLA ’06: Companion to the 21st ACM SIGPLAN symposium on Object-oriented programming systems, languages, and applications, 506-507 DOI: 10.1145/1176617.1176622
  3. Neal Gafter (2008). Is the Java Language Dying? Neal Gafter’s blog: Thoughts about the future of the Java Programming Language.

3 Comments »

  1. false

    Finally block always gets called, regardless. Always wondered what happened to a return value called earlier.
    Gets dumped it appears.

    Comment by Phil Lord — July 23, 2009 @ 12:43 pm | Reply

    • Hi Phil, I bet you had to run it through a compiler first, just to check?

      Comment by Duncan — July 24, 2009 @ 12:55 pm | Reply

  2. Next question. If you commented out the ‘return true;’ line, would it still compile, given that *whatever* happens in the try block, false will always be returned?

    Phil, over to you. And no cheating.

    Comment by Neil Swainston — July 30, 2009 @ 5:22 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: