Reputation: 384
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);
}
}
Upvotes: 2
Views: 4869
Reputation: 184
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); } }
Upvotes: 0
Reputation: 20005
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);
}
}
Upvotes: 5