golddove
golddove

Reputation: 1206

Return in if statement causing unreachable code error

The following code:

public static void print(ListNode p)
{
    System.out.print("[");
    if(p==null);
    {
        System.out.println("]");
        return;
    }
    ListNode k = p.getNext();
    //more code
}

causes the following compile error:

 ----jGRASP exec: javac -g Josephus_5_Rajolu.java

Josephus_5_Rajolu.java:53: error: unreachable statement
            ListNode k = p.getNext();
                     ^
1 error

 ----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.

Why is that happening? I am only returning if p = null. I want to do my other code if p!=null. Why is it unreachable?

Upvotes: 1

Views: 2044

Answers (6)

Madbreaks
Madbreaks

Reputation: 19539

There's a semicolon after your if statement.

Upvotes: 12

Where are you instantiating ListNode K?

It looks like to me that the issue is ListNode k is not being instantiated.

I think you need something like this. ListNode k = new ListNode();

Are you creating this within your class?

Also you have a ; after if(p==null); That needs to be removed.

Upvotes: 1

Drew
Drew

Reputation: 24949

remove the semicolon after your if

Upvotes: 1

zaffargachal
zaffargachal

Reputation: 810

there is ; after if statement remove it it will work :)

Upvotes: 3

Barracuda
Barracuda

Reputation: 101

maybe the ';' at the:
if(p==null);

Upvotes: 2

Eugene Retunsky
Eugene Retunsky

Reputation: 13139

if(p==null); <-- remove the semicolon at the end

Upvotes: 2

Related Questions