How can this Java code compile?

牧云@^-^@ 提交于 2019-12-08 21:24:38

问题


A colleague came across some code that looked like this and couldn't understand how it could ever compile:

class FooClass {
  public static void bar(String arg) {
     System.out.println("arg = " + arg);
     http://www.google.com
     System.out.println("Done!");
  }
}

Basically, there was a random URL pasted in the middle of a method but javac didn't care.

We worked out so I'll post the answer if no-one else finds out but I thought it was interesting enough to post.


回答1:


"http:" is interpreted as a label. What follows is an end-of-line comment.




回答2:


You have a label

http:

followed by a comment

//www.google.com



回答3:


Easy. The highlighting on this site shows why.

http: is a label, as in break http;

//www.google.com is a comment.




回答4:


http: is the label. // starts the comment.




回答5:


"http:" is a label, and the part after the "//" is, of course, a comment




回答6:


Another example with two http://

public class Main {
    {
        http://en.wikipedia.org/wiki/Hello_world_program
        System.out.print("Hello ");
    } {
        http://java.sun.com/docs/books/tutorial/getStarted/application/index.html
        System.out.println("World!");
    }

    public static void main(String... args) {
        new Main();
    }
}


来源:https://stackoverflow.com/questions/916871/how-can-this-java-code-compile

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!