Since the Java method is one of the important Java methods,   developers consider it compulsory in Java.  It is true to some extent, but not in all cases.

The main method is the entry point in Java and whenever we execute a program in Java JVM searches for the main method and begins to execute it.

Moreover, there is a condition that if you are using the Java JDK version till JDK 5,   you don’t need to use the main method in your program and more so, you should write your code under a static block then you can code normally.

Example: 

// Java Program to demonstrate till Java JDK5 version
// without main() method is possible.
class WithoutMainMethod {
static {
int i = 2, j = 4, sum;

sum = i + j;

System.out.println(“The sum of i and j is :” + sum);
System.out.println(“This program is without main() valid till JDK 5 version”);
}
}

Here is the output of the above example.

E:\Programs>javac WithoutMainMethod. Java

E:\Programs>java WithoutMainMethod

The sum of I and j is: 6

This program is without main() valid till JDK 5 version

Here static block executes before the main method. And when you use the main method, your program starts executing from the main method.

As mentioned above, till Java JDK 5, the main method was not compulsory, but for Java JDK 6, the main method is mandatory.

Can you run spring boot without the main method?

In response to a question that whether we can run spring boot without the main method? Remember that all you should SpringBootServietnitializer as mentioned Kryger. What happens is that @SpringBootApplication public class Application prolongs SpringBootServietniitializer.

That is, {@Override protected SpringApplicationBuilder organize(SpringApplicationBuider application{ return application

@SpringBootApplication

public class Application extends SpringBootServletInitializer {

    @Override

    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {

        return application.sources(Application.class);

    }

….

….

Hence in the case of Spring Boot, you need to do three main things:

  • Employ @SpringBootApplication
  • Enhance SpringBootServiietinitializer
  • Overwrite the configure method as given above

Conclusion

In short, the main method is required for any executable program because when we aim to execute a Java class, the JVM looks for the main method to invoke it. However, not all classes need a main method like the Java JDK version till JDK 5.

References:

  • https://en.wikipedia.org/wiki/Java_syntax#main_method
  • https://www.includehelp.com/java/is-main-method-compulsory-in-java.aspx
  • https://stackoverflow.com/questions/29782148/why-do-i-need-main-method-if-i-develop-web-app-as-war-using-spring-boot/29791224

 

 

 

You cannot copy content of this page
Scroll Up

  • Name

  • Minimum length of 8 characters.