Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return true and then break from a for loop

Tags:

java

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!

like image 834
Avishay28 Avatar asked Dec 01 '15 13:12

Avishay28


People also ask

Does return false break a for loop?

return false is not breaking your loop but returning control outside back.

Does returning a value break a loop?

Yes, usually (and in your case) it does break out of the loop and returns from the method.

Can we return from a for loop?

It is good practice to always have a return statement after the for/while loop in case the return statement inside the for/while loop is never executed. Otherwise, a compile-time error will occur because the method cannot return nothing (unless it has the Java reserved word "void" in the method header).

Does return break a method?

return will exit the entire method you are currently executing (and possibly return a value to the caller, optional).


1 Answers

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.

like image 63
Eran Avatar answered Sep 27 '22 22:09

Eran