7

In one of the forum I found below code as a question:

public class Test{
    public static void main(String[] args){
        System.out.println("Hello");
        Test:
        System.out.println("World");
    }
}

And asked what would be the result ?

I thought it would be a compile time error, since I have not seen Test: code in java. I was wrong, surprisingly both line is printed after compiling and running above code.

Can any one tell me what is the use of this Test: kind of code ? And why it is not throwing error ?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Narayan Subedi
  • 1,343
  • 2
  • 20
  • 46

2 Answers2

8

Text followed by a colon (:) is called a label. It can be used in the context of control structures (such as loops) to break to or continue at. In this context, although perfectly legal, it's pointless.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
5

The Test: text is a label, and is described in the language specification, and are used to break or continue from inner loops as shown in the following example:

Unlike C and C++, the Java programming language has no goto statement; identifier statement labels are used with break or continue statements (§14.15, §14.16) appearing anywhere within the labeled statement.

public static void main(String[] args) {
    outerLoop:
    while (true) {
        int i = 0;
        while (true) {
            System.out.println(i++);
            if (i > 5) {
                break outerLoop;
            }
            if (i > 10) {
                break;
            }
        }
        System.out.println("Broken inner loop");
    }
    System.out.println("Broken outer loop");
}
Edd
  • 3,724
  • 3
  • 26
  • 33