Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"loop:" in Java code. What is this, and why does it compile?

This code just made me stare at my screen for a few minutes:

loop: for (;;) {     // ... } 

(line 137 here)

I have never seen this before, and I had no idea Java has a "loop" keyword (NetBeans doesn't even color it like a keyword), and it does compile fine with JDK 6.

What is the explanation?

like image 494
Amy B Avatar asked Sep 29 '10 13:09

Amy B


People also ask

What is the purpose of a loop in Java?

The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop.

What is the purpose for a loop?

Definition: Loops are a programming element that repeat a portion of code a set number of times until the desired process is complete. Repetitive tasks are common in programming, and loops are essential to save time and minimize errors.


1 Answers

It is not a keyword it is a label.

Usage:

    label1:     for (; ; ) {         label2:         for (; ; ) {             if (condition1) {                 // break outer loop                 break label1;             }             if (condition2) {                 // break inner loop                 break label2;             }             if (condition3) {                 // break inner loop                 break;             }         }     } 

Documentation.

like image 50
jmj Avatar answered Sep 20 '22 13:09

jmj