0

I made a mistake while testing some code and forgot to delete a line that contained only a URL. The code looked something like this:

class Example {
    public static void main(String[] args) {
        https://example.com
        System.out.println("Example");
    }
}

I assumed that the compiler would fail because a non-Java code was present in the first line of the main method. However, the code compiled and worked fine.

I thought that everything after the // symbol was a comment and expected the following code to fail compilation:

https:
System.out.println("Example");

To my surprise, it compiled without error.

However, the following code produced a compile error, as expected:

class Example {
    public static void main(String[] args) {
        https://example.com
    }
}

Compiler error

/Example.java:4: error: illegal start of statement
    }
    ^
1 error

Can anyone explain why and under what circumstances the javac compiler ignores a line that contains a URL?

I compile the code online in https://www.jdoodle.com/ locally by hand and the behavior is the same always. I used Java8 and Java17.

I saw that the line is ignored because in intellij I could check in the decompiled code that the line is not there.

  • 2
    It doesn't "contain a URL", it contains a label and a comment. It just happens to look like a URL. – Dave Newton Apr 19 '23 at 16:06
  • What you accidentally used via `https:` is called a [label](https://stackoverflow.com/questions/28381212/how-to-use-labels-in-java-code). – OH GOD SPIDERS Apr 19 '23 at 16:07

1 Answers1

1

It is actually valid Java code:

    https://example.com
    System.out.println("Example");

The https: is a label

The // is a comment ... to the end of the line

The System.out.println("Example"); is the statement that is labelled with https:

Labelled statements are an obscure Java construct that is used in conjunction with the break to label statement. Here's a (marginally) useful example:

out: while (true) {
        int i = Random.nextInt(10);
        while (true) {
            int j = Random.nextInt(10);
            if (i == j) break out;
        }
     }

The break out; breaks the two while loops.


Your second example is not valid Java because there isn't a statement after the label.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216