Return to site

☕ JAVA TRICK: Labeled breaks and continues

· java

You know to use the 'break' statement to get out of a loop, but did you know that

you can give it a label to break out of an appropriately labeled outer loop as well?

search: //𝐠𝐞𝐭 𝐛𝐚𝐜𝐤 𝐡𝐞𝐫𝐞
        for (i = 0; i < arrayOfInts.length; i++) {
            for (j = 0; j < arrayOfInts[i].length;
                 j++) {
                if (arrayOfInts[i][j] == searchfor) {
                    foundIt = true;
                    break search; //𝐡𝐞𝐫𝐞
                }
            }
        }

Likewise with 'continue', which skips the rest of current iteration of the innermost loop:

if you pass it a label, it will skip the iteration of the labeled instead.

test: //𝐬𝐤𝐢𝐩 𝐛𝐚𝐜𝐤 𝐭𝐨 𝐡𝐞𝐫𝐞
        for (int i = 0; i <= max; i++) {
            int n = substring.length();
            int j = i;
            int k = 0;
            while (n-- != 0) {
                if (searchMe.charAt(j++) != substring.charAt(k++)) {
                    continue test; //𝐡𝐞𝐫𝐞
                }
            }
            foundIt = true;
                break test;
        }

But as always, just because you can, doesn't mean you should!