Tuesday, February 19, 2008

After >10 years with java - I learned something new

Today I badly wished for the keyword "goto" in java to have an implementation - deeply nested if/then/else in loops and I wanted to break out of several levels at once. What I found was something I have not seen in use anywhere - the possibility to break out of a labeled block! So, if you, like me have not read chapter 14 of the Java Language Specification - here is a quick tip!
everything:
{
    // do something
    break everything;
}
breaks out of the block. This is true for loops as well! And with loops it is also possible to address which loop to continue.
outer:
for(int i = 0; i < someLimit; i++)
    for(j = 0; j < someLimit;j++)
           break outer;
breaks the outer loop
outer:
for(int i = 0; i < someLimit; i++)
    for(j = 0; j < someLimit;j++)
           continue outer;
continues the outer loop.