How main Method works in Java

Introduction

The main method is the starting point of any Java application. When starting the program, this method is invoked by the JVM after loading the class into memory.
The main method should have the following syntax:

main Method Specifiers

Let us understand the need of various keywords in the signature of main method:

public: The method has to be public so that it is visible outside of its package to the JVM. If main method is not public, JVM won’t be able to invoke it.static: JVM doesn’t create any instance before calling the main method. Actually, JVM need not create an instance to call main method because it won’t know which constructor to invoke in case of overloaded constructors and what value to pass if the constructor accepts arguments. This means that the main method has to be static.void: JVM doesn’t expect main method to return anything. Hence the keyword void is used.main: main is the method name looked for by JVM.args: This string array is used as the argument to main method. The purpose of this argument is to capture the command line inputs given while starting the program.

Important points about main method

a) The point to note here is that if one omits static or changes the method access specifier or specifies a return type for the above method, it doesn’t become an invalid method to JVM but it becomes just another method.
b) It is not the main word but all the above specifiers which make main as the starting point.
c) There could be multiple classes in an application having the main method. If this is so, Eclipse will ask for which main method to invoke.
d) We cal also specify main-class in the META-INF folder of a JAR/WAR. This information is then used to identify main method when multiple classes are defining it.
e) The name of argument args for the main method is just a preference and can be renamed to myarg, mainArgument or mainMethod etc.

main method signatures

Let us now look at some valid and in-valid signatures for the main method in a class.

Valid main signatures

Thus we see that shuffling the specifiers doesn’t make any difference. Hence the point is that public, static, void, main should be present in any order.
The argument name “args” is normally used for main method. But we can use any other name as shown in 3rd signature above.

In-valid main signatures

public void main(String[] args) (Removal of static keyword).
public static int main(String[] args) (specify a return type of int. The return type has to be void).
private static void main(String[] args) (Change in method access specifier. The access specifier should be private).
public static void main123(String[] args) (Change in method name from main to main123).
public static void main(String args) (Change in method argument from String array to String).

All of the above have in-valid signature because they are not adhering to the main method specification.
If a class does not have starter main method then an error as NoSuchMethodError is thrown by JVM.

As you can see that arg[0] refers to “welcome” and not “Example”. The program name is not part of the arguments array. Moreover, if no argument is passed and still we try accessing arg[0], we shall get ArrayIndexOutofBoundsException.

Variable Arguments

As noted above, the main method accepts a String array as the only argument. In Java, we can make a method accept variable number of arguments by using ellipses (…). Internally the variable number of arguments to a method is handled by using arrays. This means that there is a direct co-ordination between the string array and varargs for the main method. A valid main method signature when using varargs feature is:

public static void main(String… args)

If you de-compile and see the code for the above main method signature then it will be same as when using:

public static void main(String[] args)

strictfp with main method

Apart from using public, static and void keywords with the main method, we can use the synchronized and strictfp keywords too. Though an in depth discussion of strictfp keyword will not be meaningful here but to get an overview of strictfp keyword, read the following:

The strictfp keyword is used for achieving reproducible results for floating point computations. By default, the JVM is allowed to use high precision computations before truncating the result to 64 bits. This means that if a processor has 80 bit and other has 90 bit registers then running the same program on these processors could result in different results. However if you want to get the same result for every time for the same operation then better use the strictfp keyword. Note that strictfp keyword can be used with method or class (making all method of the class as strictfp).

Troubleshooting Tips

When writing a Java application with main method, the following are some of the issues faced by beginners:

main method not found: If you are trying to run a Java application from within Eclipse IDE and getting an error that no main method was found then check the problems view to see if there were any build path related errors. Always remember that a program can be run only after it has been compiled. If there are build path errors in your project, Eclipse won’t compile the code and hence you won’t be able to run the project as Java application.

Can’t refer non-static members: The non-static members of a class are associated with instances and not to class as a whole. Thus if you try to refer non-static members from the main method, there is no way for JVM to find out which copy of non-static member you want to refer too as there could be 10 instances already created for that class. To resolve this problem, see if you can make that non-static member as static or create an instance of the class first and then access the non-static member by using the newly created instance.

