Wednesday, May 8, 2024

The new Java main()

`public static void main(String[] args)` is (or wa

public static void main(String[] args) is (or was) the infamous entry point in all Java programs

class MyApp1 {
	public static void main(String[] args) {
		System.out.println("Hello World!");
	}
}
# Using Java 21

$ javac MyApp1.java
$ java MyApp1
Hello World!

Now, since Java 21 the Java Team added the instance main methods feature that allows Java Programs to be launched with simple instance methods named main that no need to be static, nor public (but they cannot be private for obvious reasons), nor receive parameters:

class MyApp2 {
	void main() {
		System.out.println("Hello World!");
	}
}
# Using Java 21

$ javac MyApp2.java
$ java --enable-preview MyApp2
Hello World!

then also they added another feature called unnamed classes that add the ability to declare classes in an implicit manner. Lets say we create a file called MyApp3.java and then in that file we write:

void main() {
	System.out.println("Hello World!");
}

this main method is an instance method in a implicit class named MyApp3 (the class its taking its name from the file name).

# Using Java 21

$ javac --enable-preview --release 21 MyApp3.java
$ java --enable-preview MyApp3
Hello World!

and soon in Java 23 every implicit class will automatically import static methods from package java.io.IO.* which will allow to write the main method much simpler.

void main() {
	println("Hello World!");
}

but again this feature is not yet released not even as a preview.