Skip to content

Looping

Estimated time to read: 4 minutes

While Statement

The while loop will evaluate a condition and whilst that evaluates to true, it will execute the code block over and over again.

While Statement example

Below is an example of a while loop. Whilst the value of count is less than n, the statement will loop.

int count = 0;
int n = 20;

while ( count < n ) {
 System.out.print("*");
 count++;
}

If we remove the count++; statement, the loop will never stop running as count will always be equal to 0.

If we set count to 20 before the while statement, the code block will not run at all.

An improved While Statement example

The further your condition evaluation is from the things that affect the condition , the harder it can be to debug. For example count++ is at the end of the statement, though it affects the loop.

This can be improved by moving the unary increment operator to the start of the while loop, so that it is evaluated and applied on each start of the loop.

int count = 0;
int n = 20;

while ( count++ < n ) { // Note the postfix ++. This will increase the value by 1, AFTER it has been evaluated!
 System.out.print("*");
}

Do While Statement

In the while loop, the condition is evaluated first. If the evaluation is false, the body of the loop is never run.

The do while loop, on the other hand, provides a loop that will always run at least once; as it evaluates the condition last. It will continue to run as long as the condition evaluates to true.

int count = 20;
int n = 20;
do {
 System.out.print("DW")
 count++;
} while ( count < n);

For Loop

Whilst while loops are based around the idea of counting and manually updating the integer, for loops are built specifically for this purpose.

The for loop statement was created to help prevent loops which never stop running do to coding error. Its signature takes three expressions, which are separated by semi-colons.

Note! The semi=colons are required, through the expression are optional!

For Loop Example

for (int i=0; i<10; i++) {
 // Code Block
}

The example above will run as long as i is less than 10. it will set i to 0 before it runs the code clock for the first time. At the end of each pass through the block, it will increment i by 1 and re-test.

For Loop Example breakdown

statement Initialise* Test Post block
for (int i=0; i<10; i++)
Initialization
  1. List itemMore than one variable can be initialised during the Initialise phase
Test
  1. Execute the test and evaluate the result
  2. If true, execute the compound statement code block
  3. If false, break and skip the code block
Post Block
  1. If the test evaluated to true and the compound statement code block has run
  2. Process the statement within the post block statement
  3. Go back to the test

Complex For Loop Example

The initialise and increments parts of the for signature can have more than one statement. These statements are separated by commas.

init i, j;
for (i=0, j=2; i < 10; i++, j+=3){
 // i increments by 1 and j by 3 each time this code block completes
}

Enhanced For Loops (for-each loops)

The basic for loop was extended in Java 5 to make it easier to loop through arrays and other types of 'collections. This is known as the for-each loop statement is also known as the Enhanced For loop statement.

The for-each makes it easier to loop through array and collections as anything that implements the iterable interface may be used in this kind of loop

Enhanced Loop / For-each Loop syntax

// General form of the loop: 
for (type_name temporary_variable_name : collection) (
 //  Invoke methods of name
)

Example Enhanced For / For-each loop

The code for looping through different types of collection classes is the same. The compiler is responsible for generating the correct 'standard' code to implement the loop.

String[] sa = {"o1","o2","o3"};

for (String s : sa) {
 System.out.print(s.toString()); //s.toString converts `s` to a string
} // Prints each string stored in the array - Output is o1 o2 o3

Integer [] ia = { 1, 2, 3};

for (Integer i2 : ia) {
// System.out.println(i2.intValue());
// The above can be done by using autoboxing to create the result instead
System.out.println(i2);
// Output is (on a new line each time) 1 2 3
}

Break

When looping, there are reasons to escape the loop. In this case, the break; statement will break the application out of the loop. It can be executed in a while, for, do-while or switch structure causes an immediate exit from the structure / code block.

Break example

The example below uses break; to cause an immediate exit

int count = -1;
 while ( count++ <= endValue)
  int someVar = readData();
  if ( someVar == badValue);
   break;
  }
  System.out.println (count);
}

There may be times where a break in a structure is not the best use case. Imagine needing to go through a Java class file, printing it line by line, but ignoring lines with comments. A break would stop the statement from running entirely. For this, we could use...

Continue

The continue statement when executed in the body of a while, for or do-while structure skips the remaining statements and begins the next iteration of the main statement after processing the post-block statement.

Continue Example

```java for ( count = 1; count <=10; count++){ if ( count == 7) continue; System.out.print(count + ", "); }

// Outputs - 1,2,3,4,5,6,8,9,10