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.
Since you’ve mentioned in a comment that you’re using Eclipse, it appears that there is currently no support for
Consolein Eclipse, according to this bug report.The
System.consolemethod returns a console associated with the current Java virtual machine, and if there is no console, then it will returnnull. From the documentation of theSystem.consolemethod:Unfortunately, this the correct behavior. There is no error in your code. The only improvement that can be made is to perform a
nullcheck on theConsoleobject to see if something has been returned or not; this will prevent aNullPointerExceptionby trying to use the non-existentConsoleobject.For example: