Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console Input error java.lang.NullPointerException

Tags:

java

io

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

like image 383
Enthusiastic Avatar asked Jan 21 '13 13:01

Enthusiastic


People also ask

How do I fix Java Lang NullPointerException error?

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.

What does it mean when it says Java Lang NullPointerException?

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.

How do I ignore Java Lang NullPointerException?

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.

How do you raise the NullPointerException in Java?

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.


3 Answers

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.

like image 108
Alankar Srivastava Avatar answered Sep 23 '22 19:09

Alankar Srivastava


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.

like image 43
Renato Lochetti Avatar answered Sep 19 '22 19:09

Renato Lochetti


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!

like image 36
InfantPro'Aravind' Avatar answered Sep 23 '22 19:09

InfantPro'Aravind'