Search code examples
javalabeled-statements

How to use labels in java?


I am getting error while using break statements in labels in java code. This is showing undefined label. It is wrong to write code like this. Please assist me in using it correctly. Thanks in advance.

 while (true) {
     label149: if (!localIterator2.hasNext());
     while (true) {
         i++;
         break;
         HashMap localHashMap2 = (HashMap)localIterator2.next();
         if (!((String)localHashMap1.get("name")).equalsIgnoreCase((String)localHashMap2.get("emotion")))
             break label149;
         if (!((String)localHashMap2.get("IS_paid")).equalsIgnoreCase("1"))
             break label246;
         ((HashMap)Saved.this.keynamedata.get(i)).put("is_paid", "1");
     }
     label246: ((HashMap)Saved.this.keynamedata.get(i)).put("is_paid", "0");
}

Solution

  • A break with a label is not the same as a goto statement. Java does not have a goto statement.

    A label marks the statement that follows it. You can use it to break out of that statement, and only out of that statement. Control of flow will always transfer to the end of the labeled statement.

    So what do you have here?

            label149: if (!localIterator2.hasNext());
    

    Because of the semicolon after the if, this is in fact the entire labeled statement. So your break label149 is not within its scope at all. If you did not have that semicolon, the if block would include the while, and then the break label149 would work. But control would be transferred to the line after the end of the while block.

           label246: ((HashMap)Saved.this.keynamedata.get(i)).put("is_paid", "0");
    

    This is the statement marked by label246. Again, the break label246 is not inside it, so it is not in its scope, and you can`t break out of a statement you are not inside of.