Transcript for:
Mastering Enhanced For Loops in Java

Hi, I'm Dr. Karen Agar, and this video discusses enhanced for loops, also known as for each loops in Java. So the purpose of an enhanced for loop is a way to easily ensure that you have iterated through all items in a collection. In this video, we're going to discuss enhanced for loops using arrays. Arrays are typically the first collection that new programmers are exposed to, but note that we could use an enhanced for loop for any type of collection that we learn later on. So when coding an enhanced for loop, first ask yourself the following two questions.

Question number one, what is the name of the collection or currently the array that I want to iterate through? Question number two, what type are the individual elements in that collection? So for an example, here I've got a double array named interest rates, and you can see that it stores four different doubles in memory.

In a little bit, our task is going to be to print all the items in the interest rates array to the console using an enhanced for loop. For now, let's take a closer look at this double array named interest rates. We can see that it holds enough space for four doubles.

And here's what it would look like in memory. We have a variable name called interest rates and it points to somewhere in memory in your computer where you have enough space to hold four different doubles and you can see that I've annotated them with their indices here. Now note that technically interest rates holds the memory address for where in your computer there is enough space to store these four doubles.

That's why when you print out something like system.out.println interest rates, you're going to get an ugly combination of letters and numbers. And again, that is just the memory address for where these doubles are stored. So coming back to our problem, now hopefully we can answer these questions a little bit better.

The name of the collection I want to iterate through, it is called interest rates. And what? What type are the individual elements of the collection?

Well, in this case, each individual element is by itself just a double. Once I have the answer to these two questions, it becomes pretty easy to create an enhanced for loop. Note that it's just a different syntax than you're used to, but once you get the hang of it, these actually become preferred for a number of problems.

To create an enhanced for loop. The basic structure is we use the keyword for just like we typically would with a normal for loop. However, we have a colon here that separates two different parts of our for loop.

I always start creating my enhanced for loop from the right hand side of the colon. So over here on the right hand side of the colon, what I put is the name of the collection that I want to iterate through. In this case, the name of our collection was interest rates.

So I'm going to place that here on the right-hand side of my colon. Now I'm going to work on the left-hand side. And basically what I would like to do is grab each individual item out of interest rates. Because we've said that each individual item in this particular collection is a double, I'm going to put the word double right here.

And the last step is I want to actually declare a temporary variable in memory of type double. so that I can hold each value of interest rates there. You can name this whatever you want. I'm going to just call it rate. So what I've done here is I have set up a loop that is guaranteed to grab each double in the collection interest rates, and that double will be stored in a variable, a temporary variable here called rate.

The first time that we go through this loop, Rate is going to have the value of 2.9, the next time 3.5, then 4.8, 6.7, and so on. Now that I've set this loop up to iterate through the array, in order to print all the items in the interest rates array, I could just add a statement in here that said system.out.println rate, and it would print the current value. So here's an example where I've added this system.out.println rate for each. rate in interest rate. And now I'd just like to walk through what that looks like in memory.

So again, here was our array named interest rates. Got my four different doubles inside here at these different indices. And when I create this for each loop or enhanced for loop, note that this looks a lot like declaring a new double. And in fact, it is somewhere else in memory. It creates enough space to store a single double and we're going to call it rate.

Now, initially, we don't have anything in that with doubles. The initial value is zero. But when we start actually iterating through this loop, but this time it's going to grab the value at the next index.

holding 3.5. Similarly, through the third iteration, you're going to grab the value 4.8 stored in rate, and then 6.7 will be stored in rate for that final iteration. Again, by just having the statement in here, system.app.println rate, this would accomplish the task of printing each individual element to the console one at a time.

So let's practice creating an enhanced for loop one more time. Here I have a string array named colors and you can see here that I've got all the different colors of the rainbow stored inside I don't need to think about the length or anything, but I do need to think about those two questions The first question was what was the name of the collection? I want to iterate through it's called colors and the second question What type is each individual element of this array and we can see here clearly that each type is a string.

