javaconsoleconsole-application

Newer easier ways to interact with the console in Java 23+?


I have seen mentions of new classes and methods for interacting with a console in a Java app. Like this:

You shouldn't use Scanner at all, really. It's not meant for keyboard input, and it has bizarre API. In that the API does exactly what its spec says, but if you think 'Scanner - that's the keyboard, right?' the spec of scanner is bizarre. See the usual confusion about mixing nextLine and nextInt for example. There is no good replacement right now yet, but there will be soon: java.io.IO.

I cannot find a Java JEP for these new features on the JEP index.


Solution

  • tl;dr

    Yes, new console methods are being previewed in Java 24 (& Java 23).

    The existing Console class, and a new IO class, offer print, println, & readln methods.

    The old System.out.println ( "Hello world!" ) is supplanted by the new IO.println ( "Hello world!" ).

    New 🟢 🔴 Old
    IO.println ( "Hello world!" ) System.out.println ( "Hello world!" )
    String input = IO.readln ( "Enter id: " ); System.out.println ( "Enter id: ) ;
    String input = System.console().readLine();

    Details

    Yes, there is a series of JEPs adding features related to the console.

    This series is part of the Paving the On-Ramp effort in recent years to make Java easier for beginner students.

    java.io.IO

    If successful, this series of JEPs would add a new class, java.io.IO. This class offers these methods:

    Notice that these methods are static. So we can use them without instantiating the class.

    So the familiar System.out.println ( "Hello world!" ); becomes:

    import java.io.IO;
    …
    IO.println ( "Hello world!" );
    

    Or, becomes even more brief with a static import.

    import static java.io.IO.println;
    …
    println ( "Hello world!" );
    

    java.io.Console

    These java.io.IO methods are implemented by calling upon the Console object returned from System.console(). So that Console class gains new methods, with the same signatures.

    More info

    Caveat: These are preview features, subject to change or removal.

    Try these out in Java 24 based on the OpenJDK codebase. Available from JDK vendors such as Azul Systems, BellSoft, Amazon, Red Hat, IBM, Oracle, Adoptium of Eclipse Foundation, SAP, Microsoft, and more.