Why main method is public static in Java?

Main method in Java

Main method in Java is the first programming method a Java programmer knows when he starts learning Java programming language.have you ever thought about why main method in Java is public, static and void, of-course Yes, since most of us first learn C and C++ than we move to Java in our programming path we familiar with main method but in Java main method is slightly different it doesn’t return any value like in C it returns int, main method is public static and void Why? In this post we will try to find answer of these questions and have an idea of one of the most popular questions in Java why main method is declared Static.

What is main method in Java?

Main method in Java is entry point for any core Java program. Remember we are not talking about Servlet, MIDlet or any other container managed Java program where life cycle methods are provided to control the execution. In core Java program, execution starts from main method when you type java main-class-name, JVM search for public static void main(String args[]) method in that class and if it doesn’t find that method it throws error NoSuchMethodError:main and terminates.

Signature of main method in Java
Main method has to strictly follow its syntax; other wise JVM will not be able to locate it and your program will not run. Here is the exact signature of main method
public static void main(String args[])
This signature is classic signature and there from start of Java but with introduction of  variable argument or varargs in Java5 you can also declare main method in Java using varargs syntax as shown in below example:
public static void main(String… args)
Remember varargs version of java main method will only work in Java 1.5 or later version. Apart from public, static and void there are certain keywords like final, synchronized and strictfp which are permitted in signature of java main method.

Why main method is static in Java

Now come to the main point “Why main method is static in Java”, there are quite a few reasons around but here are few reasons which make sense to me:
1. Since main method is static Java virtual Machine can call it without creating any instance of class which contains main method.
2. If main method were not declared static than JVM has to create instance of main Class and since constructor can be overloaded and can have arguments there would not be any certain and consistent way for JVM to find main method in Java.
3. Anything which is declared in class in Java comes under reference type and requires object to be created before using them but static method and static data are loaded into separate memory inside JVM called context which is created when a class is loaded. If main method is static than it will be loaded in JVM context and are available to execution.
Why main mehtod is public in Java
Java specifies several access modifiers e.g. private, protected and public. Any method or variable which is declared public in Java can be accessible from outside of that class. Since main method is public in Java, JVM can easily access and execute it.
Why main method is void in Java
Since main method in Java is not supposed to return any value, its made void which simply means main is not returning anything.
1. Main method must be declared public, static and void in Java otherwise JVM will not able to run Java program.
2. JVM throws NoSuchMethodException:main if it doesn’t find main method of predefined signature in class which is provided to Java command. E.g. if you run java Helloworld than JVM will search for public static void main String args[]) method in HelloWorld.class file.
3. Main method is entry point for any Core Java program. Execution starts from main method.
4. Main method is run by a special thread called “main” thread in Java. Your Java program will be running until your main thread is running or any non-daemon thread spawned from main method is running.
5. When you see “Exception in Thread main” e.g.
Exception in Thread main: Java.lang.NullPointerException it means Exception is thrown inside main thread.
6. You can declare main method using varargs syntax from Java 1.5 onwards e.g.
public static void main(String… args)
7. Apart from static, void and public you can use final, synchronized and strictfp modifier in signature of main method in Java.
8. Main method in Java can be overloaded like any other method in Java but JVM will only call main method with specified signature specified above.
9. You can use throws clause in signature of main method and can throw any checked or unchecked Exception.
10. Static initializer block is executed even before JVM calls main method. They are executed when a Class is loaded into Memory by JVM.
Source  : Javarevisited

JSP Life Cycle

JSP’s life cycle can be grouped into following phases.

1. JSP Page Translation:

A java servlet file is generated from the JSP source file. This is the first step in its tedious multiple phase life cycle. In the translation phase, the container validates the syntactic correctness of the JSP pages and tag files. The container interprets the standard directives and actions, and the custom actions referencing tag libraries used in the page.

2. JSP Page Compilation:

The generated java servlet file is compiled into a java servlet class.

Note: The translation of a JSP source page into its implementation class can happen at any time between initial deployment of the JSP page into the JSP container and the receipt and processing of a client request for the target JSP page.

3. Class Loading:

