Unless you are developing a very specific application, the Console
object returned by System.console()
is not the one you should use to retrieve user input.
This is System.console()
definition:
/**
* Returns the unique {@link java.io.Console Console} object associated
* with the current Java virtual machine, if any.
*
* @return The system console, if any, otherwise <tt>null</tt>.
*
* @since 1.6
*/
public static Console console() {
if (cons == null) {
synchronized (System.class) {
cons = sun.misc.SharedSecrets.getJavaIOAccess().console();
}
}
return cons;
}
It may return null
: Returns the unique object associated with the current Java virtual machine, if any.
Here you can find the reason why it can be null
:
Whether a virtual machine has a console is dependent upon the underlying platform and also upon the manner in which the virtual machine is invoked. If the virtual machine is started from an interactive command line without redirecting the standard input and output streams then its console will exist and will typically be connected to the keyboard and display from which the virtual machine was launched. If the virtual machine is started automatically, for example by a background job scheduler, then it will typically not have a console.
As other answers and comments suggest, you should use System.in
, being Scanner
an easy to use tool to read lines and tokens.