I’m busy studying for my certification and I stumbled upon a concept I’ve never even heard before – “Labeled Statements”. e.g:
‘label’ : ‘statement’
L1: while(i < 0){
L2: System.out.println(i);
}
So my question is.. why? How is this useful and when would one want to use something like this?
The only use that I’m aware of is that you can use labels in
breakorcontinuestatements. So if you have nested loops, it’s a way to break out of more than one level at a time:As the example implies, it’s occasionally useful if you’re iterating over two things at once in a nested fashion (e.g. searching for matches) and want to continue – or if you’re doing normal iteration, but for some reason want to put a break/continue in a nested
forloop.I tend to only use them once every few years, though. There’s a chicken-and-egg in that they can be hard to understand because they’re a rarely-used construct, so I’ll avoid using labels if the code can be clearly written in another way.