Avishay28
Avishay28

Reputation: 2456

Return true and then break from a for loop

I'm new to java. I have been trying to do something without success. Basically What I want to do is to create a method that return true or false. The method gets some parameter, checks if a certain array is full, if not it pushes the parameters to the to the first cell that isn't empty, return true and NOT keep checking for the rest of the array. If the array is full it just return false. This is the code:

public boolean add( param1, param2, param3 ){
 for( int i = 0; i < array.length; i++ ){
   if ( array[i] == null ){
     array[i] =  new SomeObject( param1, param2, param3 ); 
     return true;
     break;
     }
  }
  return false;
}

But I get error- "unreachable statement" for "break;". Any help?

Thanks in advance!

Upvotes: 9

Views: 16405

Answers (3)

Codor
Codor

Reputation: 17605

As some people insist on a function having a single point of return, the function can be reformulated as follows, matching the apparent expectation of the original question.

public boolean add( param1, param2, param3 ){
    boolean result = false;
    for( int i = 0; i < array.length; i++ ){
        if ( array[i] == null ){
            array[i] =  new SomeObject( param1, param2, param3 ); 
            result = true;
            break;
        }
    }
    return result;
}

Upvotes: 2

Aniruddha Sinha
Aniruddha Sinha

Reputation: 799

Yes, Because the moment the control encounters a return statement it just gets out of a method, switch or a loop etc. so any code written below the return statement will be just "unreachable." So its always advisable to place the return at the last of the block (of a method) unless required and it is also advisable not to write any code after the return statement in a single block lest you should get an error.

Upvotes: 0

Eran
Eran

Reputation: 393986

Since you have a return statement, you don't need to break from the loop, since the return statement ends the execution of the method. Just remove the break statement.

Upvotes: 22

Related Questions