Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console.writer().println() vs Console.format() vs System.out.println()

Tags:

java

io

Console.writer().println() is displaying "Enter 3 words" after console.readLine(). Can anyone explain why?

class Class3{
    public static void main(String... args){
        Console console = System.console();
        if(console == null){
            throw new RuntimeException("No console");
        }else{
            //System.out.println("Enter 3 words");
            //console.format("Enter 3 words");
            console.writer().println("Enter 3 words");
            
            List<String> strings = new ArrayList<>();
            for(int i=0;i<3;++i){
                strings.add(console.readLine());
            }
            console.format("You entered %s, %s, %s",
                    strings.get(0),
                    strings.get(1),
                    strings.get(2)
            );
            console.writer().println();  
        } 
    }
}

Output: Output of the application

I tried using System.out.println() and console.format() and both print "Enter 3 words" before the application accepts 3 strings

like image 391
Libro Avatar asked Nov 17 '25 07:11

Libro


1 Answers

A quick look at JDK24 source code shows Console as a sealed class with permits ProxyingConsole. The class ProxyingConsole declares writer() to use WrappingWriter extends PrintWriter which constructs super class PrintWriter which sets this.autoFlush = false

This means that when you use console.writer(), it should be followed by console.writer().flush() if you want to guarantee the output is shown when you want it to.

System.out.println() is defined with autoflush so any output is shown for each call.

Thanks for the useful comments. JDKs have different behaviours for autoFlush in Console writer. From some checks on OpenJDK in Windows 11:

JDK console.writer() autoFlush System.out autoFlush
14 17 18 19 20 ✅ true ✅ true
21 22 23 24 25b18 ❌ false ✅ true
like image 65
DuncG Avatar answered Nov 19 '25 22:11

DuncG