I have the following problem: method readLine()
or nextLine()
, nextInt()
, etc. throw an exception: NullPointerException
.
I use the NetBeans IDE (if it matters).
public static void Reading()
{
String qq;
qq = System.console().readLine();
System.console().printf(qq);
}
NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.
When a project is ran from inside IDEA, System. console() returns null. According to the Console's API docs: 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.
What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.
Some IDEs don't provide a console. Note that System.console()
returns null
in these cases.
From the documentanion
Returns:
The system console, if any, otherwise null.
You can always use System.in
and System.out
instead, as follows:
String qq;
Scanner scanner = new Scanner(System.in);
qq = scanner.nextLine();
System.out.println(qq);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With