0

In this code:

search :
        for (int i = 1; i <= 30; i++) {
            System.out.println(i);
            if (i == 20) {
                break search;
            }
        }

What is search and how does one use it?

And wouldn't this code do the same without it?

Berry
  • 2,143
  • 4
  • 23
  • 46

1 Answers1

0

search: is a label. You use labels with loops (break and continue) to indicate which loop is to be exited or continued.

Tutorial: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

In this case, there's only one loop. So yes I think the program would work the same without the label. However, occasionally I've seen labels used as a kind of comment to indicate what exactly is being done, and I guess that's what the coder here has done

markspace
  • 10,621
  • 3
  • 25
  • 39