Labeled Loops in Java लेबल किए गए लूप

Labeled loops are used in Java when working with nested loops to control the flow of execution more precisely. A label is simply a valid Java identifier followed by a colon (:) placed before a loop. It allows the use of break or continue to directly jump to or skip a specific loop block rather than just the inner one. These are especially useful when you need to exit or continue an outer loop from inside an inner loop.

लेबल्ड लूप का उपयोग जावा में नेस्टेड लूप के साथ किया जाता है ताकि प्रोग्राम के कंट्रोल फ्लो को अधिक सटीक तरीके से नियंत्रित किया जा सके। एक लेबल, एक वैध जावा पहचानकर्ता होता है जिसे कोलन (:) के साथ लूप के पहले लिखा जाता है। इसका प्रयोग break या continue स्टेटमेंट के साथ करके हम सीधे बाहरी लूप को प्रभावित कर सकते हैं। यह तब उपयोगी होता है जब हमें किसी इनर लूप से निकलकर सीधे आउटर लूप पर कार्य करना हो या उसे स्किप करना हो।

Syntax:

labelName:
for(initialization; condition; update){
   // loop body
}
labelName:
while(condition){
   // loop body
}

✅ Java Example using Labeled break

public class LabeledBreakExample {
    public static void main(String[] args) {
        outerLoop:
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (i == 2 && j == 2) {
                    break outerLoop; // exits both loops
                }
                System.out.println("i=" + i + ", j=" + j);
            }
        }
    }
}

✅ Java Example using Labeled continue

public class LabeledContinueExample {
    public static void main(String[] args) {
        outerLoop:
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (j == 2) {
                    continue outerLoop; // skips to next iteration of outer loop
                }
                System.out.println("i=" + i + ", j=" + j);
            }
        }
    }
}

Comments

Popular posts from this blog

What is a Web Browser? वेब ब्राउज़र क्या है?

Java's Support System जावा का सहयोगी तंत्र

The Internet and Java इंटरनेट और जावा का सम्बन्ध