Wednesday, May 10, 2023

Why main method is public static in Java

The 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 the 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 the main method but in Java main method is slightly different it doesn't return any value like in C it returns an int, the main method is public static and void Why?

In this post, we will try to find answers to these questions and have an idea of one of the most popular questions in Java why the main method is declared Static.


What is the main method in Java?

The main method in Java is the 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 the 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 the main method in Java

The main method has to strictly follow its syntax; otherwise, JVM will not be able to locate it and your program will not run. Here is the exact signature of the main method



public static void main(String args[])

This signature is a classic signature and there from the start of Java but with the introduction of  variable argument or varargs in Java5 you can also declare the main method in Java using varargs syntax as shown in the below example:

public static void main(String... args)

Remember varargs version of the java main method will only work in Java 1.5 or later versions. 

Apart from the public, static and void, there are certain keywords like final, synchronized, and strictfp which are permitted in the signature of the java main method.

Why the main method is static in Java?

why main method is public static void in JavaNow come to the main point "Why the 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 the main method is static Java Virtual Machine can call it without creating an instance of a class that contains the main method.

2. Since C and C++ also have a similar main method which serves as an entry point for program execution, following that convention will only help Java.

3. If the main method were not declared static then JVM has to create an instance of the main Class and since the constructor can be overloaded and can have arguments there would not be any certain and consistent way for JVM to find the main method in Java.

4. Anything which is declared in class in Java comes under reference type and requires objects to be created before using them but the static method and static data are loaded into separate memory inside JVM called context which is created when a class is loaded. If the main method is static then it will be loaded in the JVM context and are available for execution.



Why the main method 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 accessed from outside of that class. Since the main method is public in
Java, JVM can easily access and execute it.


Why the main method is void in Java

Since the main method in Java is not supposed to return any value, it's made void which simply means main is not returning anything.

Summary:
1. The 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 the 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. The main method is an entry point for any Core Java program. Execution starts from the main method.

4. The 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 the 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 the 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 a final, synchronized and strictfp modifier in the signature of the main method in Java.

8. The main method in Java can be overloaded like any other method in Java but JVM will only call the main method with the specified signature specified above.

9. You can use the throws clause in the signature of the main method and can throw any checked or unchecked Exception.

10. A static initializer block is executed even before JVM calls the main method. They are executed when a Class is loaded into Memory by JVM.


Some tutorials you may like

