Table of Contents
URL: https://www.progressiverobot.com/public-static-void-main-string-args-java-main-method/
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
staticmodifier is required so the JVM can invoke themainmethod on the class itself, before any object instances have been created. - The
publicaccess modifier ensures themainmethod is visible and accessible to the external JVM process that initiates program execution. - The
String[] argsparameter 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.lengthbefore accessing array elements. - For maintainable code, the
mainmethod 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
argsor swapping the order of thepublicandstaticmodifiers. - While mandatory for standalone programs, the
mainmethod 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:
[label 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:
[label 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:
javac Test.java
java Test
[secondary_label 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:
[label 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:
javac Test.java
java Test
[secondary_label 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:
[label 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:
javac Test.java
[secondary_label 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:
[label 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:
javac Test.java
java Test
[secondary_label 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:
[label 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:
javac Test.java
java Test 1 2 3 "Testing the main method"
[secondary_label 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.
- Missing the
publicModifier: If you omit thepublicaccess modifier, the main method is no longer visible to the JVM from outside the class. Thepublicmodifier makes a method part of a class'spublicinterface, accessible by any external entity. Since the JVM is an external process that initiates your code, it needs public access to find and invoke themainmethod. 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. - Missing the
staticModifier: Omitting thestatickeyword makes themainmethod 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-staticmainmethod. This is why the entry point must bestatic; it belongs to the class itself and can be called without an instance. - Changing the
voidReturn 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 returnsvoid. By changing the return type fromvoidtoint, you have defined a completely different method. From the JVM's perspective, the requiredmainmethod that returnsvoidis now missing entirely. Your code may compile, but the JVM will not find the specific signature it needs to start the program. - Altering the Method Name or Parameter Type: Any change to the method's name (e.g.,
Main) or its parameter type (e.g.,Stringinstead ofString[]) also breaks the signature contract. The JVM is programmed to look for a method named exactlymain(case-sensitive) that accepts exactly one parameter of typeString[]. 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 typeString, 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 themainmethod, this is functionally equivalent to theString[]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.
[label 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:
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.
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.,
maiminstead ofmain). - Incorrect Capitalization: The name is capitalized (e.g.,
Maininstead ofmain). Java is case-sensitive. - Wrong Return Type: You have something other than
voidas the return type (e.g.,public static int main(...)). - Incorrect Parameter Type: The parameter is not a
Stringarray (e.g., you havemain(String arg)instead ofmain(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.
- Keep the
mainMethod Lean: Treat themainmethod 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 insidemain, 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.lengthto ensure the user has provided the required input, and usetry-catchblocks when parsing numbers. This prevents common runtime errors likeArrayIndexOutOfBoundsExceptionandNumberFormatExceptionand 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 usingSystem.exit(). By convention, exit withSystem.exit(0)for a successful run and a non-zero number (likeSystem.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
mainmethod in your primary class is fine. However, in larger applications, it's a best practice to put themainmethod in its own dedicated class (e.g.,Application.javaorMain.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:
publicis an access modifier. Thepublickeyword ensures the method is completely accessible. Since the JVM is not part of your class, it needs public access to find and run themainmethod to launch the application.
staticis 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.staticallows the JVM to call the method directly from the class, without needing to create an object first.
voidis the return type.voidsignifies that this method does not return any value. Themainmethod's job is to start the program's execution; it's not expected to return a result to the JVM once it's finished.
mainis 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
argsto anything you want (e.g.,myParams,inputs). - The array syntax: You can use C-style array declaration:
String args[]. - Use
varargs: You can use thevarargssyntax:String... args. - The modifier order: You can swap
publicandstatic:static public void main(...).
What You CANNOT change:
public: It cannot beprivate,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.,Mainwill 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: