Wednesday, June 10, 2009

Puzzle 31 – Solution

You folks came up with a myriad of solutions for this puzzle – here is the one I had in mind.

Try-catch and finally has a peculiar behavior when it comes to returning values. In case a return statement exists in the finally block – the value in the finally block is returned even if the return in the try/catch has executed smoothly.
Finally code is always executed – even if there is a return statement in the try!!

For those who did look hard there was a hint in the last line of the puzzle – "Finally if you still haven’t figured this out – my suggestion is try again!!" It was no coincidence that two java keywords Finally and Try were present in a single sentence!

Here is the code snippet that does the trick.

package com.twisters
class TheTest{
public boolean win(){
return false; //Get this code to always return true.
return true;

There were loads of other solutions that were correct – some where real gems. (Unfortunately, I still haven’t gone through all the solutions/comments!!!)

1. Use a switch statement – Oh yes I forgot to ban that one. Righhhhht.
2. return false == false?true:false – which one is the original false please?
3. Rename false to false1 and declare flase1 as a boolean variable.

There are lots more - have a look at the comments if you want to see them all.
Leaders board to be updated next week.

@Abhi – I did goof up a bit with the scores. They now stand corrected. Thanks for pointing out!

No comments:

Post a Comment

Solution for this question?