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.

3 Answers 3

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.
}
Sign up to request clarification or add additional context in comments.

1 Comment

Just a nitpick, but I'd use System.err.println instead of System.out.println
0

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

2 Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.