Shevek (shevek) wrote,
Shevek
shevek

I'm quite happy and bouncy, I just thought this was cool, so I'm making a technical post anyway.

I think that statement labels are one of the most underused features of Java. It's elegant, and a very simple solution to a problem which people often solve using boolean variables and complex additional conditions, incurring considerable runtime overhead. Most people probably know that this is valid Java:
LABEL: {
    ...
    if (cond) break LABEL;
    ...
    if (cond) break LABEL;
    ...
}

Or this:
LABEL:
while (...) {
    while (...) {
        .... break LABEL;
    }
}

But did you know that all of the following are also valid Java
boolean c0 = ...;
L0: if (c0) { } 
if (c0) L1: { } 
if (c0) { } else L2: { } 
if (c0) { } else L3: if (c0) { } 

So, having accepted that, what does the following code fragment print?
if (true) L4:
    break L4;
else 
    System.out.println("First else clause");

L5: if (true)
    break L5;
else
    System.out.println("Second else clause");

For bonus marks:
1) What is the bytecode generated by a recent Sun javac? This might surprise you, given the design policies of Java, but it makes a lot of sense.
2) Under what circumstances will javac not do that? (This, every Java programmer ought to know.)


From jcpp, a pure Java implementation of the C preprocessor, digraph handling. This is a second pass, perhaps there's an even better way to do it. The first pass was the obvious block of conditionals, but I think this reads better.
            case '%':
                d = read(); 
                if (d == '=') 
                    tok = new Token(MOD_EQ);
                else if (d == '>') 
                    tok = new Token('}');   // digraph
                else if (d == ':') PASTE: {
                    d = read(); 
                    if (d != '%') {
                        unread(d);
                        tok = new Token('#');   // digraph
                        break PASTE;
                    }    
                    d = read(); 
                    if (d != ':') {
                        unread(d);
                        unread('%');
                        tok = new Token('#');   // digraph
                        break PASTE;
                    }       
                    tok = new Token(PASTE); // double-digraph
                }
                else
                    unread(d);
                break;

Tags: java
Subscribe
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 15 comments