for
loops
The final control structure we’ll be seeing in this article is actually just a more advanced version of a while
loop, called a for
loop. The relatively complex syntax tends to scare away beginners; additionally, the fact that any for
loop can also be written as a while
loop makes it especially tempting to simply not use this particular control structure. Nevertheless, the for
loop provides a nice shortcut for the most common application of while
loops, so in my opinion it’s worthwhile learning. Here’s what the syntax looks like:
for (initialize; condition; update) {
// loop body
}
In the above, initialize
is a statement that is executed once, just before the condition is checked for the first time. It is usually used to set up a counter variable for the loop. condition
is simply the condition that determines when to stop executing the loop (it works exactly the same as the condition in a while
loop). Finally, update
is a statement that will be executed after the loop body and before the condition is re-checked. It is commonly used to update the counter variable. Figure 2 illustrates how a for
loop works.
To demonstrate a for
loop in practice, I’ve adapted the Countdown
program above to use a for
loop instead of a while
loop:
1 /**
2 * Countdown.java
3 * A simple Java program that counts down from 10.
4 */
5
6 class Countdown {
7 public static void main(String[] args) {
8 System.out.println("Countdown to liftoff...");
9
10 for (int count=10; count>0; count=count-1) {
11 System.out.println(count + "!");
12 }
13
14 System.out.println("Liftoff! We have liftoff!");
15 }
16 }
The actual code used by this program is not so different from the original version with the while
loop! The creation and initialization of the count
variable has become the ‘initialize’ statement in the for
loop, while the command from the loop body that subtracts 1 from the value of the count
variable has become the ‘update’ statement. The condition and the remaining line of the loop body remain unchanged. What a for
loop lets you do is combine all of the commands having to do with the initialization, checking, and updating of the counter variable (count
, in this case) into a single line, making the code in general easier to read.
Even though any for
loop could be expanded out into a while
loop with the appropriate statements before the loop and at the end of the loop body, it is common practice (and generally tidier) to express any loop that uses a counter variable as a for
loop.
Summary and Further Reading
We’ve covered a lot of ground in this article; it’s a shame most of it had to be so dry!
We looked at how variables let you store data for use in calculations, how that data can come in the form of a handful of data types, what operators are available for putting pieces of data together and getting a result, and what control structures let you make programs that do something other than go in a straight line. Unfortunately, these are by far the least exciting aspects of any programming language; so if I’ve bored you, I apologise.
The good news is that I’ve now covered most of the mundane details of the Java language, and you should now be ready to make the leap into the world of object-oriented programming! It’s no coincidence, then, that the next article in this series will cover the concepts of object oriented programming and how they apply in Java. And I’ll finally answer the Big Question: how can you compare two Strings together to see if they match? Don’t tell me you’re not dying to know!
If you’re keen to get a head start, the book “Beginning Java Objects” from WROX Press is an excellent read that will have you weaving webs of Java classes like a pro. Look for a review around the same time as the next instalment in this series!
Kevin Yank is an accomplished web developer, speaker, trainer and author of Build Your Own Database Driven Website Using PHP & MySQL and Co-Author of Simply JavaScript and Everything You Know About CSS is Wrong! Kevin loves to share his wealth of knowledge and it didn't stop at books, he's also the course instructor to 3 online courses in web development. Currently Kevin is the Director of Front End Engineering at Culture Amp.