execute the code without main()

sequence is as follows:

  • jvm loads class
  • executes static blocks
  • looks for main method and invokes it

it is possible with static block, but this works only for Java 6.

Java 7 does not support it because it first look at main() as the entry point; if there is no main(), it will not execute the static blocks; but the order is still the same, it first executes the static blocks, then main()

// this will be executed in java 6, but not Java 7
public final class Test {
    static {
        System.out.println("FOO");
    }
}

// public class Test {
    static {
        System.out.println("xxx");
    }

    public static void main(String args[]) {
        System.out.println("yyy");
    }
}
output:
xxx
yyy
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s