Can we execute java program without main() method?
class MainMethod6
{
static
{
System.out.println("static block");
}
}
/*
Output:- Depending upon java version.
Explanation:- Yes we can execute a java program without main() method with the help of static block
but this idea will work upto jdk1.6 version. Still after printing output in jdk1.6 it
will generate an exception saying "NoSuchMethodError: main". We can hide this exception
by writing "System.exit(0)" before closing the static block. But after from jdk1.7
onwards main() method is mandatory eventhough we are defining static block if the class
doesn't contain main() method it will generate Runtime Error saying "Main method not
found in class MainMethod6, please define main method as......"
*/
{
static
{
System.out.println("static block");
}
}
/*
Output:- Depending upon java version.
Explanation:- Yes we can execute a java program without main() method with the help of static block
but this idea will work upto jdk1.6 version. Still after printing output in jdk1.6 it
will generate an exception saying "NoSuchMethodError: main". We can hide this exception
by writing "System.exit(0)" before closing the static block. But after from jdk1.7
onwards main() method is mandatory eventhough we are defining static block if the class
doesn't contain main() method it will generate Runtime Error saying "Main method not
found in class MainMethod6, please define main method as......"
*/
0 comments: