In this post under Java language, I will introduce you to new feature added to Java called “Instance Main Method”.
This feature was added in Java version 25.
Pre Java 25, if we have to write class with “main” method, we used to mark it as public and static as shown below. You also need to provide String array as arguments.
Pre Java 25
public class Example1 { public static void main(String[] args) { .... }}
From Java 25, we can change the above code as shown below
Java 25 onwards
public class Example1 { void main() { .... }}
As you can see we don’t need to mark the “main” method as “public” and “static”.
We also don’t need to add String array as arguments to main method.
In pre Java 25, Java runtime would directly called the “main” method using the class name, as the method was marked public and static.
From Java 25 onwards, with the new code, the Java runtime will create an instance of the class using default no argument constructor and then call the new “main” method.
Below is the complete code for your reference.
package core.language;public class InstanceMainMethodExample { public InstanceMainMethodExample() { System.out.println("InstanceMainMethodExample constructor"); } void main() { System.out.println("Hello World"); }}
In the above class, I have added my own default no argument constructor, which will print a statement in the console when called.
Then I have added new “main” method which also prints a statement in the console when called.
Now when we execute the above code, the output will be as shown below
Output
InstanceMainMethodExample constructorHello World
As you can see from the output, first the constructor is called and then the main method.
In this way we can use the new instance main method feature.