Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

static

I have the following simple hello world in Java:

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

It works as expected, but oddly, it gives an error saying that the main method doesn't exist after.

$ javac A.java && java A
Hello world
Exception in thread "main" java.lang.NoSuchMethodError: main

Why? Should I ignore it? I even tried making a method called "main", but it changes nothing.

class A {
    static {
        main();
    }
    public static void main() {
        System.out.println("Hello world");
    }
}

$ javac A.java && java A
Hello world
Exception in thread "main" java.lang.NoSuchMethodError: main
like image 793
Dog Avatar asked Jul 05 '13 21:07

Dog


2 Answers

When your class is loaded, static initializers will be run, and then the JVM will try to invoke the main method. You can fix this by adding one more line to your static initializer:

public class HelloWorld {
    static {
        System.out.println("Look ma', no hands!");
        System.exit(0);
    }
}

This will stop the JVM before it tries to invoke your main method.

Also note, this will not execute in Java 7. Java 7 looks for a main method before initializing the class.

like image 170
Jeffrey Avatar answered Oct 23 '22 06:10

Jeffrey


Its because your class is loaded by the class loader, static code is executed, then it searches for the main method and crashes as it doesn't exist.

Code in a class wrapped in a static block which is outside any method will execute upon first reference of that static class.

The reason it can't find your main method is you've declared it incorrectly. Main looks like this:

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

Get used to that line. You'll see it many, many times.

The String[] args... argument is a list of space delineated arguments a user can pass to your program through a shell. All programs enter through the main method. This is a standard passed down for some time.

A static block could be used in a class to start your program, but it would cause confusion and be extremely improper. Using a main method as an entry point is the industry standard.

I am unable to give a reason why this is the standard, or give a more convincing argument as to why to use it other than to get input into your program from a shell. I do not suggest starting your program from a static block.

like image 11
William Morrison Avatar answered Oct 23 '22 05:10

William Morrison