I think it's time for us to have an in-depth conversation about Java loops. So, today's Java tutorial will be structured around these useful control structures. This topic is yet another one of those that I would classify as “fundamental” when trying to learn how to program with Java.
I've touched on this topic briefly back in my Java tutorial about control structures, so now it's time to dig deeper!
What kinds of Loops are there in Java?
There are three types of loops:
- For Loops
- While Loops
- Do..While Loops
For Loops
In my opinion, the For Loop is the most common of all three types of loops. It is structured around a finite set of repetitions of code. So if you have a particular block of code that you would want to have run over and over again a specific number of times the For Loop is your friend. A common use of this loop is when you have a List
of items that you need to “iterate” over for processing. Let's say you have a List
of Contact
s in your address book, and you want to send an email to all of them. You could iterate over your List
of Contact
s and extract each e-mail address, like so:
public class QuickTest {
public static void main (String[] args)
{
// get some pre-existing list
List contactList = getContacts();
// find out how big the list is
Integer sizeOfList = contactList.size();
// initialize your TO: field for the email addresses
String emailToField = "";
// iterate through the contacts and extract
// the email addresses for the TO: field
for (int i=0; i getContacts()
{
List contacts = new ArrayList();
contacts.add(new Contact("abc@abc.com"));
contacts.add(new Contact("abc1@abc.com"));
contacts.add(new Contact("abc2@abc.com"));
contacts.add(new Contact("abc3@abc.com"));
contacts.add(new Contact("abc4@abc.com"));
return contacts;
}
private static class Contact
{
private String emailAddress;
public String getEmailAddress() {
return emailAddress;
}
public Contact (String email)
{
this.emailAddress = email;
}
}
}
If you were to run this code, you would see the following output:
abc@abc.com, abc1@abc.com, abc2@abc.com, abc3@abc.com, abc4@abc.com
As you can see here, we now have a List
of (fake) email addresses that we could copy/paste into an email program in the “To:” field, fill in a subject/body and fire off an email. A similar approach is used in the real world to parse a List
of email addresses that are stored in a database. All of this made easy by using the For Loop!
While Loop
Another looping strategy is known as the While Loop. The While Loop is good when you don't want to repeat your code a specific number of times, rather, you want to keep looping through your code until a certain condition is met (or rather, keep looping while a certain condition is true).
A typical case for using a While Loop is when reading a file.
BufferedReader input = new BufferedReader(new FileReader(new File("C:\testFile.txt")));
try
{
String line = null;
// Here we use a while loop because we won't
// know many lines the file has when this
// program runs.
while ((line = input.readLine()) != null)
{
System.out.println(line);
}
}
finally
{
input.close();
}
So you see here that we've used a While Loop, and although it's not entirely apparent, we will be iterating over this loop until the end of the file that we've read in (with the BufferedReader
).
For simplicity sake, let me show you a more basic version of the While Loop… now you wouldn't normally use this particular implementation of the while loop, as it would just keep running and never end… but this is just an example:
while (true)
{
// do something
}
So as you can see above, the structure of the while loop is pretty simple. There's the keyword while
followed by a condition inside round braces (/*condition*/)
. The code flow will be as follows:
- Check the while loop condition, if false, don't execute any code inside while block
- if condition is true, execute code inside while block
- repeat step 1
So, given this workflow, can you see how the second While Loop example will run forever? If you happen to try and test this out, you'll see that your computer will start to slow down and perhaps you'll hear the CPU fan fire up and make some noise! Don't worry, you can just click the red stop button in your console window to stop your infinite loop… or just close your SpringSource Tool Suite (STS). The key thing to note is that using While Loops is slightly dangerous for your code, as you can get stuck in an infinite loop if you don't give the right condition statement. I actually brought an entire QA environment to its knees once when I was a junior programmer, so don't worry if you do the same, everyone needs to learn somehow right?
Do..While Loop
This last type of loop isn't used very often, mostly because it does the same thing as a While Loop with one difference. Remember our workflow for the While Loop? Well, the Do..While Loop does it just a little bit different:
- Execute code in the Do..While block
- Check the Do..While loop condition, if false exit Do..While block
- If condition in Do..While loop is true, repeat step 1
You see the difference? The Do..While Loop will always execute the code in your block at least once. Whereas, the While Loop could skip the whole block of code if the condition is false the first time around. So like I mentioned already, the Do..While Loop isn't used too often, and I'm sure there are situations where it would make sense to use one, but I haven't hit that situation just yet in my coding adventures :)
Bonus Content
Now that you've seen the different types of loops that exist in Java, how about we get a little fancy with our code? Let's say we have a requirement that says you need to write some code that will tell us if a particular Contact
‘s email address exists in a List
of Contact
s. Sure we could write a For Loop or a While Loop that would iterate through a list to find an email address, but wouldn't it be silly if we found the particular email address we were looking for, and then just kept on looking through the rest of the List
? What happens if the List
of email addresses had a million Contact
s, and we had our answer on the 2nd Contact
! That would be quite the waste of time right? Right! So here's a neat trick:
The break
statement
Never fear, there's an app… err… a keyword for that! The break
keyword allows you to exit a loop whenever you like, so let's implement that requirement for finding an email address:
public boolean emailAddressExists(String emailAddress, List contacts)
{
boolean foundEmailAddress = false;
for (int i=0; i
So you see in the code above that if we've found the email address, we break
out of the loop and return the result of our boolean
variable. So now, if we find the email address we're looking for the second time around the For Loop, we don't waste any time! Neat!
But wait, there's more!
The continue
statement
This one is very similar to the break
keyword. You see, like I already mentioned, the break
keyword will terminate the loop that you're currently iterating through, but what if we don't want to terminate the loop, but rather, we just want to go to the next iteration sooner? Well that's what the continue
keyword is for. A common scenario here would be if you had a few conditional statements that were being executed in a particular loop and if one of them resulted in something particular, then you would go to the next iteration of your loop. For example, what if we changed our requirement above to say that we want to not only find an email address, but we want to find someone with a particular name as well? If we know that we only want to exit our loop when we find a contact by the name of "Trevor" who has the email address "tpage@ecosim.ca", then we could just check all the names FIRST, and if it doesn't match what we want, then why would we also check the email address? Here's what the implementation could look like:
public boolean emailAddressExists(List contacts)
{
boolean foundContact = false;
for (int i=0; i
Summary
Great! Now you've been exposed to three types of loops (although, only the For Loop and While Loop are commonly used). You also have an idea of which one to use in certain situations... For Loops should be used when you know exactly how many iterations you'll need, and While Loops should be used when you don't know how many iterations you'll need. And finally, you know how to optimize your loops with the break
and continue
keywords! All that's left is for you to play around with them yourself, so by all means, go nuts :)
As always, if you have any questions, feel free to post them in the comments section below. Or better yet, scroll back to the top of this page and follow me on twitter or facebook (links are on the top right side of the page), and ask me questions on those social networks. I will respond to any and all questions, so please don't be shy people!