3

I tried the java.io.Console API using eclipse. My sample code follows.

package app;

import java.io.Console;

public class MainClass {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Console console = System.console(); 
        console.printf("Hello, world!!");
    }

}

When I tried running the example, I got the following error.

Exception in thread "main" java.lang.NullPointerException at app.MainClass.main(MainClass.java:11)

Where did I go wrong? Thanks.

Bharani
  • 303
  • 1
  • 8
  • 16

3 Answers3

7

Since you've mentioned in a comment that you're using Eclipse, it appears that there is currently no support for Console in Eclipse, according to this bug report.

The System.console method returns a console associated with the current Java virtual machine, and if there is no console, then it will return null. From the documentation of the System.console method:

Returns the unique Console object associated with the current Java virtual machine, if any.

Returns:

The system console, if any, otherwise null.

Unfortunately, this the correct behavior. There is no error in your code. The only improvement that can be made is to perform a null check on the Console object to see if something has been returned or not; this will prevent a NullPointerException by trying to use the non-existent Console object.

For example:

Console c = System.console();

if (c == null) {
    System.out.println("No console available");
} else {
    // Use the returned Console.
}
coobird
  • 159,216
  • 35
  • 211
  • 226
0

System.console returns null if you don't run the application in a console. See this question for suggestions.

Community
  • 1
  • 1
McDowell
  • 107,573
  • 31
  • 204
  • 267
  • How to fix this? Should I have to run the application in the command line and not use the RUN button in eclipse? – Bharani Jun 15 '09 at 14:49
  • I updated the answer with a link to a similar question - you can work around it with external consoles, batch files and/or remote debugging. There is also a link to the issue in the Eclipse bug DB. – McDowell Jun 15 '09 at 14:52
0

System.console returns the unique Console object associated with the current Java virtual machine, if any.

you have to test if console is null before using it.

Pierre
  • 34,472
  • 31
  • 113
  • 192