Java Loops

All tutorials are implemented in text (here), and also with exercises and multimedia in the Tutorial Player. The main home page has a search engines, and more facilities.

for
while
do
Breaks

for

Like other languages, the for loop is implemented as

for (initial value; end condition; increment or decrement) {

}

Example

for (int i=0; i < numberEmployees;i++) {
   if (employeeNames[i] == thisName) {
               customerLetters.sendLetter(thisName);
    }
}

while

The while is a loop based on a condition:

i=0;
while (i < numberEmployees) {
if (employeeNames[i] == thisName) {
               customerLetters.sendLetter(thisName);
    }
i++;
}

do

do is implemented when at least loop execution is needed.

i=0;
do {
if (employeeNames[i] == thisName) {
               customerLetters.sendLetter(thisName);
    }

} while ( numberEmployees < i++)

Note the i++ is needed to ensure that the variable i is tested against numberEmployees before the addition.

Breaks

The break statement causes the loop to stop, and execution is resumed at the next instruction of the loop. Continue starts the loop at the next iteration.

Labels can be used.

checkNames:
while (i < numberEmployess) {
  if (employeeName[i] = deadPersonName) {
    databaseError = true;
    break checkNames: // if a deadPerson is found, then database corruption occurred, and processing stops  
  }
i++;
}