Iain Standing
Iain Standing

Reputation: 21

"unreachable statement" when trying to compile a "while" statement

I'm new to Java and working through some coursework. However, on the following piece of code I'm getting the error "Unreachable statement" when trying to compile. Any pointers as to what I'm doing wrong?

public String getDeliveredList() {
   int count = 0;
   while (count < deliveredList.size()){
       return ("Order # " + count + deliveredList.get(count).getAsString());
       count++;
   }
}

Upvotes: 2

Views: 974

Answers (2)

Extreme Coders
Extreme Coders

Reputation: 3521

If you have returned from a function then any statement after the point from where the function returned are basically unreachable statements and the compiler will issue an error on such statements.

However the following code will not issue an error inspite of statements written after return

void max(int a,int b)
{
    if(a>b) 
    {
        System.out.println(a+" is greater");
        return;
    }

    System.out.println(b+" is greater");
    return;
}

This is because the first return statement is written within a nested scope and not immediately visible in the function scope. The program execution will only pass through first return statement when a>b. If it is not so then that block of codes is never executed. So in spite of having statements after return, the code is compile-able;

Upvotes: 0

McGarnagle
McGarnagle

Reputation: 102793

Once you've returned from the function, logically it can no longer execute anything after that point -- the count++ statement will never be reached.

while (count < deliveredList.size()){

   // function always ends and returns value here
   return ("Order # " + count + deliveredList.get(count).getAsString());

   // this will never get run
   count++;
}

Upvotes: 10

Related Questions