A loop consists of three major parts:
Different constructs (do, while,for) all do these, but at different points in the code. Failure to do these could result in infinite loops.
The books first example is to show how you could make a bunch of asterisks,
Say, rather than
g.drawString("********", 10, 10);
we try
Where, in this code did we: initialize the variable, increment it, check for the end of looping?
And here is a very similar example using lines, along with code
Put these ideas together to get some steps
The grammatical structure for a while loop is
For loops are usually used when the number of iterations is known in advance.
Java 1.5 introduced an additional format for for's (used by other languages as well).
The enhanced for is like a for "each" in an array. It goes through each member in the array one at a time (like array.length and i++ by default)
Here is an example from the Java Tutorial:
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
With such a loop, you can also create arrays of Objects from arrays of primitive data types: see autoboxing
Finally, an infinite loop (on purpose)
for ( ; ; ) { // infinite loop
// code to do here
}