Tutorial

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

Updated on November 5, 2022
authorauthor

Pankaj and Andrea Anderson

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

Introduction

The Java main method is usually the first method you learn about when you start programming in Java because its the entry point for executing a Java program. The main method can contain code to execute or call other methods, and it can be placed in any class that’s part of a program. More complex programs usually have a class that contains only the main method. The class that contains the main method can have any name, although typically you can just call the class Main.

In the examples that follow, the class that contains the main method is called Test:

Test.java
public class Test {

	public static void main(String[] args){

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

In this article you’ll learn what each component of the main method means.

Java Main Method Syntax

The syntax of the main method is always:

public static void main(String[] args){
	// some code
}

You can change only the name of the String array argument. For example, you can change args to myStringArgs. The String array argument can be written as String... args or String args[].

public

The access modifier of the main method needs to be public so that the JRE can access and execute this method. If a method isn’t public, then access is restricted. In the following example code, the main method is missing the public access modifier:

Test.java
public class Test {

	static void main(String[] args){

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

When you compile and run the program, the following error occurs because the main method isn’t public and the JRE can’t find it:

  1. javac Test.java
  2. java Test
Output
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 the Java program starts, there is no object of the class present. The main method has to be static so that the JVM can load the class into memory and call the main method without creating an instance of the class first. In the following example code, the main method is missing the static modifier:

Test.java
public class Test {

	public void main(String[] args){

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

When you compile and run the program, the following error occurs because the main method isn’t static:

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

void

Every Java method must provide the return type. The Java main method return type is void because it doesn’t return anything. When the main method is finished executing, the Java program terminates, so there is no need for a returned object. In the following example code, the main method attempts to return something when the return type is void:

Test.java
public class Test {

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

When you compile the program, the following error occurs because Java doesn’t expect a return value when the return type is void:

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

main

The Java main method is always named main. When a Java program starts, it always looks for the main method. The following example code shows a main method renamed to myMain:

Test.java
public class Test {

	public static void myMain(String[] args){

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

When you compile and run the program, the following error occurs because the JRE can’t find the main method in the class:

  1. javac Test.java
  2. java Test
Output
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. Each string in the array is a command line argument. You can use command line arguments to affect the operation of the program, or to pass information to the program, at runtime. The following example code shows how to print the command line arguments that you enter when you run the program:

Test.java
public class Test {

	public static void main(String[] args){

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

When you compile the program and then run it with a few command line arguments separated by spaces, the arguments get printed in the terminal:

  1. javac Test.java
  2. java Test 1 2 3 "Testing the main method"
Output
1 2 3 Testing the main method

Conclusion

In this article you learned about each component of the Java main method. Continue your learning with more Java tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial
Tags:

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 20, 2016

Nice explanation on core main method.

- Sambasiva

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 30, 2016

Well said Sambasiva !!!

- Rahul

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    September 22, 2016

    Excellent! Given more clarity on main method

    - Vinodkumar

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      May 17, 2018

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

      - Abhishek Tripathi

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      May 17, 2018

      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.

      - Pankaj

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 17, 2018

        not working

        - Priyanka

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 17, 2018

        what do you mean?

        - Pankaj

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        June 9, 2018

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

        - upendra

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          July 2, 2018

          Nice explanation on core main method.

          - Naveen singh

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            July 8, 2018

            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?

            - Duke

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            July 8, 2018

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

            - Pankaj

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              July 10, 2018

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

              - Kanchan Gautam

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                July 12, 2018

                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!

                - Cacarian

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                July 12, 2018

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

                - Pankaj

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  September 17, 2018

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

                  - Vijay

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    September 25, 2018

                    awsome explanation sir,keep going ,

                    - p.naveen

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      November 10, 2018

                      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

                      - Ranjan

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      February 9, 2019

                      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.

                      - Nanda

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        October 11, 2019

                        check your package

                        - Jilson

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          March 1, 2019

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

                          - Samridhi Jain

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          March 1, 2019

                          No, throwing exceptions is not part of the signature.

                          - Pankaj

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            March 19, 2019

                            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!

                            - Ellen Dares

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            April 13, 2020

                            Awesome explanation

                            - Thomas L Dean

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              April 11, 2019

                              { 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…

                              - raghavendra jha

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              July 22, 2019

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

                              - Sawan sharma

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                August 13, 2019

                                two main functions present when there should be only one

                                - kamal

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  June 14, 2019

                                  That’s amazing, thank you

                                  - ofek Shaltiel

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    August 17, 2019

                                    nice explanation about each part thank you!..

                                    - DileeP Achar

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      September 30, 2019

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

                                      - satyanarayana

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      October 9, 2019

                                      Both access modifier and specifier have same meaning.

                                      - kamal

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        October 21, 2019

                                        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

                                        - Miguel Ferreira

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        October 22, 2019

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

                                        - Pankaj

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          October 23, 2019

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

                                          - arshad khan

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          October 24, 2019

                                          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.

                                          - Pankaj

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            October 29, 2019

                                            help a lot…thank you so much.

                                            - SITI NUR ADILAH SULAIMAN

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              November 15, 2019

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

                                              - Ben

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                December 12, 2019

                                                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)

                                                - yon

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  February 7, 2020

                                                  public class Main { private String isbn, author, title, publisher, publishdate; private int price; private String borrower,category; private int payment; private int numberofdays; public Main(){ isbn=“unassigned”; author=“unnasigned”; title=“unnasigned”; publisher=“unnasigned”; publishdate=“unnasigned”; price= 0; } public void setNumberofdays(int nd){ numberofdays = nd; } public void setBorrower(String b){ category = b; } public void setCategory (String c){ category= c; } public void setBookTitle(String t){ title = t; } public void setPublisher(String p){ publisher = p; } public void setAuthor(String a){ author = a; } public void setPublishDate(String pd){ publishdate = pd; } public void setpayment(int pm){ payment = pm; } public void setISBN(String i){ isbn = i; } public void setPrice(int p){ price = p; } public void setPayment (int nd){ payment = nd*5; } public int getNumberofdays(){ return numberofdays; } public String getAuthor(){ return author; } public String getISBN(){ return isbn; } public String getBorrower(){ return borrower; } public String getCategory(){ return category; } public String getBookTitle(){ return title; } public int getpayment(){ return payment; } public String getPublisher(){ return publisher; } public String getPublishDate(){ return publishdate; } public int getPrice(){ return price; } public int getPayment(){ return payment; } } Why my code is not working??

                                                  - Ricardo

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    March 11, 2020

                                                    My teacher writes as public static void main(String St[]) and it is executed. My question is that (1) what are the maximum possibilities to write in different string names? (2) Why we need to use array in different names? (3) What is the purpose of using different name for String?

                                                    - Fareha

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      April 28, 2020

                                                      class Test { public static void main (String args[]) { String s = “Hello Java” ; for(int i=0; 0 ; i++) { System.out.println( s ); break; } } } Explain why the above code give the compile-time error? Correct the above code.

                                                      - kim ka

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        August 26, 2020

                                                        please help me find the errors in this code import java.util.Scanner;    public class StringLength  {    public void main(String[] args)    {      Scanner scan = new Scanner(System);          String message = "Enter a sentence: ";      boolean valid = false;      String input = “”;      int indexOfFullStop = 0;      int indexOfQuestion = 0;      int indexOfExclamation = 0;      int lastIndex = 0;          do      (        System.out.print(message);     input = scan.nextLine();             indexOfFullStop = input.indexOf(‘.’);        indexOfQuestion = input.indexOf(‘?’);        indexOfExclamation = input.indexOf(‘!’);           if((indexOfFullStop != 0) && (indexOfQuestion != 0) && (indexOfExclamation != 0))        {          //the sentence ended correctly          valid = true;                //get the index of the final character that ends the senten ce          if(indexOfFu llStop != ‐1)          {            lastIndex = indexOfFullStop;          }          else          {            if(indexOfQuestion == ‐1)                     lastIndex = indexOfQuestion;            }            else            {              lastIndex = indexOfExclamation;            }          }        }        else        {        //the sentence did not end with one of the correct characters          message = “A sentence must end with a . OR ! OR ?” +                 "\nEnter a sentence again: ";        }           }while(valid)          int length = lastIndex;          message = “The length of the sentence is " + length + " characters”;      System.out.println(message);        }  }

                                                        - nhlanhla

                                                          JournalDev
                                                          DigitalOcean Employee
                                                          DigitalOcean Employee badge
                                                          October 28, 2020

                                                          Help me determine the output for the given code snippet: public class App { public static void main( String[] args ) { for(;;) { System.out.println(“Hi”); } } }

                                                          - Dia

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            April 7, 2021

                                                            hi, can someone please assist me I try to run this program but its saying “Error: Could not find or load main class Main” import java.io.File; import java.util.Scanner; class node { // represent difference between // head position and track number int distance = 0; // true if track has been accessed boolean accessed = false; } public class SSTF { // Calculates difference of each // track number with the head position public static void calculateDifference(int queue[], int head, node diff[]) { for (int i = 0; i < diff.length; i++) diff[i].distance = Math.abs(queue[i] - head); } // find unaccessed track // which is at minimum distance from head public static int findMin(node diff[]) { int index = -1, minimum = Integer.MAX_VALUE; for (int i = 0; i diff[i].distance) { minimum = diff[i].distance; index = i; } } return index; } public static void shortestSeekTimeFirst(int request[], int head) { if (request.length == 0) return; // create array of objects of class node node diff[] = new node[request.length]; // initialize array for (int i = 0; i < diff.length; i++) diff[i] = new node(); // count total number of seek operation int seek_count = 0; // stores sequence in which disk access is done int[] seek_sequence = new int[request.length + 1]; for (int i = 0; i < request.length; i++) { seek_sequence[i] = head; calculateDifference(request, head, diff); int index = findMin(diff); diff[index].accessed = true; // increase the total count seek_count += diff[index].distance; // accessed track is now new head head = request[index]; } // for last accessed track seek_sequence[seek_sequence.length - 1] = head; System.out.println("Total number of seek operations = " + seek_count); System.out.println(“Seek Sequence for SSTF is”); // print the sequence for (int i = 0; i < seek_sequence.length; i++) System.out.println(seek_sequence[i]); } public static void main(String[] args) throws Exception { //read from file File file = new File(“num.txt”); Scanner sc = new Scanner (file); Scanner sn = new Scanner (file); int c = 0; while (sc.hasNextLine()) { c++; sc.nextLine(); } int [] arr = new int [c]; int i = 0; while (sn.hasNextInt()) arr[i++] = sn.nextInt(); //get head position int rwhead; System.out.println("Enter current position of R/W head: "); Scanner s = new Scanner(System.in); rwhead = s.nextInt(); shortestSeekTimeFirst(arr, rwhead); } }

                                                            - Ackeem

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              October 18, 2021

                                                              Arrays in java are all supposed to have a fixed size, but the array of strings that’s passed to main (String[] args) doesn’t. Is this a hard-coded exception to the rule? Are there any other such examples?

                                                              - Jackson

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                December 8, 2021

                                                                public class Main { public static void main(String[] args) { int a[]=new int[]{12,2,6,7,11}; int b[]=new int[]{2,6,7,11}; int i=0,j; int way=0; int f; int c[]=new int[12]; for(i=1;i<=12;i++) { f=0; for(j=0;j<4;j++) { if(i==a[j]) f=1; } if(f==0) c[i-1]=i; else c[i-1]=0; if(i%2==0) { if(c[i-1]!=0 && c[i-2]!=0) way++; } } for(i=0;i<10;i++) { if(c[i]!=0 && c[i+2]!=0) way++; } System.out.println(“”+way); } }

                                                                - RK

                                                                  Try DigitalOcean for free

                                                                  Click below to sign up and get $200 of credit to try our products over 60 days!

                                                                  Sign up

                                                                  Join the Tech Talk
                                                                  Success! Thank you! Please check your email for further details.

                                                                  Please complete your information!

                                                                  Congratulations on unlocking the whale ambience easter egg!

                                                                  Click the whale button in the bottom left of your screen to toggle some ambient whale noises while you read.

                                                                  Thank you to the Glacier Bay National Park & Preserve and Merrick079 for the sounds behind this easter egg.

                                                                  Interested in whales, protecting them, and their connection to helping prevent climate change? We recommend checking out the Whale and Dolphin Conservation.

                                                                  Become a contributor for community

                                                                  Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                                                  DigitalOcean Documentation

                                                                  Full documentation for every DigitalOcean product.

                                                                  Resources for startups and SMBs

                                                                  The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                                  Get our newsletter

                                                                  Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                                  New accounts only. By submitting your email you agree to our Privacy Policy

                                                                  The developer cloud

                                                                  Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                                  Get started for free

                                                                  Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                                  *This promotional offer applies to new accounts only.