Label in Java

The label in Java (from version 7) is a way of giving a logic name to a loop statement.

Why naming a statement in Java?
Just because in case, of very deeper loops, you want to break/continue that specific statement.

How to give a name to a statement?
Specifying a name (as a class style) followed by “:”

How can you break using label?
Simple, with break and continue followed by the label name. That’s it.

Example

  Task:
  {
    (loop statement){
        if (condition){
            break Task;
        }
    }
  }

In the above example “Task” is the label. When you reach the line “break Task;” the program will go outside the Task statement.
Of course the similar logic works with “continue Task;“, but in this case the program will continue with labeled statement.

A little curiosity, the below code works perfectly:

public int myMethod(){
http://www.google.com
return 1;
}

because “http:” is treated as label and “//www.google.com” is treated as comment

0 Comments

Add Your Comment: