I was asked this question in an interview.
How to print message on console without using main()
method?
class MainMethodNot
{
static
{
System.out.println("Hello World");
System.exit(0);
}
}
Because the static initializer block is executed when the class is first loaded, we can print out “Hello World” without writing a main method. The execution is stopped using “System.exit()” command. So, we prevent “main method not found” error. It's quite a tricky question
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.)
It was possible till java 6 to use System.out.println(); without main(). From java 7 onwards, it is not possible to do it with static block. It will still ask for main method in main class.
Actually it doesn't work in the latest update of java 8. You can call it a bug fix according to them, but as far as I believe on my current knowledge this can't be called as a bug fix because it also lead to few conceptual changes too in java programming.
Yes, you can print a message to console without using main().
Create a test with JUnit and execute it:
@Test
public printTest() {
System.out.println("myprint");
}
If you don't want to use static block too, it can be done following way
public class NoMain {
private static final int STATUS = getStatus();
private static int getStatus() {
System.out.println("Hello World!!");
System.exit(0);
return 0;
}
}
However, please note that this is for Java 6 version. Its not working in Java 7 which is said to be supported in Java 8. I tried with JDK 1.8.0_77-b03, which is still not working