15

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?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880

6 Answers6

25

The only use that I'm aware of is that you can use labels in break or continue statements. So if you have nested loops, it's a way to break out of more than one level at a time:

OUTER: for (x : xList) {
          for (y : yList) {
              // Do something, then:
              if (x > y) {
                  // This goes to the next iteration of x, whereas a standard
                  // "continue" would go to the next iteration of y
                  continue OUTER;
              }
          }
       }

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 for loop.

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.

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
  • That would explain the use of `L1`, but what about `L2`? – Baz Aug 22 '12 at 10:18
  • @Baz I think the L2 just there to show the syntax. This was copied out of my text book. No reference to L2 in the book either.. –  Aug 22 '12 at 10:20
  • @DeanGrobler Ah, I see. I couldn't think of any purpose of `L2`. – Baz Aug 22 '12 at 10:21
  • @Baz You're right - I just got rid of the `L2` because it was completely unnecessary. Though it does indicate that you're free to label any statements, even if you don't have code that uses those labels. Sometimes it might be clearer to label a bunch of stuff (e.g. some might consider that the `OUTER` label makes more sense when there's also an `INNER` label to provide context; while others would consider the latter just extra clutter.) – Andrzej Doyle Aug 22 '12 at 10:22
  • @AndrzejDoyle Since once can label any statements (except declaration statements). Can one then also use labeled statements out of a looping context e.g. LABEL1 : System.out.println("Hello"); LABEL2 : continue LABEL1; This would essentially create a never ending loop? in other words, using labels outside of a looping structure labels could be used to jump anywhere in the class? –  Aug 22 '12 at 10:33
  • Nevermind my stupid last comment. I see that when saying continue LABEL 1; or whatever. It does not repeat the statement labeled LABEL 1, but control flows to the statement after LABEL1... –  Aug 22 '12 at 10:44
  • the example aint so good as `continue OUTER` can be replaced by simple `break`, you need some code *after* the inner loop to make evident why one may opt to use labels. – bestsss Aug 22 '12 at 11:02
  • @DeanGrobler The biggest problem in fact is that you can't use `continue` outside of a loop context. If you *could* (i.e. if there was a `goto` command, which there isn't), then you would indeed have an infinite loop. So you can indeed *label* statements outside of a loop context, it's just it will be hard to do anything useful with those labels. – Andrzej Doyle Aug 22 '12 at 11:21
  • This `labeled statement` language feature seems awfully similar to C's `goto`... – Trevor Boyd Smith Aug 22 '12 at 12:18
  • @bestsss Would `break OUTER` be more to your liking? – Izkata Aug 22 '12 at 18:12
  • @TrevorBoydSmith `if` statements are controlled `goto`s, as is this. I see nothing wrong. And `goto` itself isn't bad, it's just been vilified because of coders without discipline who abuse it. – Izkata Aug 22 '12 at 18:14
  • @Izkata, No where in my comment did I say anything about this feature being "wrong" or "goto being bad". It's almost like you read something completely different from what I wrote. – Trevor Boyd Smith Aug 22 '12 at 21:06
  • @TrevorBoydSmith I didn't realize you were responding to Andrzej. Without that context, it looks like you're just pulling the comparison out of nowhere, which makes it sound like you're trying to say labeled statements are bad like `goto`. (As a side note, once a poster comments on their submission, you can directly respond to them with @ to lessen the ambiguity) – Izkata Aug 22 '12 at 21:39
  • @Izkata, that's acceptable indeed, continue OUTER is just a bad example. – bestsss Aug 23 '12 at 07:25
21

It can be used to avoid the need for a "not found" flag.

FOUND: {
  for(Type t: list)
     if (t.isTrue())
        break FOUND;

  // handle not found.
}

This is perhaps a misuse of labels, but you can use them to break without a loop.

LABEL: {
    if(condition)
       break LABEL;
    // do something
}

It can also be used to confuse people, which is a good reason to avoid it. ;)

http://www.google.com
while(true) break http;
Zoltán
  • 21,321
  • 14
  • 93
  • 134
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

I think that they are required so that you can write Fortran while pretending to write Java. Without them, the aphorism Real programmers write in Fortran whatever language they are using might be invalidated.

bestsss
  • 11,796
  • 3
  • 53
  • 63
High Performance Mark
  • 77,191
  • 7
  • 105
  • 161
  • I approve this statement (although I can't do FORTRAN myself), sweet memories - I was kid (10 I guess) reading about the true macho of the programming... real nice stuff. Btw, the answer does miss a link to the original story though (and possibly about Mel as well) – bestsss Aug 22 '12 at 10:41
  • @bestsss: if you want to improve this 'answer' with links, go right ahead, it's the SO way. – High Performance Mark Aug 22 '12 at 10:47
  • ok, Mel story also addresses the (infinite) loop and the lack of `break` – bestsss Aug 22 '12 at 10:57
  • @bestsss I am not sure how the links relates to the question, but thanks for sharing these. They are great pieces of writing. – Simon Bergot Aug 22 '12 at 14:24
  • @Simon, *Real Programmers aren't afraid to use GOTOs.* `break/continue label` is practically GOTO, you can't get better than this (in java, that's it) – bestsss Aug 22 '12 at 14:27
  • Exactly. Labels exist to be the targets of `GOTO`s. And what is `break` but a sugary substitute for `GOTO` ? – High Performance Mark Aug 22 '12 at 14:31
  • break is as much a substitute for GOTO as for loops and return statements. – Simon Bergot Aug 22 '12 at 14:58
2

I used to use those as comment statements :) Jokes aside, it is like the Go to statements in basic, which allows you to jump to a line of code, ie during a deep looping structure...

Usage:

scan: {
      int c;
      for (firstUpper = 0 ;
          firstUpper < count ;
          firstUpper += Character.charCount(c)) {
        c = codePointAt(firstUpper);
        if (c != Character.toLowerCase(c)) {
          break scan;
        }
      }
      return this;
    }
sed
  • 5,431
  • 2
  • 24
  • 23
2

Here is an example of inordinate break that is likely to be missed out by the rest of the replies. It allows to break a loop within switch{} statement:

loop: for(;;){
  int c=in.read();
  switch(c){
  case -1:
  case '\n':
    break loop;
  case 'a':
    processACommand();
    break;
  case ...
  default:
    break;
  }

}
bestsss
  • 11,796
  • 3
  • 53
  • 63
0

As other answers have stated, labels are a seldom used part of the Java language.

But in your case some other things should be considered:

  • The labels are quite "generic" and are in fact line numbers: L1, L2, ...

  • The labels are not used in the code.

  • You are studying material for a certification.

This means, that the L1, L2 labels are simply line numbers. I assume, that the text explaining the code refers to that line numbers. In the same way some books and papers enumerate all mathematical terms just for referencing them in the text or to make citations easier.

A.H.
  • 63,967
  • 15
  • 92
  • 126