public static void main(String[] args) – Java main method

Filed Under: Java

public static void main(String[] args) is the most important Java method. When you start learning java programming, this is the first method you encounter. Remember the first Java Hello World program you wrote that runs and prints “Hello World”?

public static void main(String[] args)

Java main method is the entry point of any java program. Its syntax is always public static void main(String[] args). You can only change the name of String array argument, for example you can change args to myStringArgs.

Also String array argument can be written as String... args or String args[].

public static void main string args, java main method

Let’s look at the java main method closely and try to understand each of its parts.

public

This is the access modifier of the main method. It has to be public so that java runtime can execute this method. Remember that if you make any method non-public then it’s not allowed to be executed by any program, there are some access restrictions applied. So it means that the main method has to be public. Let’s see what happens if we define the main method as non-public.


public class Test {

static void main(String[] args){

	System.out.println("Hello World");
	
}
}

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

static

When java runtime starts, there is no object of the class present. That’s why the main method has to be static so that JVM can load the class into memory and call the main method. If the main method won’t be static, JVM would not be able to call it because there is no object of the class is present. Let’s see what happens when we remove static from java main method.


public class Test {

public void main(String[] args){

	System.out.println("Hello World");
	
}
}

$ javac Test.java 
$ java Test
Error: Main method is not static in class Test, please define the main method as:
   public static void main(String[] args)
$

void

Java programming mandates that every method provide the return type. Java main method doesn’t return anything, that’s why it’s return type is void. This has been done to keep things simple because once the main method is finished executing, java program terminates. So there is no point in returning anything, there is nothing that can be done for the returned object by JVM. If we try to return something from the main method, it will give compilation error as an unexpected return value. For example, if we have the main method like below.


public class Test {

public static void main(String[] args){
	
	return 0;
}
}

We get below error when above program is compiled.


$ javac Test.java 
Test.java:5: error: incompatible types: unexpected return value
	return 0;
	       ^
1 error
$

main

This is the name of java main method. It’s fixed and when we start a java program, it looks for the main method. For example, if we have a class like below.


public class Test {

public static void mymain(String[] args){

	System.out.println("Hello World");
}
}

And we try to run this program, it will throw an error that the main method is not found.


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

String[] args

Java main method accepts a single argument of type String array. This is also called as java command line arguments. Let’s have a look at the example of using java command line arguments.


public class Test {

public static void main(String[] args){

    for(String s : args){
	System.out.println(s);
    }
	
    }
}

Above is a simple program where we are printing the command line arguments. Let’s see how to pass command line arguments when executing above program.


$ javac Test.java 
$ java Test 1 2 3
1
2
3
$ java Test "Hello World" "Pankaj Kumar"
Hello World
Pankaj Kumar
$ java Test
$ 

Java main method command line arguments in Eclipse

Below images show how to pass command line arguments when you are executing a java program in Eclipse.

java main method eclipse run configurations

java main method command line arguments eclipse

java main method executing eclipse

That’s all for public static void main(String[] args), java main method.