Now following that example, I'm going to start creating my enhanced for loop. I always just put a lot of blanks in here when I show how to program. That way, I can work on this right hand side first. So if you'll recall, we put the name of the collection we wanted to iterate through on the right hand side of this colon. So I would like to iterate through colors, and each time I iterate, I want to grab a single string.

And we can name it whatever we want here. In this case, I'm just going to name it current color. Note that I am still a big advocate for using good variable names here. Now, depending on what the problem was asking us to do, we could do something different with color.

In this case, I'm just going to print it out to the console, current color. Again, this first iteration, current color. should store the value red. The next time enough space for a string but current color should store the value orange then yellow green blue and so on and you can see that I am printing them to the console.

This will print them on a new line but note I could do any kind of string thing I wanted with them because current color is just a string and again the first time just has the value red in it. I can do anything here that I would typically do with a string, like let's say currentColor.char at 0. That's going to grab the first character of currentColor, which is r, print it to the console. But when I come back through with orange, it's going to grab the first character of orange, which is o, print it to the console. And so if I do it like this, you can see that it's printing out just the acronyms. So a common question is, can we just forget about normal for loops now that we know about these neat enhanced for loops?

The answer is no. We need to be very cautious when we use these enhanced for loops and only use them for retrieving values. Note that this is true for primitive types, all of those types beginning with a lowercase letter in Java, and strings, but will behave differently with reference types. This video does not discuss the way this would work with reference types. So a couple examples here.

It is completely okay to use an enhanced for loop when you're printing values. When you're printing something, you're just retrieving the current value. Or when you're searching through a collection for a value, that's okay too. You can just grab those values, search through them.

This includes problems like finding the max or min again. Typically, in all of these scenarios, I am only retrieving the values in the array, but I am not updating them. So that brings me to when I do not want to use Enhanced For Loop. Anytime you want to update a value in the collection, an Enhanced For Loop will actually not let you update a value in the collection. And then obviously anything that requires indices.

So for example, if I wanted to loop through a collection and print that. index for a given value I was searching for. I don't have an index. I don't have that count controlled loop with a for each loop.

So that would not be my choice here. Just to kind of solidify this one more time, we're going to look at an example of when not to use enhanced for loops and why not to do that. So here if we go back to our example where we had a double array named interest rates, and here is my enhanced for loop created to loop through interest rates, grabbing each double out one at a time and storing them in a variable named rate.

This was totally okay when all I wanted to do was print out the rate. Here I've got system.out.println rate. However, if the problem changed and asked us to increase all rates by 0.2, Then we would have an issue because if I did something like this, rate equals rate plus 0.03.

Note that while this does not give us an issue per se, it actually will not correctly update the values stored in the array. To prove it, I will create another. Quick for each loop, that will just print out system.out.println each rate. This loop, I would like it to increase all rates by 0.03, making this 3.2, 3.8, and so on. But you'll see that when I actually print the rates after trying to do this, they have not changed.

I'll run that, let you see that these rates are actually completely unchanged. And now let's talk about why that happened. So going back to our discussion about memory, here I've updated my loop to include this rate equals rate plus 0.03. And in the first iteration of this loop, rate has the first value, which is 2.9. So when I get to this line of code, rate equals rate plus 0.03, it does in fact do what it says and increment rate.

by 0.03. Rate should have a value of approximately 3.2 stored in memory now, but note how this did not update what was in interest rates. This becomes part of a larger discussion about how primitive types work in memory.

We're not going to get too heavily into this discussion in this video. Do note that these are two totally different places in memory for a double. Here I've got enough space to store a double name rate, and by updating this variable, it does not have consequences on the variable, this double that it came from.

Again, I want to note that these are the rules for primitive types and strings, but other reference types that you may or may not use later on do not behave exactly like this. That is it for enhanced for loops. Thanks.