Report this

What is the reason for this report?

Understanding public static void main(String[] args) in Java

Updated on June 26, 2025
Understanding public static void main(String[] args) in Java

Introduction

For every Java developer, from the absolute beginner to the seasoned professional, the Java main method is the universal starting line. It serves as the entry point for any standalone application, the exact location where the Java Virtual Machine (JVM) begins execution. Understanding its signature, public static void main(String[] args), is the first step towards building runnable Java programs.

This article will be your definitive resource for the main method. We will deconstruct each keyword (public, static, void), explore how to handle command-line arguments effectively, and explain exactly why this signature is so strict. You’ll also learn to navigate common errors, apply professional best practices, and explore advanced concepts that will elevate your code.

Whether you’re troubleshooting a Main method not found error or aiming to write cleaner, more maintainable applications, this article has you covered.

Key Takeaways

  • The public static void main(String[] args) signature is the mandatory, unchangeable entry point the Java Virtual Machine (JVM) requires to execute a standalone application.
  • The static modifier is required so the JVM can invoke the main method on the class itself, before any object instances have been created.
  • The public access modifier ensures the main method is visible and accessible to the external JVM process that initiates program execution.
  • The String[] args parameter serves as the mechanism to receive command-line arguments, allowing external data to be passed into the program at runtime.
  • To prevent common runtime errors, always validate the number of arguments using args.length before accessing array elements.
  • For maintainable code, the main method should act as a coordinator that delegates complex logic to other methods or objects rather than containing it directly.
  • Minor flexibility is permitted in the signature, such as changing the parameter name args or swapping the order of the public and static modifiers.
  • While mandatory for standalone programs, the main method is not the entry point in container-managed environments like web or Android applications.

Java main Method Syntax

The Java main method is 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!");

    }
}

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

Why the main Method Signature Must Be Exact

The Java Virtual Machine (JVM) operates on a strict, standardized protocol to launch applications, ensuring consistent behavior across all platforms. This protocol requires a predefined entry point, and the JVM is specifically programmed to look for a method with the exact signature: public static void main(String[] args).

The JVM’s process is not flexible; it performs a direct lookup for this signature and does not look for similar methods or attempt to infer the developer’s intended entry point. If this precise signature is absent, the program will fail to run. This rigid requirement is fundamental to Java’s architecture, guaranteeing that every application has a predictable and reliable starting point, which is essential for its portability.

What Happens When the main Method Signature is Altered?

When the public static void main(String[] args) signature is modified, the JVM can no longer recognize it as the application’s entry point. While your code might be syntactically correct and compile without issue, it will fail to run. This is because the JVM is not just looking for a method named main; it is looking for a method that perfectly matches every part of the required signature contract.

Let’s examine the specific consequences for each type of alteration.

  1. Missing the public Modifier: If you omit the public access modifier, the main method is no longer visible to the JVM from outside the class. The public modifier makes a method part of a class’s public interface, accessible by any external entity. Since the JVM is an external process that initiates your code, it needs public access to find and invoke the main method. Without it, the method is hidden from the JVM’s scope, and you will typically receive an error indicating the main method was not found or is not public.
  2. Missing the static Modifier: Omitting the static keyword makes the main method an instance method, which requires an object to be called upon. The JVM’s execution process begins by loading your class into memory, but it does not create an object of your class at startup. A non-static (instance) method can only be invoked on an object. Since no object exists, the JVM has no way to call a non-static main method. This is why the entry point must be static; it belongs to the class itself and can be called without an instance.
  3. Changing the void Return Type: In Java, a method’s signature includes its name and parameter types, but the return type is also part of the contract for invocation. The JVM is hard-coded to look for an entry point that returns void. By changing the return type from void to int, you have defined a completely different method. From the JVM’s perspective, the required main method that returns void is now missing entirely. Your code may compile, but the JVM will not find the specific signature it needs to start the program.
  4. Altering the Method Name or Parameter Type: Any change to the method’s name (e.g., Main) or its parameter type (e.g., String instead of String[]) also breaks the signature contract. The JVM is programmed to look for a method named exactly main (case-sensitive) that accepts exactly one parameter of type String[]. Any deviation creates a method that, while valid in other contexts, does not match the required entry point signature. The JVM will conclude that no main method exists and will terminate with an error.