The java servlet class that was compiled from the JSP source is loaded into the container.

4. Execution phase:

In the execution phase the container manages one or more instances of this class in response to requests and other events.

The interface JspPage contains jspInit() and jspDestroy(). The JSP specification has provided a special interface HttpJspPage for JSP pages serving HTTP requests and this interface contains _jspService().

5. Initialization:

jspInit() method is called immediately after the instance was created. It is called only once during JSP life cycle.

6. _jspService() execution:

This method is called for every request of this JSP during its life cycle. This is where it serves the purpose of creation. Oops! it has to pass through all the above steps to reach this phase. It passes the request and the response objects. _jspService() cannot be overridden.

7. jspDestroy() execution:

This method is called when this JSP is destroyed. With this call the servlet serves its purpose and submits itself to heaven (garbage collection). This is the end of jsp life cycle.

jspInit(), _jspService() and jspDestroy() are called the life cycle methods of the JSP.

Difference between servletContext and ServletConfig

ServletConfig is implemented by the servlet container to initialize a single servlet using init().  you can pass initialization parameters to the servlet using the web.xml deployment descriptor. Every servlet has its own ServletConfig object.

Example code:

<param-value>Difference between servletContext and ServletConfig</param-value>

ServletContext is implemented by the servlet container for all servlet to communicate with its servlet container. It is applicable only within a single Java Virtual Machine.
The ServletContext object is contained within the ServletConfig object. That is, the ServletContext can be accessed using the ServletConfig object within a servlet. You can specify param-value pairs for ServletContext object in  <context-param> tags in web.xml file. ServletContext is created at the application level and shared by all the Servlet codes.

Example : Database string used by the application.

<param-value>Provider=MySQLProv;Data Source=shivasoft;User Id=shiva; Password=soft;</param-value>

difference in ServletRequest.getRequestDispather() and ServletContext.getRequestDispatcher() in Servlet

Servletrequest.getRequestDispatcher(“url”) means the dispatch is relative to the current HTTP request.
Example code:

RequestDispatcher reqDispObj = request.getRequestDispatcher("/login.jsp");

getServletContext().getRequestDispatcher(“url”) means the dispatch is relative to the root of the ServletContext.
Example code:

RequestDispatcher reqDispObj = getServletContext().getRequestDispatcher("/testApp/login.jsp");

Why not to write constructor in Servlet

Technically you can define constructors in servlet. But, the declared constructor cannot access the ServletConfig object or throw a ServletException.

Then why is it not customary to declare a constructor in a servlet? Because the init() method is used to perform servlet initialization. In JDK 1.0 (servlet were written in this version), constructors for dynamically loaded Java classes such as servlets cannot accept arguments. Therefore init() was used to initialize by passing the implemented object of ServletConfig interface and other needed parameters.
Also, Java constructors cannot be declared in interfaces. So, javax.servlet.Servlet interface cannot have a constructor that accepts a ServletConfig parameter. To overcome this, init() method is used for initialization instead of declaring a constructor.

What is preinitialization of servlet

In the java servlet life cycle, the first phase is called “Creation and intialization“.

The java servlet container first creates the servlet instance and then executes the init() method. This initialization can be done in Two ways. The default way is that, the java servlet is initialized when the servlet is called for the first time. This type of servlet initialization is called lazy loading.

The other way is through the <load-on-startup>non-zero-integer</load-on-startup> tag using the deployment descriptor web.xml. This makes the java servlet to be loaded and initialized when the server starts. This process of loading a java servlet before receiving any request is called preloading or preinitialization of a servlet.
Servlet are loaded in the order of number(non-zero-integer) specified. That is, lower(example: 1) the load-on-startup value is loaded first and then servlet with higher values are loaded.


Example to Override the init() method of the servlet

It is not recommended to override the init() method of the servlet.

Here is an example to override init() method of servlet:

public class BookDBServlet ... {

    private BookstoreDB books;

    public void init(ServletConfig config) throws ServletException {

        // Store the ServletConfig object and log the initialization

        // Load the database to prepare for requests
        books = new BookstoreDB();

you must write super.init(config) code and after that program specific logic.