Search code examples
javaunreachable-statement

Unreachable statement after conditional


The following code gives the error: Unreachable statement for current= current.getmNextNode(); How can it be solved?

public int indexOf(E element) {

    Node current = head;
    for (int i = 0; i < size; i++) {
        if (current.getmElement().equals(element)) ;
        {
            return i;
        }
        current = current.getmNextNode();
    }

    return -1;
}

Solution

  • You have an extra semicolon between the if statement, and what is supposed to be its body. The way you wrote it, the return i; statement will be executed regardless of the result of the condition.

    public int indexOf(E element) {
      Node current = head;
    
      for (int i = 0; i < size; i++) {
        if (current.getmElement().equals(element)) {
          return i;
        }
    
        current= current.getmNextNode();
      }
      return -1;
    }