2

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++;
   }
}
hologram
  • 533
  • 2
  • 5
  • 21
  • 1
    You can't have a statement after your return statement. It will never get executed as it is unreachable (your code will have returned execution from the method already) – Mr Moose Nov 30 '12 at 02:19

2 Answers2

10

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++;
}
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • 2
    Yes, and the routine will do at most one (partial) iteration. `if (count < deliveredList.size())` would work just as well. – Hot Licks Nov 30 '12 at 02:03
  • dbaseman is right. You should try `count++;` before the return statement, if that still works for what you are trying to do. – hologram Nov 30 '12 at 02:04
0

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;

Extreme Coders
  • 3,441
  • 2
  • 39
  • 55