Comments

  1. yon says:

    are these correct?
    public static main(String[ ] args)

    public static void[ ] main(String[ ] args)

    public int static main(String[ ] args)

    public static void mian (String args)

    1. Pankaj says:

      public static main(String[ ] args) – invalid, return type is missing.

      public static void[ ] main(String[ ] args) – invalid, void[] is an invalid return type.

      public int static main(String[ ] args) – invalid, static should come before return type. “public static int main(String[ ] args)” is fine, although it’s not a java main method.

      public static void mian (String args) – valid method but it’s not a java main method.

  2. Ben says:

    I was trying to run this program so that class Lion and class Dog can extend Class Animal to override animalSound and return “Roar” and “Woof”, no compilation error and no output.
    Help

    public abstract class Animal{
    public abstract void animalSound();
    public static void main(String args[]){

    class Lion extends Animal{

    @Override
    public void animalSound(){
    System.out.println(“Roar”);
    Lion obj = new Lion();
    obj.animalSound();
    }
    }
    class Dog extends Animal{

    @Override
    public void animalSound(){
    System.out.println(“Woof”);
    Dog obj = new Dog();
    obj.animalSound();
    }
    }
    }
    }

  3. SITI NUR ADILAH SULAIMAN says:

    help a lot..thank you so much.

  4. arshad khan says:

    Hello Sir,

    I have a query about 2 main method in java?

    I was written 2 main method in single main class,But i am not getting 2 output like(Show screen,sucess shows). you can see the program below?
    ———————————————————————————
    class Module{

    public void Dress() {

    System.out.println(“Shows Screen”);
    }
    }

    public class JavaObject3 {

    public static void main(String[] args1) {

    Module m=new Module();

    m.Dress();
    }

    public static void main1(int args) {

    JavaObject3 obj1=new JavaObject3();

    System.out.println(“sucess shows”);
    }

    }

    1. Pankaj says:

      When you execute a java class, method with the signature public static void main(String[] args) gets executed. The other method is just having a name as “main” and it’s overloading the main method but it won’t get executed unless you call it explicitly.

  5. Miguel Ferreira says:

    Why do you sometime type: public static void mymain(String args[ ])
    and other times: public static void mymain(String [ ] args) ?
    What is the correct sintax?

    Thanks,
    Miguel Ferreira

    1. Pankaj says:

      Both syntaxes are correct. But the recommended and conventional one is String [ ] args.

  6. satyanarayana says:

    public is access specifier or access modifier . i think it is access specifier but in the explanation you given it as access modifier.

    1. kamal says:

      Both access modifier and specifier have same meaning.

  7. DileeP Achar says:

    nice explanation about each part thank you!……..

  8. ofek Shaltiel says:

    That’s amazing, thank you

  9. raghavendra jha says:

    {
    public static void main(int[] args)
    {
    System.out.println(“this is the overload of the method”);
    }
    public static void main(String[] args)
    {
    System.out.println(“this isn working anymore”);
    }
    output-this isn working anymore
    can you explain me why this output will be show….

    1. Sawan sharma says:

      “this isn working anymore”- this output came bacause JVM never accepts the int[] args in main method.
      When you run a java program then JVM will search for main method in the class with String []args if it not present then it will not print anything. it will give an error like ” Main method not found”.

    2. kamal says:

      two main functions present when there should be only one

  10. Ellen Dares says:

    Hi, Great article, I will share my thoughts.

    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!

  11. Samridhi Jain says:

    What about adding throws Exception() in the definition, doesn’t it change the signature of the function?

    1. Pankaj says:

      No, throwing exceptions is not part of the signature.

      1. Julie says:

        /*My program below is returning “Solution.java:44: error: method main(String[]) is already defined in class Solution
        public static void main(String[] args) { */
        //I can’t get to understand why though am new to programming//

        import java.io.*;
        import java.math.*;
        import java.security.*;
        import java.text.*;
        import java.util.*;
        import java.util.concurrent.*;
        import java.util.regex.*;
        public class Solution
        {
        public static void main(String args[])
        {
        Scanner scan = new Scanner(System.in);
        int n =scan.nextInt();
        scan.close();
        String result =””;
        if (n100){
        result=””;
        }
        else{
        if(n%2==1){
        result = “Weird”;
        }
        else{
        if(n>=2 && n>=5){
        result =”Not Weird”;
        }
        else{
        if(n>=6 && n<=20){
        result ="Weird";
        }
        else{
        result ="Not Weird";
        }
        System.out.println(result);
        }
        }
        }
        }

        private static final Scanner scanner = new Scanner(System.in);

        public static void main(String[] args) {
        int N = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        scanner.close();
        }
        }

  12. Ranjan says:

    Sir i am new to java . I have compiled and run about 30 java programe but now in a specific folder java programe comiled but wont run showing error main method not found even i have main method psvm(S[] args).but when i run same programe in other folder it runs .why that only folder its not running .pls help me

    1. Nanda says:

      can any one suggest me how to study or how to understand threads in java,,, because i studied so many times ,
      but i’m unable to get the clarity about the concept and coding.

    2. Jilson says:

      check your package

  13. p.naveen says:

    awsome explanation sir,keep going ,,,,,,

  14. Vijay says:

    Very Nice explanation about java main method…each part…….Great

  15. Cacarian says:

    I think there is a small mistake in saying “Java programming mandates that every method signature provide the return type. “. Return type is not part of the method signature. Nice explanation though!

    1. Pankaj says:

      Thanks for noticing the typo. Java programming mandates to have a return type, but yes it’s not part of the method signature.

  16. Kanchan Gautam says:

    Sir I still haven’t understood the significance of String [] args. Please explain.

  17. Duke says:

    Can you explain as to why do we need to have a String args[] array passed to main? Why does it not compile if we do not pass a String args[] array? Why does Java need a String args[] array?

    1. Pankaj says:

      It’s the syntax and to pass command line arguments to the main method.

  18. Naveen singh says:

    Nice explanation on core main method.

  19. Priyanka says:

    not working

    1. Pankaj says:

      what do you mean?

      1. upendra says:

        //run this code and see the same error at run time. your idea fails
        public class aggregation
        {
        String name;
        int roll;
        String bg;
        int marks;
        aggregation(String name, int roll, String bg, int marks)
        {
        this.name=name;
        this.roll=roll;
        this.bg=bg;
        this.marks=marks;
        }}
        class students
        {
        int salary;
        String gender;
        aggregation info;
        students(int salary, String gender, aggregation info)
        {
        this.salary=salary;
        this.gender=gender;
        this.info=info;
        }
        public static void main(String[] args)
        {
        aggregation a1=new aggregation(“Upendra Dhamala”, 48, “B+”,98);
        students a2=new students(90000, “M”, a1);
        System.out.println(a2.salary);
        System.out.println(a2.gender);
        System.out.println(a2.info.name);
        System.out.println(a2.info.roll);
        System.out.println(a2.info.bg);
        System.out.println(a2.info.marks);

        }
        }

        1. Raj says:

          //Very vague response. Try to avoid saying things like your idea fails. Made minor changes. Changed the first letter of the class to uppercase, but you might not have to.

          package raj.basic.test;

          public class Aggregation
          {
          String name;
          int roll;
          String bg;
          int marks;
          Aggregation(){};
          Aggregation(String name, int roll, String bg, int marks)
          {
          this.name=name;
          this.roll=roll;
          this.bg=bg;
          this.marks=marks;
          }
          }
          class Students
          {
          int salary;
          String gender;
          Aggregation info;
          Students(int salary, String gender, Aggregation info)
          {
          this.salary=salary;
          this.gender=gender;
          this.info=info;
          }
          public static void main(String[] args)
          {
          Aggregation a1=new Aggregation(“Upendra Dhamala”, 48, “B+”,98);
          Students a2=new Students(90000, “M”, a1);
          System.out.println(a2.salary);
          System.out.println(a2.gender);
          System.out.println(a2.info.name);
          System.out.println(a2.info.roll);
          System.out.println(a2.info.bg);
          System.out.println(a2.info.marks);
          }

          }

          //Output is as follows
          /*
          90000
          M
          Upendra Dhamala
          48
          B+
          98
          */

  20. Abhishek Tripathi says:

    Sir I want to implement push notifications like your site. My website is built on spring and jsp. Please help me out of this.

    1. Pankaj says:

      I am using OneSignal push notification and they have a WordPress plugin, they also have Java API. Please look into their documentation for implementing it. You can also look at some other services for push notification.

  21. Vinodkumar says:

    Excellent! Given more clarity on main method

  22. Sambasiva says:

    Nice explanation on core main method.

    1. Rahul says:

      Well said Sambasiva !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages