Hello world works but then gets error that there's no main?

前端 未结 6 605
星月不相逢
星月不相逢 2020-12-09 09:57

I have the following simple hello world in Java:

class A {
    static {
        System.out.println(\"Hello world\");
    }
}

It works as ex

6条回答
  •  天涯浪人
    2020-12-09 10:39

    You do need a main method. In your last code example you've defined it wrong. Define it like this:

    public static void main(String[] args) {
    
    }
    

    You were missing the args that's why it still complained the second time.

    @WilliamMorrison and @Jeffrey have explained why your program outputs "Hello world" and then it crashes.

    There is a very good reason to use main instead of the way you're using the static block. Mainly, that it's the entry point into your program. You can't successfully run your program from the java command without one. You can't execute a jar file without one. And, as you've seen, you'll If you're missing a main, you'll get this error every time unless you write a hack to prevent it (see @Jeffrey's answer. I don't mean that in an offensive way, his answer is very informative, but it is a hack IMO).

    Another thing is that this is not idiomatic. If I had to read your code I'd be wondering, "Where does this freaking code start?!" I wouldn't be able to download it and figure out how to get my tools (IDE, maven, ant, etc) to run it. Intellij doesn't know it can run a class without a main method. That is the standard entry point into a program.

    A random static block is not an entry point. There's no way to pass arguments into it. For example, if you wanted to write a command line program like unix's "cat" where you pass in a file name and it outputs the file contents, you couldn't do that with a static block because there would be no way to set and get the input.

提交回复
热议问题