8

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

Bakudan
  • 19,134
  • 9
  • 53
  • 73
Enthusiastic
  • 549
  • 4
  • 8
  • 23

5 Answers5

6

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.

  • In my case in Linux console when i run the script from run.sh i got `NullPointerException` after removing `"&"` from end of my script and remove `nohup` from the beginning the error gone away. good-luck – Saman Salehi Aug 07 '18 at 04:52
3

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.

Community
  • 1
  • 1
Renato Lochetti
  • 4,558
  • 3
  • 32
  • 49
3

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!

Rookie Programmer Aravind
  • 11,952
  • 23
  • 81
  • 114
  • Well, you're right. It works from windows console. But the problem here is, OP is using Eclipse IDE. And Eclipse IDE does not have a `System.console()`. It's a known bug: - https://bugs.eclipse.org/bugs/show_bug.cgi?id=122429 – Rohit Jain Jan 21 '13 at 13:11
  • @RohitJain, I said the same thing his IDE doesn't use console. But you can run any java compiled code from command prompt. That's the beauty of Java! – Rookie Programmer Aravind Apr 22 '14 at 13:39
0
import java.io.*;

public class ConsoleExTest {

    public static void main(String[] args) throws Exception {
        Console c = System.console();
        String uname = c.readLine("User Name:");
        char[] pwd = c.readPassword("Password:");
        String upwd = new String(pwd);
        if (uname.equals("chenna") && upwd.equals("chenna")) {
            System.out.println("User is valid");
        } else {
            System.out.println("User is not valid");
        }
    }

}

Note:

System.console(); return null so we will get

Dmytro Dadyka
  • 2,208
  • 5
  • 18
  • 31
0

The cause of this problem has already been mentioned in other answers, but I would like to add one possible solution.

There is a library that can be used as a replacement for java.io.Console that mitigates the problem: https://codeberg.org/marc.nause/console-with-fallback

Petra Minaler
  • 91
  • 1
  • 8