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!
return false is not breaking your loop but returning control outside back.
Yes, usually (and in your case) it does break out of the loop and returns from the method.
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).
return will exit the entire method you are currently executing (and possibly return a value to the caller, optional).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With