-2

this is my code. please tell me what is wrong here and how to correct it

   public void displayList(){                   //displays items on the list
   Node current = head;

   while(current!=null){
       current = current.next;
       System.out.println(current);
   }
  • Please show us the error you get. Where does Node come from? Presumably it is `javax.xml.soap` – Scruffy Mar 15 '15 at 03:00
  • 1
    The code looks fine. There's only one place that could throw an npe, and there's a check right above it. So it's being thrown somewhere else. Could you match up the line number in the stack trace to your source code, and include that line in your question? (Node is probably a custom class not included in this sample, which is fine.) – mk. Mar 15 '15 at 03:02

1 Answers1

-1

For starters, in Node current = head;, head does not exist unless it is a predefined field.

Fields are sometimes not initialised by accident. Watch out for that.

Scruffy
  • 580
  • 8
  • 23
  • If it didn't exist, they'd get a compilation error, not a runtime exception. If `head` does exist and isn't initialized, it still couldn't cause an NPE here, at least not in the code posted. – Sotirios Delimanolis Mar 15 '15 at 03:17
  • @SotiriosDelimanolis OP hasn't given their error. It could be a comp. error. – Scruffy Mar 15 '15 at 03:17
  • I'm assuming from the title _shown below is my method but it gives a null pointer exception_ that they got a `NullPointerException`. – Sotirios Delimanolis Mar 15 '15 at 03:19