zzxjoanw
zzxjoanw

Reputation: 384

how to check if an object's property is null

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

Answers (2)

Rahul Vashishta
Rahul Vashishta

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

JuniorCompressor
JuniorCompressor

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

Related Questions