- Why is main method public, static, and void in Java? Answer
- Valid Signature of the main method in Java
- Why the main method is public static and void in Java
- Difference between C, C++, and Java main method
- Java main() Method
- Why is main method public static and void in Java? Will the program compile, if the main method is not static?
Why is main method public, static, and void in Java? Answer
What is the main method in Java?
the main method in Java is a standard method that is used by JVM to start the execution of any Java program. the main method is referred to as the entry point of Java application which is true in the case of core java applications but in the case of container-managed environments like Servlet , EJB, or MIDlet this is not true as these Java programs have their own life-cycle methods like init() , service() or destroy() for Servlet’s which is used by the container. The main method in Java is run by the main thread which is a non-daemon thread and the Java program runs until the main method finishes or any other user thread is running.
When we start JVM by running the java command we also provide the name of the class that contains the main method, which is later invoked by JVM to start Java program execution. for example in the below command :
C:\Documents and Settings\JavaTutorial>edit Calculator.java code of Calculator class public class Calculator > C:\DOCUME~1\JavaTutorial>javac Calculator.java C:\DOCUME~1\JavaTutorial>java Calculator I am main class which contains the main method
Calculator class must contain public static void main(String args[]) method. Now if we change the signature of the main method and try to run the same Java program we will get an error as shown below :
public class Calculator< public static void main(String args)< System.out.println("I am main class which contains the main method"); > > C:\DOCUME~1\sharma>javac Calculator.java C:\DOCUME~1\sharma>java Calculator Exception in thread "main" java.lang.NoSuchMethodError: main
because we have changed String[] to String which means JVM not able to find a standard main method that is required to start execution of the Java program. You can learn more about the main method by joining these free Java Programming courses online.
Valid Signature of the main method in Java
the main method is a standard method and has a pre-specified signature if you change the signature of the main method JVM will not be able to locate the main method will throw Exception at runtime as shown in the above example.
The main method is public, static, and void and accepts a String[] as an argument and from Java 5 onwards it can also accept variable arguments instead of arrays. following signatures are valid main method signatures in Java :
public static void main(String args[]) <> public static void main(String[] args)<> public static void main(String. args)<>
You can also use certain modifiers like final , synchronized, and strictfp along with the main method in Java.
Why the main method is public static and void in Java
This is a very famous core Java interview question and appeared on many fresher and experience level interviews. Though every java programmer uses the main method not everyone is familiar with the reason why the main is static or why the main is public in Java.
1. The main method in Java is public so that it’s visible to every other class, even which are not part of its package. if it’s not public JVM classes might not able to access it.
2. The main method is static in Java so that it can be called without creating any instance. While JVM tries to execute the Java programs it doesn’t know how to create instances of the main class as there is no standard constructor is defined for the main class.
Difference between C, C++, and Java main method
If you come from C and C++ programming language then you know what is the main method as both of these programs also use main() as an entry point for program execution but the main method in C and C++ is quite different than the main method in Java.
The main method in java doesn’t return anything and has return type void while the main method is C and ++ return int.
That’s all on what is the main method in Java, What are the valid signature of the main method in Java, What happens if you put the incorrect signature of the main method, Why the main method is public, static, and void in Java and finally we saw the difference between C, C++ and Java main methods.
This is one of the most important fundamentals of the Java programming language and every Java programmer should be familiar with it.
Java main() Method
Have you ever tried to reason why Java’s main() method is public , static and void ? Why its name is main ? What happens inside JVM when you invoke main() method? What is the purpose of main method? Let’s find out.
Since Java 21, we can create instance main() methods that do not require the public and static access modifiers, as well as, the method arguments are optional.
If we have not created the unnamed class, the discussion in this article still applies.
1. Java main() Method Syntax
Start with reminding the syntax of the main method in Java.
2. Why Java main Method is public?
This is a big question and perhaps most difficult to answer, too. I tried hard to find a good reason for this question in all the good learning material in my reach, but nothing proved enough.
So, my analysis says (like many others): the main method is public so that it can be accessible everywhere and to every object which may desire to use it for launching the application.
Here, I am not saying that JDK/JRE had this exact similar reason because java.exe or javaw.exe (for windows) can use Java Native Interface (JNI) to execute the invoke method for calling the main() method, so they can have invoked it, either way, irrespective of any access modifier.
A second way to answer this is another question, why not public? All methods and constructors in java have some access modifier. The main() method also needs one. There is no reason why it should not be public , and be any other modifier(default/protected/private).
Notice that if we do not make main() method public, there is no compilation error. You will runtime error because the matching main() method is not present. Remember that the whole syntax should match to execute main() method.
Error: Main method not found in class Main, please define the main method as: public static void main(String[] args)
Another big question. To understand this, let suppose we do not have the main method as static . Now, to invoke any method you need an instance of it. Right?
Java can have overloaded constructors, we all know. Now, which one should be used, and from where the parameters for overloaded constructors will come. These are just more difficult questions, which helped Java designers to make up their minds and to have the main method as static .
Notice that if you do not make main() method static , there is no compilation error. You will runtime error.
Error: Main method is not static in class main, please define the main method as: public static void main(String[] args)
Why should it not be void? Have you called this method from your code? NO. Then there is no use of returning any value to JVM, who actually invokes this method. It simply doesn’t need any returning value.
The only thing application would like to communicate to the invoking process is normal or abnormal termination. This is already possible using System.exit(int) . A non-zero value means abnormal termination otherwise everything was fine.
No rock-solid reason. Let us assume because it was already in use with C and C++ language. So, most developers were already comfortable with this name.
Otherwise, there is no other good reason.
6. What happens internally when you invoke main method?
The purpose of the main method in Java is to be a program execution start point.
When you run java.exe , then there are a couple of Java Native Interface (JNI) calls. These calls load the DLL that is really the JVM (that’s right – java.exe is NOT the JVM). JNI is the tool that we use when we have to bridge between the virtual machine world, and the world of C, C++, etc. The reverse is also true. It is not possible to actually get a JVM running without using JNI.
Basically, java.exe is a super simple C application that parses the command line, creates a new String array in the JVM to hold those arguments, parses out the class name that you specified as containing main() , uses JNI calls to find the main() method itself, then invokes the main() method, passing in the newly created string array as a parameter.
This is very, very much like what you do when you use the reflection from Java, it just uses confusingly named native function calls instead.
It would be perfectly legal for you to write your own version of java.exe (the source is distributed with the JDK), and have it do something entirely different.
7. main() method native code in java.c
Download and extract the source jar and check out ../launcher/java.c . It is something like this:
/* * Get the application's main class. */ if (jarfile != 0) < mainClassName = GetMainClassName(env, jarfile); . . mainClass = LoadClass(env, classname); if(mainClass == NULL) < /* exception occured */ . . /* Get the application's main method */ mainID = (*env)-&amp;amp;gt;GetStaticMethodID(env, mainClass, "main", "([Ljava/lang/String;)V"); . .* Make sure the main method is public */ jint mods; jmethodID mid; jobject obj = (*env)-&amp;amp;gt;ToReflectedMethod(env, mainClass, mainID, JNI_TRUE); . . /* Build argument array */ mainArgs = NewPlatformStringArray(env, argv, argc); if (mainArgs == NULL) < ReportExceptionDescription(env); goto leave; > /* Invoke main method. */ (*env)-&amp;amp;gt;CallStaticVoidMethod(env, mainClass, mainID, mainArgs);
So, here you can see what happens when you invoke a java program with the main method.
Java’s main method is used by all developers and everybody knows the basic syntax to write it. Yet, very few completely understand the correct reasoning and the way it works.
In this post, we got a very basic understanding of the things behind the main method that is the primary starting point of an application.
Why is main method public static and void in Java? Will the program compile, if the main method is not static?
Java program’s main method has to be declared static because keyword static allows main to be called without creating an object of the class in which the main method is defined. If we omit static keyword before main Java program will successfully compile but it won’t execute.
For a little detailed description, look at the usual signature of Java’s main method
Above code line begins defining the main method. This is the line at which the program will start executing. All Java applications begin execution by calling main .
The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public , then that member may be accessed by code outside the class in which it is declared. In this case, main must be declared as public , since it must be called by code outside of its class when the program is started. The keyword static allows main to be called without having to instantiate a particular instance of the class. Without having declared main method static , your program will successfully compile but won’t execute and report error at run time. This is necessary since main is called by the Java interpreter before any objects are made. The keyword void simply tells the compiler that main does not return a value. The main is the method called when a Java application begins. Keep in mind that Java is case-sensitive. Thus, Main is different from main. It is important to understand that the Java compiler will compile classes that do not contain a main method. But the Java interpreter has no way to run these classes. So, if you had typed Main instead of main, the compiler would still compile your program. However, the Java interpreter would report an error because it would be unable to find the main method.
Hope you have enjoyed reading the reason why main in Java is declared public static and void. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!