OO Programming with Java


Note on Loops

There are 3 ways to stop a loop:

  1. return will stop by exiting the operation at a specific point.
  2. break will stop by continueing the statements placed after the loop,
  3. continue will avoid the statements placed after this instruction and return to the next index of the loop.

As an illustration, finding a product with its name can be defined in 3 ways:

for(Product book : this)  // 1 //
  if (book.getName().equals(name)) return book;
return null;
Product result=null;      // 2 //
for(Product book : this) 
  if (book.getName().equals(name)) {
    result = book;
    break;
  }
return result;
Product result=null;     // 3 //
for(Product book : this) {
  if (! book.getName().equals(name)) continue;
  result = book;
}
return result;