NOTE: problem doesn't appear when we run your code from console/terminal via java [options] [MainClass] so if this is valid solution for you you can stop reading here. Rest of this answer is for people who are using some IDEs to run their code.

Problem

Most IDEs are using javaw.exe instead of java.exe to run Java code (see image below).

Difference between these two programs is that javaw runs Java code without association with current terminal/console (which is useful for GUI applications), and since there is no associated console window System.console() returns null. Because of that System.console().readLine() ends up as null.readLine() which throws NullPointerException since null doesn't have readLine() method (nor any method/field).

But just because there is no associated console, it doesn't mean that we can't communicate with javaw process. This process still supports standard input/output/error streams, so IDEs process (and via it also we) can use them via System.in, System.out and System.err.

This way IDEs can have some tab/window and let it simulate console.

For instance when we run code like in Eclipse:

package com.stackoverflow;

public class Demo {

    public static void main(String[] args) throws Exception {
        System.out.println("hello world");
        System.out.println(System.console());
    }

}

we will see as result

which shows that despite javaw.exe not having associated console (null at the end) IDE was able to handle data from standard output of the javaw process System.out.println("hello world"); and show hello world.

General solution

To let user pass information to process use standard input stream (System.in). But since in is simple InputStream and Streams are meant to handle binary data it doesn't have methods which would let it easily and properly read data as text (especially if encoding can be involved). That is why Readers and Writers ware added to Java.

So to make life easier and let application read data from user as text you can wrap this stream in one of the Readers like BufferedReader which will let you read entire line with readLine() method. Unfortunately this class doesn't accept Streams but Readers, so we need some kind of adapter which will simulate Reader and be able to translate bytes to text. But that is why InputStreamReader exists.

So code which would let application read data from input stream could look like

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Hello. Please write your name: ");
String name = br.readLine();
System.out.println("Your name is: "+name);

Preferred/simplest solution - Scanner

To avoid this magic involving converting Stream to Reader you can use Scanner class, which is meant to read data as text from Streams and Readers.

This means you can simply use

Scanner scanner = new Scanner(System.in);
//...
String name = scanner.nextLine();

to read data from user (which will be send by console simulated by IDE using standard input stream).

Answer from Pshemo on Stack Overflow
Top answer
1 of 7
91

NOTE: problem doesn't appear when we run your code from console/terminal via java [options] [MainClass] so if this is valid solution for you you can stop reading here. Rest of this answer is for people who are using some IDEs to run their code.

Problem

Most IDEs are using javaw.exe instead of java.exe to run Java code (see image below).

Difference between these two programs is that javaw runs Java code without association with current terminal/console (which is useful for GUI applications), and since there is no associated console window System.console() returns null. Because of that System.console().readLine() ends up as null.readLine() which throws NullPointerException since null doesn't have readLine() method (nor any method/field).

But just because there is no associated console, it doesn't mean that we can't communicate with javaw process. This process still supports standard input/output/error streams, so IDEs process (and via it also we) can use them via System.in, System.out and System.err.

This way IDEs can have some tab/window and let it simulate console.

For instance when we run code like in Eclipse:

package com.stackoverflow;

public class Demo {

    public static void main(String[] args) throws Exception {
        System.out.println("hello world");
        System.out.println(System.console());
    }

}

we will see as result

which shows that despite javaw.exe not having associated console (null at the end) IDE was able to handle data from standard output of the javaw process System.out.println("hello world"); and show hello world.

General solution

To let user pass information to process use standard input stream (System.in). But since in is simple InputStream and Streams are meant to handle binary data it doesn't have methods which would let it easily and properly read data as text (especially if encoding can be involved). That is why Readers and Writers ware added to Java.

So to make life easier and let application read data from user as text you can wrap this stream in one of the Readers like BufferedReader which will let you read entire line with readLine() method. Unfortunately this class doesn't accept Streams but Readers, so we need some kind of adapter which will simulate Reader and be able to translate bytes to text. But that is why InputStreamReader exists.

So code which would let application read data from input stream could look like

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Hello. Please write your name: ");
String name = br.readLine();
System.out.println("Your name is: "+name);

Preferred/simplest solution - Scanner

To avoid this magic involving converting Stream to Reader you can use Scanner class, which is meant to read data as text from Streams and Readers.

This means you can simply use

Scanner scanner = new Scanner(System.in);
//...
String name = scanner.nextLine();

to read data from user (which will be send by console simulated by IDE using standard input stream).

2 of 7
6

