0

i'm working on a legacy project & i found something like that :

test:{
        if(1 == 1) {
            System.out.println("Oups");
            break test;
        }
        System.out.println("Hello World");
    }

I google it, but nothing seems to match with this kind of structure.

Of course, this part of code compile & run ... ????

Do someone know what that do ?

neilerua
  • 3
  • 1
  • 4
    `test:` is called a label. Just like on a loop, the `break` jumps to the end of a block. While it works, labels are generally too confusing, partly because they are rarely used, so I would avoid them. This has been part of Java since version 1.0 and is still supported in Java 10. – Peter Lawrey Feb 28 '18 at 10:16
  • @PeterLawrey: I don't know for Java, but the .NET framework internal implementation uses a lot of labels. – Thomas Weller Feb 28 '18 at 10:19
  • @PeterLawrey: okay, thank you – neilerua Feb 28 '18 at 17:13

4 Answers4

0

test: is called a label. Just like on a loop, the break jumps to the end of a block. The label is used to define where the break jumps to. Note the start of the scope doesn't mater provided the end is where you need it to be so really you are labelling the end not the start of the code to break to.

While it works, labels are generally too confusing with if statements, partly because they are rarely used, so I would avoid them. If you can write something with a label, you can usually write it without by using a method or in this case using an else to the if

Even using labels with loops should be avoided if you can.

This has been part of Java since version 1.0 and is still supported in Java 10.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

It is called label.

It is used with break to do something similar to goto in other languages.

More details you can find here

talex
  • 17,973
  • 3
  • 29
  • 66
0

Jump-out label (Tutorial):

label: for (int i = 0; i < x; i++) {
    for (int j = 0; j < i; j++) {
        if (something(i, j)) break label; // jumps out of the i loop
    }
} 
// i.e. jumps to here
Dsenese1
  • 1,106
  • 10
  • 18
-2

As comments already said, this is a label that break can jump to / out of. More information here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

kutschkem
  • 7,826
  • 3
  • 21
  • 56