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
public static void main(String[] args)
signature is the mandatory, unchangeable entry point the Java Virtual Machine (JVM) requires to execute a standalone application.static
modifier is required so the JVM can invoke the main
method on the class itself, before any object instances have been created.public
access modifier ensures the main
method is visible and accessible to the external JVM process that initiates program execution.String[] args
parameter serves as the mechanism to receive command-line arguments, allowing external data to be passed into the program at runtime.args.length
before accessing array elements.main
method should act as a coordinator that delegates complex logic to other methods or objects rather than containing it directly.args
or swapping the order of the public
and static
modifiers.main
method is not the entry point in container-managed environments like web or Android applications.main
Method SyntaxThe 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
:
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:
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:
- javac Test.java
- java Test
OutputError: 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:
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
:
- javac Test.java
- java Test
OutputError: 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
:
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
:
- javac Test.java
OutputTest.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
:
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:
- javac Test.java
- java Test
OutputError: 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:
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:
- javac Test.java
- java Test 1 2 3 "Testing the main method"
Output1
2
3
Testing the main method
main
Method Signature Must Be ExactThe 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.
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.
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.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.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.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.main
Method SignatureWhile 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.
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.
}
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.
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.
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.
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:
- javac GreetUser.java
Now, run the program and pass your name right after the class name. Let’s use “Alice”.
- java GreetUser Alice
Output:
Hello, Alice! Welcome to the program.
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.
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:
maim
instead of main
).Main
instead of main
). Java is case-sensitive.void
as the return type (e.g., public static int main(...)
).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)
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.
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.
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.
main
MethodFollowing a few key practices when writing your main
method can significantly improve your application’s quality, making it more readable, robust, and professional.
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.
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.
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.
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.
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!");
}
}
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.
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.");
}
}
}
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)
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);
}
}
main
method?You can make small, specific modifications, but the core parts of the signature must remain unchanged.
What You CAN change:
args
to anything you want (e.g., myParams
, inputs
).String args[]
.varargs
: You can use the varargs
syntax: String... args
.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).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.
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.
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
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.
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
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
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
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
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.