How do I Read User Input in a Compact Java 25 Program?

Java 25 (via JEP 512: Compact Source Files and Instance Main Methods, finalized in Java 25) makes reading user input dramatically simpler. You no longer need a class declaration, a public static void main(String[] args) signature, or even System.out.println / Scanner boilerplate.

The New IO Class

Java 25 introduces the java.lang.IO class, which is automatically imported in compact source files. It provides three convenient static methods:

Method Purpose
IO.print(x) Print without newline
IO.println(x) Print with newline
IO.readln(prompt) Print a prompt and read a line from stdin

Compact Example

Here’s a compact Java 25 program that reads user input:

void main() {
    String username = IO.readln("Username: ");
    String password = IO.readln("Password: ");
    int result = Integer.parseInt(IO.readln("What is 2 + 2: "));

    if (username.equals("admin") && password.equals("secret") && result == 4) {
        IO.println("Welcome to Java Application");
    } else {
        IO.println("Invalid username or password, access denied!");
    }
}

Key Points

  • No class declaration required — the file becomes an implicitly declared class.
  • No String[] args — you can just write void main().
  • No import statements — java.base and java.lang.IO are auto-imported.
  • No Scanner — IO.readln(...) handles the prompt and line read in one call.
  • The method can be void main() or void main(String[] args); static is optional.

Running It

Save the code as Login.java and run it directly (no compile step needed):

java Login.java

When You Still Need Scanner

IO.readln only returns String. If you need typed input like int, double, etc., you either:

  1. Parse it yourself (as shown above with Integer.parseInt), or
  2. Fall back to java.util.Scanner for its nextInt(), nextDouble(), etc.

For most simple interactive programs, IO.readln + parsing is the cleanest approach in Java 25.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.