I was asked this question in an interview.
How to print message on console without using main()
method?
public class Foo {
static {
System.out.println("Message");
System.exit(0);
}
}
The System.exit(0)
exits program before the jvm starts to look for main()
(Note: This works only with java 6. Even if it compiles with JDK 7's javac
it cannot be run with its java
, because it expects a main(String[])
method.)