Here is my code:
System.out.println("Enter Username: ");
String unm=System.console().readLine();
System.out.println("Enter Password: ");
char[] pwd=System.console().readPassword();
System.out.println("Welcome: " + "" + " Your password is " + new String(pwd));
Why am I getting this error?
Enter Username:
Exception in thread "main" java.lang.NullPointerException at Cons.main(Cons.java:13)
From the Javadoc:
Returns the unique Console object associated with the current Java virtual machine, if any.
If there is no console associated to the JVM, the pointed line is the call of a method on a null object, hence the exception.
How do you launch your application?
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.
If you want to read the username from the standard input, you could use this code:
try {
System.out.print("Enter Username: ");
InputStreamReader streamReader = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(streamReader);
String username = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
That is because System.console()is returning null. The official documentation states (bold is mine to emphasize):
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.
You can see it here.
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