What is the result of compiling and running programs (JDK to version 6 inclusive) when starting the class considered MainClass?

public class MainClass {
    static {
        MyClass m = new MyClass();                  // 1
        System.out.println(m.toString());           // 2
        System.exit(0);
    }
}

class MyClass {
    public String toString() {
        return "MyClass";
    }    
}
Explanation
In Java 6 the class runs in the following sequence:
1) There is a loading class MainClass;
2) The initialization of the class and the blocks with static initialization are being made;
3) And then the JVM might try to call the method main(), that is absent in the class MainClass. But in the static block the completion of the program by calling System.exit (0). has already happened

In Java 7 the sequence is changed a bit the resolving of the main method is executed to the class initialization. Therefore, immediately ejected NoSuchMethodException, handler displays a message
Error: Main method not found in class MainClass, please define the main method as:
public static void main (String[] args)

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes