2

I'm trying to check whether a property is null, but I get a null pointer exception. What's the right way to do this?

private void recursePrintList(myNode head)
{
    if(head.next == null) //NullPointerException on this line
    {
        System.out.println(head.value);
    }
    else
    {
        System.out.println(head.value);
        recursePrintList(head.next);
    }
}
zzxjoanw
  • 374
  • 4
  • 16
  • If `head` is null, then `head.next` will throw a `NullPointerException` – Powerlord Mar 23 '15 at 17:17
  • 2
    possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – fabian Mar 23 '15 at 17:17

2 Answers2

5

You have to check if head is null at the start of your method. Also you can further simplify your recursive print:

private void recursePrintList(myNode head) {
    if (head != null) {
        System.out.println(head.value);
        recursePrintList(head.next);
    }
}
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
0

You should check the value of head as if null is not equal to head then do the operations.

ivate void recursePrintList(myNode head) { if ( null != head) { System.out.println(head.value); recursePrintList(head.next); } }
Rahul Vashishta
  • 184
  • 2
  • 6