Can we execute a program without main() method in java?

Yes, using static block (not possible from JDK 1.7 onwards)
 
for example:
class A
{
 static
{
 String name = getName();
 System.out.println(name);
}
 
public static String getName()
{
 return “project code bank”;
}
}
 
output:
project code bank
Exception in thread “main” java.lang.NoSuchMethodError: main
 
using System.exit(0) in the static we can avoid NoSuchMethodError exception
 
class A
{
static
{
String name = getName();
System.out.println(name);
System.exit(0);
}
 
public static String getName()
{
return “project code bank”;
}
}
 
output:
project code bank
Rate this post

Leave a Reply