Variations in the main Method Signature

While the core signature of the Java main method is standardized, certain elements offer flexibility without affecting the program’s execution. Understanding these variations is useful for reading different code styles and recognizing valid main method declarations.

Let’s look at some of the acceptable modifications to the main method signature.

1. The Parameter Name

The name of the String array parameter, conventionally args, is arbitrary. The Java compiler enforces the type of the parameter (String[]) and its position, but the identifier is chosen by the developer for use within the method body.

Standard Convention:

public static void main(String[] args) {
    // Standard 'args' parameter name
}

Valid Alternative:

public static void main(String[] commandLineArgs) {
    // The name has been changed, but the signature remains valid.
}

2. Parameter Syntax Variations

The String array parameter can be declared in three different ways, all of which are correctly interpreted by the JVM.

  • Standard Array Syntax (Recommended): The brackets [] are associated with the type String, indicating it is an array of strings.

    public static void main(String[] args) { /* ... */ }
    
  • Alternative Array Syntax: The brackets can also be placed after the parameter name, a syntax common in other languages like C++.

    public static void main(String args[]) { /* ... */ }
    
  • Varargs (Variable Arguments): The varargs syntax (...), introduced in Java 5, can be used. For the main method, this is functionally equivalent to the String[] array.

    public static void main(String... args) { /* ... */ }
    

Although all three are functional, String[] args is the canonical format and is strongly recommended by Java coding conventions for consistency and clarity.

3. The Order of Access Modifiers

The public and static modifiers are required, but their order is not strictly enforced by the Java compiler.

Standard Convention:

public static void main(String[] args) { /* ... */ }

Valid Alternative:

static public void main(String[] args) { /* ... */ }

Despite this flexibility, public static is the universally accepted convention. Adhering to this standard is a best practice that improves code readability and maintains consistency across projects.

How to Use Command-Line Arguments in Java

While knowing the theory behind public static void main(String[] args) is great, the real fun begins when you start making your programs interactive. The String[] args parameter lets you do just that, allowing you to pass in information from the command-line the moment you run your application.

Let’s look at a simple yet practical example to see how it works.

We’ll create a program that greets you by name. It’s a simple way to see the args array in action.

The code below takes the input you provide on the command line and uses it to print a friendly welcome message.

GreetUser.java
public class GreetUser {
    public static void main(String[] args) {
        // The first argument is at index 0 of the 'args' array.
        String userName = args[0];
        System.out.println("Hello, " + userName + "! Welcome to the program.");
    }
}

Let’s try it out!

First, compile the Java code:

  1. javac GreetUser.java

Now, run the program and pass your name right after the class name. Let’s use “Alice”.

  1. java GreetUser Alice

Output:

Hello, Alice! Welcome to the program.

Common Errors and Troubleshooting

When you’re starting out, it’s easy to make small typos or conceptual mistakes related to the main method. This troubleshooting guide covers the most common errors you’ll encounter, explains what they mean in simple terms, and shows you how to fix them.

1. Error: Main method not found in class...

This is the most frequent error a Java beginner will see. It’s the JVM’s way of saying, it couldn’t find the exact public static void main(String[] args) signature to start the program.

What it looks like:

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

Common Causes:

  • A Typo in the Name: The method name is misspelled (e.g., maim instead of main).
  • Incorrect Capitalization: The name is capitalized (e.g., Main instead of main). Java is case-sensitive.
  • Wrong Return Type: You have something other than void as the return type (e.g., public static int main(...)).
  • Incorrect Parameter Type: The parameter is not a String array (e.g., you have main(String arg) instead of main(String[] args)).

How to Fix It:

Carefully check your main method against the required signature. It must be: public static void main(String[] args)

2. Error: Main method is not static in class...

This is a more specific error that occurs when the JVM finds a main method with the correct name, but it’s missing the static keyword.

What it looks like:

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

Common Cause:

You have simply forgotten to include the static modifier in the method signature.

How to Fix It:

Add the static keyword between public and void. The main method must be static because the JVM needs to run it without creating an object of your class first.

3. Runtime Error: ArrayIndexOutOfBoundsException

