Search code examples
javasyntaxnotation

Java what is the double underscore notation for?


I was browsing the web and found this example. Within the public static void main method is this line syntax which I have never seen before __main:

As in:

public class Klass {
    public static void main(String[] args) {
        // code goes here...
__main:
        // and mode code here...
    }
}

I tried punching this into eclipse and got a little yellow underline with a tool-tip which said "The label __main is never explicitly referenced".

I can't find anything online and I'm really curious! I've been programming in Java for years and I've never seen this syntax before. What does it do, why would you use it, where can I learn more?


Solution

  • A goto statement in C and its counterparts are accompanied by a Label argument. In a defined method, a goto label; statement will fire the routine proceeding the label. Below is an example demonstrated by Greg Rogers in this Post.

    void foo()
    {
        if (!doA())
            goto exit;
        if (!doB())
            goto cleanupA;
        if (!doC())
            goto cleanupB;
    
        // everything succeed
        return;
    
    cleanupB:
        undoB();
    cleanupA:
        undoA();
    exit:
        return;
    }
    

    A goto can be a very effective tool in Java, but Java does not explicitly support the goto keyword even though the keyword has been reserved by the language. Using a break statement will enable the command jump out of the label to proceed to the statement after the label.

    Example:

    public class Klass {
      public static void main(String[] args) {
      // code goes here...
      __main:
            {
             if(args.length==0)
             {
              break __main;
             }
            }
      //code after label
        }
    }
    

    The package com.sun.org.apache.bcel.internal.generic.GOTO, I have not used it personally but I think it can aid to achieve the same code structure as demonstrated by Greg Rogers like this:

     void foo()
      {
          if (!doA())
              GOTO exit;
          if (!doB())
              GOTO cleanupA;
          if (!doC())
              GOTO cleanupB;
    
          // everything succeed
          return;
    
      cleanupB:
          undoB();
      cleanupA:
          undoA();
      exit:
          return;
      }
    
      void undoB(){}
      void undoA(){}
      boolean doC(){return false;}
      boolean doA(){return false;}
      boolean doB(){return false;}