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 :

Neeraj said...

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.

extremejava said...

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

Anonymous said...

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)

Ashutosh Agarwal said...

@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).

Farhan said...

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.

Anonymous said...

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

Unknown said...

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

Anonymous said...

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

Radhika said...

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 ?

Anonymous said...

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"

Dimistri said...

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.

Peter said...

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.

Aster said...

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.

javin paul said...

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.

Anonymous said...

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.

Unknown said...

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

Unknown said...

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

Unknown said...

This is really helpful for a beginner. Thanks

Anonymous said...

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

Anonymous said...

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"

Anonymous said...

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

Anonymous said...

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");
}
}

Moaz Amin said...

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

Omkar said...

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.

Anonymous said...

why main has to be void?

Anonymous said...

@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.

hackermanid said...

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

Unknown said...

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.

Ellen Dares said...

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/

Post a Comment