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 OverflowNOTE: 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).
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.
This is a bug #122429 of eclipse
This code snippet should do the trick:
private String readLine(String format, Object... args) throws IOException {
if (System.console() != null) {
return System.console().readLine(format, args);
}
System.out.print(String.format(format, args));
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
return reader.readLine();
}
private char[] readPassword(String format, Object... args)
throws IOException {
if (System.console() != null)
return System.console().readPassword(format, args);
return this.readLine(format, args).toCharArray();
}
While testing in Eclipse, your password input will be shown in clear. At least, you will be able to test. Just don't type in your real password while testing. Keep that for production use ;).
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.
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.*;
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();
}
}
From System#console javadoc:
Returns the unique
Consoleobject 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