For loops
In this section, we're going to take a quick look at for
loops. We use for
loops to solve a common problem in Java in a very semantically elegant manner. These loops are appropriate when we need to iterate a variable to count how many times we've looped.
To start off, I've written a very basic program using a while
loop; it prints the values 1
through 100
to the window on our screen. Once you've hashed out in your mind how this while
loop is working, we'll write the same loop with a for
loop so that we could see how the for
loop is more elegant in this particular instance. Let's comment out our while
loop so that we can still see it as shown in the following screenshot without having it execute any of its code and begin writing our for
loop instead :

The basic syntax of a for
loop looks very similar to that of a while
loop. We have the reserved keyword, two parentheses in which we'll put some information that the loop needs, and the code block that we're going to loop through. Unlike...