Unknown structure in java 1.6

68 views Asked by At

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 ?

4

There are 4 answers

0
Dsenese1 On BEST ANSWER

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
0
kutschkem On

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

4
Peter Lawrey On

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.

0
talex On

It is called label.

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

More details you can find here