Monday, December 19, 2011

Why main method is public static in Java

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 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 main method but in Java main method is slightly different it doesn't return any value like in C it returns int, main method is public static and void Why? In this post we will try to find answer of these questions and have an idea of one of the most popular questions in Java why main method is declared Static.

What is main method in Java?

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

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

public static void main(String args[])

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

public static void main(String... args)

Remember varargs version of java main method will only work in Java 1.5 or later version. Apart from public, static and void there are certain keywords like final, synchronized and strictfp which are permitted in signature of java main method.

Why main method is static in Java

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

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

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

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

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

Why main method is void in Java
Since main method in Java is not supposed to return any value, its made void which simply means main is not returning anything.

1. 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 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. Main method is entry point for any Core Java program. Execution starts from main method.

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

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

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

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

Some tutorials you may like


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

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 khwaja 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 ?

iTfinGer Ode 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.

neha shirlekar said...

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

Sasmita Nayak said...

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

Docket Smart 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();

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

Your articles are really helpful......keep adding more to this site :)

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.

Post a Comment