Java Notes
'for' Loop
Purpose
The for statement is similar to the while statement, but it is often easier to use if you are counting or indexing because it combines three elements of many loops: initialization, testing, and incrementing.
General Form
The for and equivalent while statements have these forms.
for (init-stmt; condition; next-stmt) { body } |
init-stmt; while (condition) { body next-stmt; } |
There are three clauses in the for
statement.
- The init-stmt statement is done before the loop is started, usually to initialize an iteration variable.
- The condition expression is tested before each time
the loop is done. The loop isn't executed if the boolean expression
is false (the same as the
while
loop). - The next-stmt statement is done after the body is executed. It typically increments an iteration variable.
Example - Printing a table of squares
Here is a loop written as both a while loop and a for loop. First using while:
int number = 1; while (number <= 12) { System.out.println(number + " squared is " + (number * number)); number++; }
And here is the same loop using for.
for (int number = 1; number <= 12; number++) { System.out.println(number + " squared is " + (number * number)); }
Example - Counting doubled characters
This code will look at each character in a string, sentence, and count the number of times any character occurs doubled.
String sentence = ...; int doubleCount = 0; // Number of doubled characters. // Start at second char (index 1). for (int pos = 1; pos < sentence.length(); pos++) ( // Compare each character to the previous character. if (sentence.charAt(pos) == sentence.charAt(pos-1)) { doubleCount++; } }
Summary
The for loop is shorter, and combining the intialization, test, and
increment in one statement makes it easier to read and verify that it's doing
what you expect.
The for loop is better
when you are counting something.
If you are doing something an indefinite number of times,
while
loop may be the better choice.