0

I am trying to retrieve a string from my console with System.console().readline(); but when i run the program to get the string it throws a exception.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

How can i get data from my console and put it in a string? This is what i tried:

String response = System.console().readline();
System.out.println(response);
4

2 Answers 2

2

Use Scanner for this purpose.

Scanner sc = new Scanner(System.in);
String st = sc.next();

You can use sc.nextInt() to get integer value from console.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

Nice explanation why it doesn't work!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.