We have a perception that every standalone program will have main() method when comes to languages C, C++ and Java. However, there is small difference in understanding.
The main() method is starting point in C, C++ languages but not in Java. In Java, we have a concept called Class Loading. We know that we pass class name as an argument when we run any java program. It means that we are telling the interpreter that class name we are passing must be loaded to start the process. So now we can sure that the starting point of java standalone program is class loading and not main() method. In other words, before reaching main() (which is in the class ), the interpreter must load the class.
Now we know where and how the java program starts its execution. Now we have to execute other code in the program without going to main() (you can also remove completely main() method).
There is a possibility called Static block. This block executes immediately once the class loaded into JVM. The block structure is as follows.
static {
}
This is a separate block which can be written apart of members and methods in a class. The code inside this block executes once the class loads in to JVM. So we can write any sort java code in this bound to our requirements.
However, once the execution of block ends, the JVM looks for the main() method. It does not matter whether you have main() defined or undefined in the program, we can terminate the process completely using System.exit() method. This must be called as a last line of the static block to stop the process intentionally without proceeding further to check for main() method.
class ABC
{
static {
System.out.println(“Standalone program execution without main()”);
System.exit(0);
}
}
> javac ABC.java
> java ABC
Standalone program execution without main()
This is how we can run a standalone program without using main() method.
Happy Learning – Java.













I really enjoyed the article . Hope this is written by vasu.
Warm welcome to your excellent articles.
Hi sir, i have a ques related to threads, if there are 2 threads t1 and t2, t1 should print 1 to 10 and t2 should print 10 to 1.
Answered in Android section.
thanks,
satish.p