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.
public static void main(String[] args) {
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.
This version allows you to define the main logic without even creating a method.
System.out.println("Hello, World!");
inside a MyRunner.java
file would be translated by the JVM as:
public class MyRunner {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}