tags:

views:

504

answers:

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.

A: 

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

McDowell
How to fix this? Should I have to run the application in the command line and not use the RUN button in eclipse?
Bharani
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
A: 

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
+2  A: 

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
Just a nitpick, but I'd use System.err.println instead of System.out.println
R. Bemrose