29 comments:

  1. Though I understand why main is static in Java and why main is publicI didn't understand the point on making main method void in Java, Why not it could be int or boolean to return whether it ran successfully or not. We already have main method in C++ and C which returns int.

    ReplyDelete
  2. one more point is that one can play with the argument to main method as:
    String[] args,String args[]
    Also sometimes we get confused that the following is not a valid main method but it is:
    public static void main(String[] test123){...}

    Java Interview : Database SQL and JDBC
    Connection and Datasource in Java Applications

    ReplyDelete
  3. Following are valid main method signature:

    public static void main(String[] argument)
    public static void main(String argument[])
    public static void main(String... args)
    public static synchronized void main(String... args)
    public static strictfp void main(String... args)
    public static final void main(String... args)

    ReplyDelete
  4. @Neeraj
    We have servlet & other as managed java objects. The java runtime environment provides many facilities like memory allocation & garbage collection etc. Our main application is executed by the JRE process. The process can return the status to the OS as zero or some other integer to return its status. Your application can return the value or JVM itself. Thus it might have make sense to assign the value by using System.exit(1).

    ReplyDelete
  5. Nice explanation of 'public static void main(Strin args[])'. here is my post on the same 'public static void main(String args[]): Explained

    here is point too on main:

    The main method can be overloaded.

    ReplyDelete
  6. do you know how to pass arguments to main method in Java and how to get those arguments inside java program ?

    ReplyDelete
  7. even though main method should not return values,it can use empty return statement.
    ex return; allowed
    but return somevalue; not allowed

    ReplyDelete
  8. Java Main method can also throw any Exception or Error in its throws clause, following main method in java is perfectly legal:
    public static void main(String args[]) throws AssertionError

    ReplyDelete
  9. Can we declare main method private? this was the question asked to me. What will happen if we make main method private in Java, i said we can not access it from outside of Class since its private and also can not run Java program, was that correct answer ?

    ReplyDelete
  10. Can we throw exception from main method in Java ? I am asking both checked and unchecked Exception. Also when do we get error "no main class found your program will terminate"

    ReplyDelete
  11. Can main method throw Exception in Java?
    indeed main method can throw Exception both checked and unchecked.

    Can main method be overloaded in java?
    Yes main method in java can be overloaded but JVM will only invoke main method with standard signature.

    Can main method be overridden in java?
    Yes main method in java can be overridden and the class you passed to java command will be used to call main method.

    ReplyDelete
  12. here are few more questions like why main is static:

    Why run method in Java doesn't return any thing ?
    Why start method is used to start thread instead of run ?

    By the way you can run Java class even without main method, just put your code inside static initializer block and it will be run when class will be loaded.

    ReplyDelete
  13. JVM does not find for the Main Method its the JNI. Secondly your logic that why main is public has no reason. Since the class is never instantiated it doesn't matter is its public or not.

    Main method is entry point for any Core Java program, "Any"...no

    should be "public, static and void in Java", no you can write your own JVM and instead have some other return type and signature.

    You should realize your responsibility, many newbies may read your article and may take your wrong information ar true.

    ReplyDelete
  14. In order to access the Class must be public. All JVM are written using JVM specification and I have never heard of any JVM changing signature of Main method, if you have better reason than please share.

    ReplyDelete
  15. Here is my list of frequently asked question on main in Java
    1. Can we overload main method in Java?
    2. Can we make main method final in Java ?
    3. can we override main in Java ?
    4. How to call a non static method from main in Java ?
    5. can we make main method synchronized ?

    These are good questions for any beginner to know more about Main method in Java.

    ReplyDelete
  16. can you please tell why it si mandatory to pass String args[] as a argument to main ()?

    ReplyDelete
  17. why other static methods are executed after main() method is executed even when main() method is also static?

    ReplyDelete
  18. This is really helpful for a beginner. Thanks

    ReplyDelete
  19. does any one knows how to call a non static method from main method in Java? I am getting "cannot make a static reference to the non-static method" error while calling a non static method, declared in same class. please help

    ReplyDelete
  20. for exmaple my main fuction is not static how can i call main function i.e can i call main function after creating an object of class in which it is defined and calling it keeping in view that main function is not defined "Static"

    ReplyDelete
  21. similarly i want that my functions in one class can be called by any other class that i define, without creating object of class whose function i want to be called how do i accomplish this
    keep in mind no friend function is allowed

    ReplyDelete
  22. This is how you can invoke NON-STATIC method from main

    public class TestMain {

    public static void main(String[] args) {
    TestMain test = new TestMain();
    test.invokeMethodFromMain();
    }

    private void invokeMethodFromMain(){
    System.out.println("inovked NON-STATIC method from main method");
    }
    }

    ReplyDelete
  23. hello sir you tesch us that main method must be public because public method can access easily outside the class i agree with you but non specifire methods are also like a public but this code is not run
    static void main(String s[]) why it is also accessable outside the class

    ReplyDelete
  24. If public modifier is removed (made default or made private)then JVM reports following: -
    Main method not public.

    If arguments are modified like (String[]args, int i)...to test overloading....then it reports following: -
    Exception in thread "main" java.lang.NoSuchMethodError: main

    This leads to a conclusion that this is a STANDARD FORMAT, JVM looks for, the "public static void main(String[] args)" helps it have an entry point. That is precisely the reason why a thread created when main method executes is called "main" who sets this name to the thread ? .... we developers never set it explicitly but JVM must have done in implicitly, which also means this contract of "public static void main(String[] args)" if followed then JVM will follow it too and the program will execute else it will not.

    ReplyDelete
  25. why main has to be void?

    ReplyDelete
  26. @Anonymous, this is interesting question beause main in C returns int but main is void in Java. I guess only reason could be becasue only JVM calls this method and Java relies on excepiton than error code so it doesn't care what main returns. Since there is no way programmer can query JVM to find out what main returns is another reason it made void.

    ReplyDelete
  27. How JVM understands execution completed of void methods , since void doesn't return anything ??

    ReplyDelete
  28. the main method must take String[] args as its arguments and the reason is consistency.that is everything can be represented as a string so why to have multiple ways to do some task.

    ReplyDelete
  29. HI. Interesting Stuff.

    As per JLS (Java Language Specification), "A Java virtual machine starts execution by invoking the main() method of some specified class, passing it a single argument, which is an array of strings".

    Definition of your main method should be as below

    public static void main(String[] args)

    public - your method should be accessible from anywhere

    static - Your method is static, you can start it without creating an instance. When JVM starts, it does not have any instance of the class having main method. So static.

    void - It does not return anything.

    Henceforth, the main() method is predefined in JVM to indicate as a starting point.

    Hope that helps!

    Read more :- https://softwaretestingboard.com/q2a/1143/

    ReplyDelete