Main method interview questions

Some of the most commonly asked interview questions regarding main method in Java are:

1) Why is main method static in Java?

2) How can make a java application to execute without using main method?

Introduction
The main method is the starting point of any Java application. When starting the program, this method is invoked by the JVM after loading the class into memory.
The main method should have the following syntax:
public static void main(String args)
static public void main(String str)
Thus we see that...

<h2>Introduction</h2>
The main method is the starting point of any Java application. When starting the program, this method is invoked by the JVM after <a href="http://www.javaexperience.com/java-class-loading/">loading the class into memory</a>.
The main method should have the following syntax:
<blockquote>public static void main(String args[])</blockquote>
In this tutorial, we shall cover the following topics:
<div id="toc">
1. <a href="#mainspecifier">main Method Specifiers</a>
2. <a href="#imppoints">Important points about main method</a>
3. <a href="#mainsign">main method signatures</a>
4. <a href="#maincommandline">Accessing Command Line Arguments</a>
5. <a href="#varargs">Variable arguments</a>
6. <a href="#strictfp">strictfp with main</a>
7. <a href="#troubleshooting">Troubleshooting</a>
8. <a href="#interviewques">Main method interview questions</a>
9. <a href="#references">References</a>
</div>
<a name="mainspecifier"></a>
<h2>main Method Specifiers</h2>
Let us understand the need of various keywords in the signature of main method:
<strong>public:</strong> The method has to be public so that it is visible outside of its package to the JVM. If main method is not public, JVM won't be able to invoke it.
<strong>static:</strong> JVM doesn’t create any instance before calling the main method. Actually, JVM need not create an instance to call main method because it won't know which constructor to invoke in case of <a href="http://www.javaexperience.com/this-and-super-in-java/" title="this and super keywords">overloaded constructors</a> and what value to pass if the constructor accepts arguments. This means that the main method has to be static.
<strong>void:</strong> JVM doesn't expect main method to return anything. Hence the keyword void is used.
<strong>main:</strong> main is the method name looked for by JVM.
<strong>args:</strong> This string array is used as the argument to main method. The purpose of this argument is to capture the command line inputs given while starting the program.
<a name="imppoints"></a>
<h2>Important points about main method</h2>
a) The point to note here is that if one omits static or changes the method access specifier or specifies a return type for the above method, it doesn’t become an invalid method to JVM but it becomes just another method.
b) It is not the main word but all the above specifiers which make main as the starting point.
c) There could be multiple classes in an application having the main method. If this is so, Eclipse will ask for which main method to invoke.
d) We cal also specify main-class in the META-INF folder of a <a href="http://www.javaexperience.com/what-is-the-difference-between-jarwar-and-ear-files/" title="What is the difference between JAR,WAR and EAR files">JAR/WAR</a>. This information is then used to identify main method when multiple classes are defining it.
e) The name of argument args for the main method is just a preference and can be renamed to myarg, mainArgument or mainMethod etc.
<a name="mainsign"></a>
<h2>main method signatures</h2>
Let us now look at some valid and in-valid signatures for the main method in a class.
<h3>Valid main signatures</h3>
<blockquote> public static void main(String args[])
static public void main(String[] args)
public static void main(String[] str)</blockquote>
Thus we see that shuffling the specifiers doesn't make any difference. Hence the point is that public, static, void, main should be present in any order.
The argument name "args" is normally used for main method. But we can use any other name as shown in 3rd signature above.
<h3>In-valid main signatures</h3>
<blockquote>
public void main(String[] args) (Removal of static keyword).
public static int main(String[] args) (specify a return type of int. The return type has to be void).
private static void main(String[] args) (Change in method access specifier. The <a href="http://www.javaexperience.com/java-access-modifier-tutorial-defaultprivatepublicprotected/" title="Java Access Modifier tutorial – Default,Private,Public,Protected">access specifier</a> should be private).
public static void main123(String[] args) (Change in method name from main to main123).
public static void main(String args) (Change in method argument from String array to String).</blockquote>
All of the above have in-valid signature because they are not adhering to the main method specification.
If a class does not have starter main method then an error as NoSuchMethodError is thrown by JVM.
<a name="maincommandline"></a>
<h2>Accessing Command Line Arguments</h2>
The following program shows how to access the command line arguments:
1
If we invoke the above method as:
<blockquote>java Example welcome here</blockquote>
The output shall be:
<blockquote>First argument = welcome Second argument = here</blockquote>
As you can see that arg[0] refers to "welcome" and not "Example". The program name is not part of the arguments array. Moreover, if no argument is passed and still we try accessing arg[0], we shall get ArrayIndexOutofBoundsException.
<a name="varargs"></a>
<h2>Variable Arguments</h2>
As noted above, the main method accepts a String array as the only argument. In Java, we can make a method accept <a href="http://www.javaexperience.com/java-varargs-or-variable-arguments/" title="Java Varargs or Variable Arguments">variable number of arguments</a> by using ellipses (...). Internally the variable number of arguments to a method is handled by using arrays. This means that there is a direct co-ordination between the string array and varargs for the main method. A valid main method signature when using varargs feature is:
public static void main(String... args)
If you de-compile and see the code for the above main method signature then it will be same as when using:
public static void main(String[] args)
<a name="strictfp"></a>
<h2>strictfp with main method</h2>
Apart from using public, static and void keywords with the main method, we can use the synchronized and strictfp keywords too. Though an in depth discussion of strictfp keyword will not be meaningful here but to get an overview of strictfp keyword, read the following:
The strictfp keyword is used for achieving reproducible results for floating point computations. By default, the JVM is allowed to use high precision computations before truncating the result to 64 bits. This means that if a processor has 80 bit and other has 90 bit registers then running the same program on these processors could result in different results. However if you want to get the same result for every time for the same operation then better use the strictfp keyword. Note that strictfp keyword can be used with method or class (making all method of the class as strictfp).
<a name="troubleshooting"></a>
<h2>Troubleshooting Tips</h2>
When writing a Java application with main method, the following are some of the issues faced by beginners:
<ul>
<li><strong>main method not found:</strong> If you are trying to run a Java application from within Eclipse IDE and getting an error that no main method was found then check the problems view to see if there were any build path related errors. Always remember that a program can be run only after it has been compiled. If there are build path errors in your project, Eclipse won't compile the code and hence you won't be able to run the project as Java application.</li>
<li><strong>Can't refer non-static members:</strong> The non-static members of a class are associated with instances and not to class as a whole. Thus if you try to refer non-static members from the main method, there is no way for JVM to find out which copy of non-static member you want to refer too as there could be 10 instances already created for that class. To resolve this problem, see if you can make that non-static member as static or create an instance of the class first and then access the non-static member by using the newly created instance.</li>
</ul>
<a name="interviewques"></a>
<h2>Main method interview questions</h2>
Some of the most commonly asked interview questions regarding main method in Java are:
<ul>
<li>1) Why is main method static in Java?</li>
<li>2) How can make a java application to execute without using main method?</li>
<li>3) What will happen if we make main method as synchronized?</li>
<li>4) Can I throw an exception from main method? Who will catch it?</li>
<li>5) Can I invoke the proper main method from rest of my code?</li>
</ul>
<a name="references"></a>
<h2>References</h2>
1. <a href="http://stackoverflow.com/questions/146576/why-is-the-java-main-method-static" target="_blank">Why is the Java main method static</a>
2. <a href="http://csis.pace.edu/~bergin/KarelJava2ed/ch2/javamain.html" target="_blank">The Java Main Method</a>
3. <a href="http://en.wikipedia.org/wiki/Main_function" target="_blank">Main function - Wikipedia</a>

adminhttps://plus.google.com/108156674671499593770/posts[email protected]AdministratorI run this blog with lots of passion. In this website, you will find tutorials on Core Java, Spring, Struts, Web Applications, Portals and Database.
Please support me and the website by sharing the posts on your facebook / twitter. You can tap the share button at the top of each post.
Thanks for the support.Java Experience

I run this blog with lots of passion. In this website, you will find tutorials on Core Java, Spring, Struts, Web Applications, Portals and Database.
Please support me and the website by sharing the posts on your facebook / twitter. You can tap the share button at the top of each post.
Thanks for the support.