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.
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.
System.out.println(“Standalone program execution without main()”);
> 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.