Since main() is made static so that JVM can access it without creating an object of the class in which it is defined, then what is the need for writing it in a class?
As @Sören said, until the recent versions, it was just assumed that everything needs to be inside of a class, even the entry point of a program (maybe for injecting further dependencies inside the class). That is because Java is a purely object-oriented language (at least it was).
Now, you can write your main
without actually defining any class. This happened since Java 21.
void main() {
System.out.println("Hello, World!");
}
The runtime would compile and automatically create a class around it, based on the name of the .java
file containing the method. Assuming that your file is called Runner.java
, you could compile & run your code like this:
javac --source 21 --enable-preview Runner.java
java --source 21 --enable-preview Runner
... also enabling Java 21's preview features.
This version allows you to define the main logic without even creating a method.
System.out.println("Hello, World!");
inside a Runner.java
file would be translated by the JVM as:
public class Runner {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
You could also completely omit the compilation command by running your single-source program like this:
java --source 21 --enable-preview Runner.java