Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a HTTP URL in Java compile? [duplicate]

Tags:

java

If you have a program like this:

public class ABC
{
    public static void main(String args[])
    {
        System.out.println("1");
        http://example.com
        System.out.println("2");
    }
}

Note the URL http://example.com written in between the two output statements.

Why does the program compile without any errors?

like image 444
dryairship Avatar asked Jan 03 '16 12:01

dryairship


3 Answers

The reason the program compiles without error is that the program considers http: as a label, which is allowed in Java, and is mostly used with loops.
The second part, i.e., //example.com is a comment, due to the //, and is therefore ignored by the compiler.

Hence it compiles properly.

like image 161
dryairship Avatar answered Oct 09 '22 22:10

dryairship


As it described in this answer, this code compiles because Java compiler thinks that http: is a label and everything after // is a comment.

In addition, this won't compile:

System.out.println("1");
http://example.com
int i = 1;

And this won't:

System.out.println("1");
http://example.com
Date date = new Date();

But this will:

System.out.println("1");
int i;
http://example.com
i = 1;

And this will:

int i = 0;
System.out.println("1");
http://example.com
i = i + 1;

And this:

int i = 0;
System.out.println("1");
http://example.com
i++;

So you can't declare the variable after the label. Also Intellij IDEA shows some warnings with code like this.

like image 18
coolguy Avatar answered Oct 09 '22 22:10

coolguy


Looks like compiler accepting only statements after labels. So reserved keywords and class names are not allowed. But there is an exception to this rule.

interface PrintSome {
    default void print() {
        System.out.println("I`m printing some!");
    }
}

and then:

http://www.example.com
new PrintSome(){}.print();

is compiling.

like image 1
over9k Avatar answered Oct 09 '22 22:10

over9k