Java main method types

Java main() method explained with examples

In this article, we will learn Java main() method in detail. As the name suggest this is the main point of the program, without the main() method the program won’t execute.

What is a main() method in Java?

The main() method is the starting point of the program. JVM starts the execution of program starting from the main() method.

Syntax of main() method:

public static void main(String args[])

public: We have already learned in the access specifier tutorial that public access specifier allows the access of the method outside the program, since we want the JVM to identify the main method and start the execution from it, we want it to be marked “public”. If we use other access modifier like private, default or protected, the JVM wouldn’t recognise the main() method and the program won’t start the execution.

static: The reason the main() method is marked static so that it can be invoked by JVM without the need of creating an object. In order to invoke the normal method, we need to create the object first. However, to invoke the static method we don’t need an object. Learn more about static method here.

Читайте также:  No borders html code

void: This is the return type. The void means that the main() method will not return anything.

main(): This the default signature which is predefined by JVM. When we try to execute a program, the JVM first identifies the main() method and starts the execution from it. As stated above, the name of this method suggests that it is the “main” part of the program.

String args[]: The main method can also accepts string inputs that can be provided at the runtime. These string inputs are also known as command line arguments. These strings inputs are stored in the array args[] of String type.

Can we have main() method defined without String args[] parameter?

If we have a main() method without String args[] in a program, the program will throw no compilation error however we won’t be able to run the program as the JVM looks for the public main method with the String args[] parameter and if it doesn’t find such method, it doesn’t run the program.

Error: Main method not found in class JavaExample, please define the main method as: public static void main(String[] args)

As you can see that the program threw error at runtime.

Java – static block vs main method

As we learned in the previous article, static block is used to initialise the static data members. Let’s run a program with static block and main method (static method) to see in which order they run.

class JavaExample < //static block static < System.out.println("Static Block"); >//static method public static void main(String args[]) < System.out.println("Main Method"); >>

As we can see, the static block executed before the main method.

What if a program doesn’t have a main method?

Let’s write a program without the main method to see whether it runs or not.

Error: Main method not found in class JavaExample, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application

Different ways to write main method in java

The following are the valid ways to write a main method in java:

public static void main(String[] args) //We can interchange static and public static public void main(String[] args) //We can place the square brackets at the different locations public static void main(String[] args) public static void main(String []args)

Overloading of main() method in Java

We can overload the main method in Java. This allows us to have more than one main() method in Java. However the signature of all the overloaded methods must be different. To learn more about overloading, refer this guide: Method overloading in Java.

class JavaExample < public static void main(String args[]) < System.out.println("main method"); main(100); main('A'); >//Overloaded int main method public static void main(int a) < System.out.println(a); >//Overloaded char main method public static void main(char ch) < System.out.println(ch); >>

Frequently Asked Questions

The main method is used to specify the starting point of the program. This is the starting point of our program from where the JVM starts execution of the program.

No, you can’t declare a method inside main() method.

Yes we have can more than one main methods in java, however JVM will always calls String[] argument main() method. Other main() methods will act as a Overloaded method. In order to invoke these overloaded methods, we have to call them explicitly.

No, we cannot override main method of java because it is a static method and we cannot override a static method. The static method in java is associated with class which is why we don’t need an object to call these. Therefore, it is not possible to override the main method in java.

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

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;amp;gt;GetStaticMethodID(env, mainClass, "main", "([Ljava/lang/String;)V"); . . /* Invoke main method. */ (*env)-&amp;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.

Источник

Оцените статью