All about main() method in java
The main method is the entry point for any Java program. The Java Virtual Machine (JVM) uses it to start the execution of an application. Without the main method, the JVM won’t know where to begin. Here’s an in-depth look at its syntax and components:
public static void main(String[] args)
Let’s break down each part of this method:
- public: This is an access modifier. The main method must be declared as public so that the JVM can access it from outside the class. If you use other access modifiers like private, protected, or default, the JVM won’t be able to execute the method.
- static: This keyword allows the method to be called without having to create an instance of the class. The JVM can invoke the main method directly, without needing to instantiate the class that contains it.
- void: This indicates that the main method does not return any value. In Java, every method must declare its return type, and void specifies that no value will be returned.
- main: This is the name of the method that the JVM looks for as the starting point of the program. It’s a predefined method name in the JVM.
- String[] args: This parameter allows the main method to accept arguments from the command line. The args array holds these arguments as strings. While typically used for passing configuration or parameters, the array can hold any string data, including representations of numeric values.
Detailed Breakdown
- public: Ensures visibility to the JVM for execution.
- static: Enables the JVM to call this method without needing an object.
- void: Specifies that this method doesn’t return any data.
- main: The standard method name recognized by the JVM.
- String[] args: Facilitates passing command-line arguments to the program.
Example Usage
Here’s a simple example of a Java program using the main method:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, readers!");
}
}
Overloading the main Method in Java ?
Yes, it is possible to overload the main method in Java. While a Java class can have multiple main methods, it must include at least one with the signature public static void main(String[] args) for the JVM to execute the program. Without this specific method, the class will compile but won’t run.
Example of main Method Overloading
Below is an example demonstrating how to overload the main method:
/**
* Demonstrates overloading of the main method in Java.
*/
public class MainMethodOverloading {
// Overloaded main method with one integer parameter
public static void main(int number) {
System.out.println("Number: " + number);
}
// Overloaded main method with two integer parameters
public static void main(int number1, int number2) {
System.out.println("Sum: " + (number1 + number2));
}
// Standard main method required for JVM execution
public static void main(String[] args) {
// Calling the overloaded main methods
main(15);
main(25, 35);
}
}
Output:
Number: 15
Sum: 60
Accessibility of the main Method in Java
In Java, the main method must be declared as public. Declaring it as private, protected, or without any access modifier will prevent the JVM from accessing it, leading to a runtime error even though the class will compile successfully.
Example of Incorrect Access Modifier
Here’s an example that demonstrates what happens when the main method is declared with an incorrect access modifier:
public class Main {
protected static void main(String[] args) {
System.out.println("Protected main method.");
}
}
Output:
Error: Main method not found in class Main, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Explanation
The JVM will not recognize the main method because it is not declared as public. As a result, the program will compile but will fail at runtime with an error indicating that the main method was not found.
Correct Usage with public Access Modifier
To ensure the JVM can execute your program, always declare the main method as follows:
public class Main {
public static void main(String[] args) {
System.out.println("Public main method.");
}
}
Output:
Public main method.
Special Case: Using Another Entry Point
You can declare the main method with a different access modifier if it is not the entry point of your program. For example, if another class contains the standard main method, it can call the protected or private main method.
class HelperMain {
protected static void main(String[] args) {
System.out.println("Protected main method in HelperMain.");
}
}
public class Main {
public static void main(String[] args) {
HelperMain.main(args);
}
}
Output:
Protected main method in HelperMain.
Explanation
In this case, the HelperMain class has a protected main method, and the Main class has the standard public static void main(String[] args) method. The JVM starts execution from the Main class and then calls the HelperMain method, demonstrating that the main method can have different access levels if it’s not the entry point.
Can We Declare the main Method as Non-Static in Java?
No, we cannot declare the main method as non-static in Java. The JVM calls the main method before creating any instance of the class. Since non-static methods require an instance of the class to be invoked, the main method must be static to be called directly by the JVM.
Example of Incorrect Declaration
Here’s an example that demonstrates what happens when the main method is declared as non-static:
public class Main {
public void main(String[] args) {
System.out.println("Non-static main method.");
}
}
Output
Error: Main method is not static in class Main, please define the main method as:
public static void main(String[] args)
Explanation
The JVM expects the main method to be static so it can call it without creating an object of the class. If the main method is declared as non-static, the JVM will not be able to find it, resulting in a runtime error.
Correct Declaration with static Keyword
To ensure the JVM can execute your program, always declare the main method as follows:
public class Main {
public static void main(String[] args) {
System.out.println("Static main method.");
}
}
Output
Static main method.
Explanation
By declaring the main method as static, you allow the JVM to call it directly using the class name, which is necessary for the program to start execution.
Can We Change the Return Type of the main Method?
No, we cannot change the return type of the main method in Java. The main method must have a return type of void to be recognized as the entry point of the application by the JVM. Changing the return type will lead to a compilation error, as the compiler will not acknowledge it as the valid starting point.
Example of Incorrect Return Type
Here’s an example demonstrating what happens when the main method’s return type is changed:
public class Main {
public static String main(String[] args) {
System.out.println("main method with a return type");
return "example.com";
}
}
Output
Error: Main method must return a value of type void in class Main, please
define the main method as:
public static void main(String[] args)
Explanation
The JVM expects the main method to have a specific signature: public static void main(String[] args). Any deviation from this, including changing the return type, results in a compilation error because the JVM will not recognize the method as the entry point.
Can We Run a Java Class Without the main Method?
Yes, it is possible to run a Java class without the main method by using a static initializer block that includes a System.exit(0); statement. However, this approach is only valid up to Java 6. From Java 7 onwards, the program will compile but not execute without the main method.
Example Using Static Initializer Block (Valid in Java 6 and Below)
Here’s an example demonstrating how to run a Java class without the main method using a static initializer block:
public class Test {
static {
System.out.println("Hello Test");
System.exit(0);
}
}
Explanation
- Static Initializer Block: The static block is executed when the class is loaded into memory, before any objects are created and before the main method is called (if it exists).
- System.exit(0): This statement terminates the JVM, preventing the need for a main method.
Output (Java 6 and Below)
Hello Test
Java 7 and Later Versions
From Java 7 onwards, this approach will no longer work. The program will compile but fail to execute with an error indicating the absence of the main method.
Example Output (Java 7 and Later)
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
Summary
- Java 6 and Below: It is possible to run a Java class without the main method using a static initializer block and System.exit(0);.
- Java 7 and Later: This method will not work. The program will compile but fail to execute, requiring the presence of a main method.
- Best Practice: Always include a main method in your Java classes to ensure compatibility and proper execution across all Java versions.
Correct Approach for All Java Versions
To ensure your Java program runs correctly across all versions, always include a main method:
public class Test {
public static void main(String[] args) {
System.out.println("Hello Test");
}
}
Output:
Hello Test
Can We Declare the main Method as Final?
Yes, we can declare the main method as final in Java. Declaring the main method as final prevents it from being overridden in subclasses, but it still maintains the required signature for the JVM to recognize and execute it as the entry point of the program.
Example
Here’s an example demonstrating the main method declared as final:
public class Main {
public static final void main(String[] args) {
System.out.println("Final main method");
}
}
Output
Final main method
Explanation
- Final Modifier: The final keyword prevents the main method from being overridden by subclasses. This can be useful to ensure the entry point of your program remains unchanged and secure.
- Standard Signature: The main method retains its standard signature public static void main(String[] args), ensuring that the JVM recognizes it as the entry point of the application.
Summary
- Final Keyword: You can use the final keyword with the main method to prevent it from being overridden.
- Standard JVM Entry Point: The main method still needs to follow the standard signature (public static void main(String[] args)) to be recognized and executed by the JVM.
- Practical Use: Using final for the main method ensures that the entry point remains unchanged and secure against overriding in subclasses.
Example with Subclass (Attempting to Override)
Here’s an example demonstrating the use of final to prevent overriding:
public class Main {
public static final void main(String[] args) {
System.out.println("Final main method in Main class");
}
}
class SubMain extends Main {
// This will cause a compilation error
// public static void main(String[] args) {
// System.out.println("Main method in SubMain class");
// }
}
Explanation
- Compilation Error: Attempting to override the main method in the SubMain class will result in a compilation error because the main method in the Main class is declared as final.
Further references:
Thank you for reading this article. If you have any further questions or need additional assistance, please feel free to ask!
Social Media: LinkedIn, Twitter, Instagram, YouTube, GitHub.
All about main() method in java was originally published in Javarevisited on Medium, where people are continuing the conversation by highlighting and responding to this story.
This post first appeared on Read More