Josh Morrison
Josh Morrison

Reputation: 7634

What causes this NullPointerException in my Java program?

import java.io.*;
public class listjava
{
   public static void main(String args[]){
       Console c = System.console();
       char[] pw;
       pw = c.readPassword("%s","pw: ");
       for (char ch: pw)
           c.format("%c ",ch);
       c.format("\n");

       MyUtility mu = new MyUtility();
       while(true)
       {
           String name = c.readLine("%s","input?: ");
           c.format("output : %s \n",mu.doStuff(name));
       }
    }
}

class MyUtility{
    String doStuff (String arg1){
        return " result is " + arg1;
    }
}

I got an error like this:

Exception in thread "main" java.lang.NullPointerException
   at listjava.main(listjava.java:7)

Why is my program wrong?

Upvotes: 2

Views: 591

Answers (2)

templatetypedef
templatetypedef

Reputation: 373382

According to the Javadoc for System.console():

Returns: The system console, if any, otherwise null.

So I suppose that System.console() is handing back null and your line

pw = c.readPassword("%s","pw: ");

is therefore dereferencing null. I'm not sure what fix you might want to use; perhaps reading from System.in instead?

Upvotes: 3

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181460

System.console() is returning null.

Quoting Java's documentation:

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

So, there are probably no console associated to your JVM. You are probably running your program within Eclipse or other IDE. Try running your program from your system's command line. It should work.

To run your program from the command line.

  1. Go to directory where listjava.class resides
  2. Run java's interpreter

    $ java listjava

Upvotes: 7

Related Questions