I have tried code:
import java.io.Console;
public class Default
{
public static void main(String args[]) throws IOException
{
Console console = System.console();
String testing = console.readLine("Enter Name: ");
System.out.println("Entered Name: "+ testing);
}
}
goes to exception with following error:
Source not found. NullPointerException
I am using Eclipse Juno EE for debugging .. !
And the reference link for above written code is here
In Java, the java. lang. 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.
The java. lang. NullPointerException is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null. Since the NullPointerException is a runtime exception, it doesn't need to be caught and handled explicitly in application code.
Answer: Some of the best practices to avoid NullPointerException are: Use equals() and equalsIgnoreCase() method with String literal instead of using it on the unknown object that can be null. Use valueOf() instead of toString() ; and both return the same result. Use Java annotation @NotNull and @Nullable.
Java For Testers NullPointerException is a runtime exception and it is thrown when the application try to use an object reference which has a null value. For example, using a method on a null reference.
Are you running your program from an ide as console.readLine
returns null
when used from an IDE.
For more details refer to this
If you run it from command line you will not get this error.
System.console()
returns null if there is no console.
You can work round this either by adding a layer of indirection to your code or by running the code in an external console and attaching a remote debugger.
That is because, IDE is not using console !
Go to cmd.exe
type cd <bin path>
hit enter..
now type java <classname>
hit enter
It works!
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