Monday, October 12, 2009

Puzzle 54 – Solution

The principle that I wanted to bring out in this puzzle was that we can break out of any labeled block by using a break statement.

package com.twister;
public class NoIf {

public static void main(String[] args) {
if(true){}
System.out.println(
"Print This");
noPrint:{
if(true){break noPrint;}
System.out.println(
"Print This - Not!");
}
if(true){}
System.out.println(
"Print This");
}
}

The other popular solution was to wrap the code in a try-catch-finally block. As the catch block will not execute without any exception – the second print statement is skipped.

My favorite solution for this puzzle is the one by vector9x,
System.out.println("Print This - Not!".substring(0,10));

Scores to be updated next week!!

No comments:

Post a Comment

Solution for this question?