Java 25 simplifies main() with compact source files and IO

Java25 : main() , Compact Source, IO In Java 25 : The language significantly simplifies writing a main method by removing much of the traditional boilerplate. The new "Compact Source Files and Instance Main Methods" feature (JEP 512) allows you to write simple programs without a class wrapper, a public or static modifier, or the String[] args parameter. Writing main methods in Java 25 - 1.Traditional main method The classic, fully-featured main method remains the standard for most applications and is fully backward-compatible. // MyProgram.java public class MyProgram { public static void main(String[] args) { System.out.println("Hello, " + args[0] + "!"); } } 2. Simplified main method within a class For smaller programs, you can now write a less verbose main method inside a class, omitting the public, static, and String[] args parts. The JVM will look for this simplified version if it doesn't find the traditional one. java // HelloWorld.java class HelloWorld { void main() { System.out.println("Hello, World!"); } } 3. "Compact source file" with instance main For the most minimal entry point, you can place the simplified main method directly in a file without an enclosing class. The compiler automatically wraps the code in an implicit, unnamed class. // Minimal.java void main() { System.out.println("Hello from a compact source file!"); } 4. Using the java.lang.IO helper class To further reduce boilerplate for console I/O, Java 25 introduces a java.lang.IO helper class, making it easier to read and write from the console. java // IOExample.java import static java.lang.IO.*; void main() { var name = readln("What's your name? "); println("Hello, " + name + "!"); } Article: Java's main method gets a beginner-friendly reboot In its latest long-term support (LTS) version, Java 25, the platform has made a significant update to how developers, particularly beginners, can write the entry point to their programs. By finalizing JEP 512, which introduces "Compact Source Files and Instance Main Methods," Java has shed some of its long-standing "boilerplate" to become more accessible and intuitive. The feature, which was refined over several preview releases (including Java 21–24), provides a smoother on-ramp for new programmers by removing the need to understand complex, enterprise-level concepts like public, static, and the String[] args parameter from day one.

To view or add a comment, sign in

Explore content categories