This error doesn’t happen at launch, but rather during your program’s execution. It occurs when you try to access a command-line argument from the args array that doesn’t exist.

What it looks like:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
        at YourClassName.main(YourClassName.java:5)

Common Cause:

Your code attempts to use an argument (e.g., args[0]) but the user ran the program without providing any arguments on the command line.

How to Fix It:

Always check the length of the args array before trying to access its elements. This ensures your program can handle cases where the user doesn’t provide the expected input.

4. Compilation Error: incompatible types: unexpected return value

This error happens before you even run the program. It’s a compile-time error. It occurs if you try to return a value from the main method.

What it looks like:

YourClassName.java:5: error: incompatible types: unexpected return value
    return 0;
           ^

Common Cause:

The main method’s signature explicitly states that its return type is void, meaning it returns nothing. Your code includes a return statement that attempts to return a value (e.g., return 0;).

How to Fix It:

Remove the return value. The main method cannot return any data. If you need to terminate the program with a specific status code, use System.exit(0) instead.

Best Practices for the main Method

Following a few key practices when writing your main method can significantly improve your application’s quality, making it more readable, robust, and professional.

  1. Keep the main Method Lean: Treat the main method as a coordinator, not a worker. Its sole responsibility should be to parse any command-line arguments and delegate the actual work by creating objects and calling their methods. Avoid placing complex business logic inside main, as this improves readability, maintainability, and makes your code easier to test.

  2. Handle Command-Line Arguments Gracefully: Always validate command-line arguments before using them. Check args.length to ensure the user has provided the required input, and use try-catch blocks when parsing numbers. This prevents common runtime errors like ArrayIndexOutOfBoundsException and NumberFormatException and makes your application more robust and user-friendly.

  3. Use System.exit() for Clear Termination Status: Signal your program’s final outcome to the operating system using System.exit(). By convention, exit with System.exit(0) for a successful run and a non-zero number (like System.exit(1)) to indicate that an error occurred. This is crucial for scripting and automation, as it allows other tools to know if your program ran successfully.

  4. Use a Dedicated Entry-Point Class: For small, single-file programs, placing the main method in your primary class is fine. However, in larger applications, it’s a best practice to put the main method in its own dedicated class (e.g., Application.java or Main.java). This clearly separates the program’s starting point from its core logic, improving overall organization.

Frequently Asked Questions (FAQs)

1. What does public static void main mean in Java?

In Java, public static void main(String[] args) is the main method, which acts as the official entry point for any standalone Java program. When you run a Java application, the Java Virtual Machine (JVM) is specifically designed to find and execute this method to start the program.

Here is a breakdown of what each keyword means and why it is necessary:

  • public is an access modifier. The public keyword ensures the method is completely accessible. Since the JVM is not part of your class, it needs public access to find and run the main method to launch the application.

  • static is a keyword indicating that the method belongs to the class itself, rather than to a specific object (instance) of the class. The JVM must execute this method before any objects of your class are created. static allows the JVM to call the method directly from the class, without needing to create an object first.

  • void is the return type. void signifies that this method does not return any value. The main method’s job is to start the program’s execution; it’s not expected to return a result to the JVM once it’s finished.

  • main is the method’s name. This specific name is the universally recognized identifier that the JVM is programmed to look for. It’s a standard convention, not a keyword.

  • (String[] args) is the method’s parameter. This is an array of strings that allows you to pass command-line arguments into your program when you run it. For example, you could pass a filename or a configuration setting.

Here is how these keywords come together in a basic “Hello, World!” application:

public class MyFirstProgram {
    // This is the main entry point that the JVM will call.
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

2. Why is the main method static in Java?

The main method is declared static so the Java Virtual Machine (JVM) can invoke it to start the program without needing to create an instance (object) of the class first.

When an application launches, the JVM begins by loading the class file into memory. At this initial stage, no objects of the class exist yet. While non-static methods require an existing object to be called upon, static methods are different. They are tied directly to the class definition and can be called immediately.

Therefore, the main method must be static. This ensures the JVM has an accessible entry point it can call on the class itself to begin execution, solving the logical problem of how to start a program before any objects are created. In essence, the static keyword makes the main method independent of any object, making it the perfect starting point for the JVM.

3. What is the purpose of String[] args?

The String[] args parameter allows your program to accept and use command-line arguments. It acts as a channel to pass information into your application from the outside world at the moment of execution.

It is an array of String objects. When you run your program from a terminal, any text you type after the class name will be passed into your program and stored in this array.

For example, if you run your program like this:

java MyProgram "John Doe" 99

Inside your program, the args array will look like this:

