Main() without Class (and it’s not Kotlin)

Gaetano Piazzolla
3 min readJun 8, 2023

Jdk 21 has just reached Rampdown Phase One and will be released with some awesome features such as Virtual Threads, sequenced collections, generational ZGC, and pattern matching.

As if that weren’t enough, Java is becoming more accessible to new programmers thanks to this JEP (Java Enhancement Proposal) 445: Unnamed Classes and Instance Main Methods.

In this short tutorial, we’ll take a look at He-Who-Must-Not-Be-Named.

Photo by Micaela Parente on Unspash

Imagine learning the first concepts of Java without the burden of learning all the boilerplate needed to run a simple script that does the sum of two numbers. Thanks to this brand-new enhancement, It’s now possible to write:

void main() {
int a = 1;
int b = 2;
int c = a + b;
}

Instead of the draconian:

public class MainClass {
public static void main(String[] args) {
int a = 1;
int b = 2;
int c = a + b;
}
}

But what does that main() method standing alone means? Where does it reside? Is it possible to reference it from outside? First of all, let’s make a distinction between anonymous classes ad unnamed classes. I think It’s necessary considering how close these words are.

--

--