Normally, the Console object requires a valid tty provided by an operating system, but IntelliJ IDEA output window does not provide one. It's not very trivial to do this in OS-independent way. Not only IntelliJ IDEA is affected. You cannot use System.console() in jshell as well:

|  Welcome to JShell -- Version 17.0.6
|  For an introduction type: /help intro

jshell> System.console()
$1 ==> null

jshell>

In Java 20, this issue was partially addressed. Now, you can add a VM option -Djdk.console=jdk.internal.le. Go to 'Edit Run/Debug configurations', then Modify Options, Add VM Options and type it there. After that the System.console() will work inside IDE. It will be hooked to System.in which IDE already intercepts.

Note that this solution is undocumented and unsupported, so may not work in future Java versions. You can find more information in this JDK issue.

🌐
Coderanch
coderanch.com › t › 641563 › java › System-console-returns-null
System.console() returns null (Java in General forum at Coderanch)
The problem is that System.console() returns null, and for that reason the NullPointerException is thrown at 11. Is there a way to run this in Eclipse without significant changes in the code?.
🌐
JetBrains
youtrack.jetbrains.com › issue › IDEA-18814
IDEA doesnt work with System.console() : IDEA-18814
September 19, 2022 - {{ (>_<) }} This version of your browser is not supported. Try upgrading to the latest stable version. Something went seriously wrong
🌐
GitHub
github.com › ConvertAPI › convertapi-java › issues › 5
System.console() is null when using an IDE · Issue #5 · ConvertAPI/convertapi-library-java
June 4, 2019 - Caused by: java.lang.NullPointerException at com.convertapi.client.Http.getRequestBuilder(Http.java:62) at com.convertapi.client.Param.lambda$upload$1(Param.java:98) Possible fix: static Request.Builder getRequestBuilder() { if (System.console() == null) { System.out.printf("VERSIJA: %s", Http.class.getPackage().getImplementationVersion()); } else { System.console().printf("VERSIJA: %s", Http.class.getPackage().getImplementationVersion()); } String agent = String.format("ConvertAPI-Java/%.1f (%s)", Http.class.getPackage().getImplementationVersion(), System.getProperty("os.name")); return new Request.Builder().header("User-Agent", agent); } No one assigned ·
Author   ConvertAPI
🌐
JetBrains
intellij-support.jetbrains.com › hc › en-us › community › posts › 206950095-System-console-jdk6-Console
System.console() - jdk6 Console – IDEs Support (IntelliJ Platform) | JetBrains
May 4, 2010 - Hi guys,are there any plans to support:Console con = System.console() ?As at the moment it returns "null", just like probably...
🌐
JetBrains
intellij-support.jetbrains.com › hc › en-us › community › posts › 206852195-Unable-to-use-java-groovy-console-while-debugging
Unable to use java/groovy console while debugging – IDEs Support (IntelliJ Platform) | JetBrains
March 12, 2014 - System.console() will return null if launched from the IDE. This is IDE limitation. See the documentation http://docs.oracle.com/javase/7/docs/api/java/io/Console.html :
🌐
Eclipse
bugs.eclipse.org › bugs › show_bug.cgi
122429 – System.console() (Java 6.0) returns null when running inside Eclipse
Bugzilla – Bug 122429 System.console() (Java 6.0) returns null when running inside Eclipse Last modified: 2021-09-17 03:34:03 EDT
Find elsewhere
🌐
JetBrains
youtrack.jetbrains.com › issue › IDEABKL-5949 › System.console-returns-null
System.console() returns null : IDEABKL-5949
{{ (>_<) }} This version of your browser is not supported. Try upgrading to the latest stable version. Something went seriously wrong
🌐
Mkyong
mkyong.com › home › java › java – how to read input from system.console()
Java - How to read input from System.console() - Mkyong.com
January 31, 2020 - System.console() returns null in an IDE, try running it in the console or terminal. $ cd project/target/classes project/target/classes$ java com.mkyong.io.JavaSample Enter your name: mkyong Name is: mkyong Enter your password: Password is: 123456
🌐
JetBrains
intellij-support.jetbrains.com › hc › en-us › community › posts › 206154869-Fehlermeldung-bei-System-console-readLine-Nur-bei-IntellJ-und-Eclipse-
Fehlermeldung bei System.console().readLine(); [Nur bei IntellJ und Eclipse] – IDEs Support (IntelliJ Platform) | JetBrains
November 9, 2015 - Exception in thread "main" ... at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) Process finished with exit code 1 · public class Main { public static void main(String[] args){ String ipEingabe; String NetzmaskEingabe; int ipBin; int ipDez; int NetzmaskBin; int NetzmaskDez; System.out.println("IP Adresse eigeben: "); ipEingabe = System.console().readLine(); ...
🌐
Tabnine
tabnine.com › home › code library
java.lang.System.console java code examples
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
Top answer
1 of 2
3

If you start java from a terminal window, then it really should work, even though I haven't tried on OSX.

If you run a simple test using java directly from the terminal, does it work?

echo 'public class Test { public static void main(String[] args) {System.console().printf("hello world%n");}}' >Test.java && javac Test.java && java Test 

Expected output:

hello world

If it doesn't work, then sorry, no console support on your platform.

However, if it works, and your program doesn't then there is a problem with how your program is started.

Check how the java binary started? Is it started from a shell script? Check that stdin/stdout have not been redirected or piped into something, and possibly also that it's not started in the background.

ex: This will probably make System.console() return null.

java Test | tee >app.log    

and this:

java Test >/tmp/test.log

This seems to work on my machine (linux)

java Test &

Neither does it seem as if System.setOut, System.setErr or System.setIn affects the console, even after a couple of gc's and finalizers.


However:

Closing (the original) System.out or System.in will disable the console too.

echo 'public class Test { public static void main(String[] args) {System.out.close();System.console().printf("hello world%n");}}' >Test.java && javac Test.java && java Test 

Expected output:

Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:1)

So; scan your code for places where it closes streams, or passes System.out somewhere it might get closed.

2 of 2
1

To read from Standard input (command line input) you must use some kind of stream reader to read the System.in stream. An InputStreamReader initialised by

    InputStreamReader(System.in) 

lets you read character by character. However, I suggest wrapping this with a BufferedReader:

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String inputLine = reader.readLine();

Must import

    java.io.*;
🌐
JetBrains
youtrack.jetbrains.com › issue › SCL-22246 › System.console-is-null
System.console is null : SCL-22246
{{ (>_<) }} This version of your browser is not supported. Try upgrading to the latest stable version. Something went seriously wrong
🌐
Stack Overflow
stackoverflow.com › questions › linked › 4203646
Hot Linked Questions - Stack Overflow
In order to get a reference to a Console in Java, one needs to write Console console = System.console(); However, when trying to do this in an IDE, console will be initialized with null.
🌐
JetBrains
youtrack.jetbrains.com › issue › IDEA-128429 › System.console-is-null-in-build-script
System.console() is null in build script : IDEA-128429
{{ (>_<) }} This version of your browser is not supported. Try upgrading to the latest stable version. Something went seriously wrong
Top answer
1 of 5
2

Javadoc says why it returns null

console

public static Console console()

Returns the unique Console object associated with the current Java virtual machine, if any.

Returns: The system console, if any, otherwise null.

Since: 1.6

Intellij IDEA returns null too with System.console so the only thing you can do is to create two methods (one for read line, one for password since System.console have readPassword method) which helps you to avoid problems when switch to IDE to Production.

public static String readLine() throws IOException
{
    if (System.console() != null)
    {
        return System.console().readLine();
    }
    else
    {
        return new BufferedReader(new InputStreamReader(System.in)).readLine();
    }
}

public static char[] readPassword() throws IOException
{
    if (System.console() != null)
    {
        return System.console().readPassword();
    }
    else
    {
        return readLine().toCharArray();
    }
}

I chosed to keep the char[] way for readPassword but if you want you can convert it to string.

You can keep in memory the System.console reference to avoid double call to console() method which is syncronized (in my source code at least)

public static String readLine() throws IOException
{
    Console console = System.console();
    if (console != null)
    {
        return console.readLine();
    }
    else
    {
        return new BufferedReader(new InputStreamReader(System.in)).readLine();
    }
}

public static char[] readPassword() throws IOException
{
    Console console = System.console();
    if (console != null)
    {
        return console.readPassword();
    }
    else
    {
        return readLine().toCharArray();
    }
}
2 of 5
1

From System#console javadoc:

Returns the unique Console object associated with the current Java virtual machine, if any.

Returns

The system console, if any, otherwise `null`.

If you want to use System#console then you must execute your Java application since a console like Windows CMD or Linux console. If you happen to run this application since your IDE e.g. Eclipse, Netbeans, IntelliJ, etc, you will get null value since they're not real consoles.

If you happen to work with Eclipse, you can refer to this Q/A to make it work in Eclipse: java.io.Console support in Eclipse IDE