  • args[0] will be "John Doe"
  • args[1] will be "99"

You can then use this data in your code:

public class MyProgram {
    public static void main(String[] args) {
        if (args.length > 0) {
            System.out.println("Hello, " + args[0]); // Prints: Hello, John Doe
        } else {
            System.out.println("Hello, stranger.");
        }
    }
}

4. What happens if a Java program doesn’t have a main method?

If a standalone Java application does not have a method with the exact signature public static void main(String[] args), it will compile correctly but will fail at runtime.

When you try to run the compiled class, the JVM will be unable to find the designated entry point and will throw a NoSuchMethodError, often accompanied by a helpful message like:

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

5. Can a Java class have more than one main method?

Yes, a Java class can have multiple methods named main, as long as their parameter lists are different. This is a concept known as method overloading.

However, the JVM will only recognize the specific signature public static void main(String[] args) as the program’s entry point. All other main methods are just regular methods that you can call from your code like any other.

Example:

public class MultipleMains {
    // This is the only method the JVM will execute to start the program.
    public static void main(String[] args) {
        System.out.println("This is the real entry point.");
        // We can call our other 'main' methods from here.
        main(5);
    }

    // This is an overloaded method. It is not an entry point.
    public static void main(int number) {
        System.out.println("This is the overloaded main method with number: " + number);
    }
}

6. Can I change the signature of the main method?

You can make small, specific modifications, but the core parts of the signature must remain unchanged.

What You CAN change:

  • The parameter name: You can rename args to anything you want (e.g., myParams, inputs).
  • The array syntax: You can use C-style array declaration: String args[].
  • Use varargs: You can use the varargs syntax: String... args.
  • The modifier order: You can swap public and static: static public void main(...).

What You CANNOT change:

  • public: It cannot be private, protected, or have no modifier.
  • static: It cannot be a non-static instance method.
  • void: It must not return a value.
  • main: The name cannot be changed (e.g., Main will not work).

7. Why is the main method public and not private?

The main method must be public to ensure it is visible and accessible to the JVM, which operates from outside your class’s code.

In Java, access modifiers like public and private control a method’s visibility. A private method is only accessible from within the same class, effectively hiding it from all external code.

Since the JVM is an external process responsible for launching the application, it is not part of the class itself. Therefore, if the main method were private, it would be invisible to the JVM, making it impossible to invoke. The public modifier provides unrestricted access, ensuring that the main method is visible and callable by the JVM, which is an essential requirement for starting any Java application.

Conclusion

In this guide, we’ve taken a comprehensive look at the Java main method, from its public static void main(String[] args) syntax to its practical applications and best practices. Understanding not just the rules but the reasons behind them is key to building applications that are not just functional, but also robust and maintainable.

With a solid grasp of these concepts, you now have the foundational skill needed to confidently launch and control the entry point of any standalone Java application.

For more Java-related topics, check out the following articles:

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)

Pankaj Kumar
Pankaj Kumar
Author
See author profile

Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev

Andrea Anderson
Andrea Anderson
Editor
Technical Editor
See author profile
Manikandan Kurup
Manikandan Kurup
Editor
Senior Technical Content Engineer I
See author profile

With over 6 years of experience in tech publishing, Mani has edited and published more than 75 books covering a wide range of data science topics. Known for his strong attention to detail and technical knowledge, Mani specializes in creating clear, concise, and easy-to-understand content tailored for developers.

Category:
Tags:

Still looking for an answer?

Was this helpful?

Nice explanation on core main method.

- Sambasiva

Excellent! Given more clarity on main method

- Vinodkumar

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

not working

- Priyanka

Nice explanation on core main method.

- Naveen singh

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

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

- Kanchan Gautam

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

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

- Vijay

awsome explanation sir,keep going ,

- p.naveen

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

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.