The for-loop is one of the most important Java control statements.
You will be hard pressed to find an application that doesn't contain a for-loop.
The Java for-loop syntax isn't rocket science either.
You're telling Java I want you to loop over this block, and I want you to do it a set
number of times.
There's two ways to loop using the for loop,
the basic way and the enhanced for loop. In this video
I'm going to show you both, and by the end you should be a pro with the Java for-loop syntax.
In this lesson
we're going to learn about looping, specifically for loops.
We're going to look at how you can control the direction
and the step of the loop. We’ll also cover something called for-each loops,
AKA the enhanced for-loop. When we're done,
you should understand the difference between incrementing and iterating loops.
So let's take a look at loops!
The for-loop is a control statement that tells Java to loop over a Java block.
Usually you loop a finite number of times. The Java for-loop syntax starts
with the keyword
"for". Each basic for-loop has a start,
condition, and step. The start initializes any
variable you require for the loop. This is only one variable.
Other languages do more, Java does one.
That's really all you should need unless you're trying to do something silly-clever
Initialization is run only once for the life of the loop, and it happens when you
start the loop.
The condition tells the loop when it should stop. When this condition evaluates to false,
the looping stops. The step tells the for-loop how it should advance for each
loop.
Surprisingly, all of these are optional.
Here's what it looks like when everything is left out. There is no start,
no stop, and no increment. Just semicolons.
You'd think this wouldn't run, but actually
the opposite is true. This runs forever. We've seen how long that is.
The important thing to note is each piece
of the for-loop is optional. There might be a good reason to leave
everything optional,
but... if you need an empty for loop like this,
I’d just make a while loop with a true condition.
It does the same thing. So lets look at what happens in a for-loop.
The first thing run is the initialization. Here
we are initializing the variable i to 0. Every step we are going to increment i
by 1. I'm using the ++ unary operator here,
but I could also have written i=i+1.
The ++ operator is just more succinct
The condition is, we are not stopping until
i is greater than or equal to 10. The condition here says
i less than 10. That means if i equals 10,
we should not loop. When we first enter the loop, i is
0. The second loop, i is 1 and so on
We continue looping. Every time we loop, the index
i is incremented in value by one. Each loop we check
is i less than 10. Yes, increment i
and loop again. When i is 10, the condition fails.
The loop stops. Let's take a look at this in code
and play with loops a bit. Okay here I've defined a for-loop.
Loops from 0 to 99. It loops from 0 to 99 because
we have i < 100. When it hits 100 you'll stop.
For every iteration of the loop, we're going to print out the value of i.
We run it and as you can see
its printed out all the values up to 99,
exactly as expected. Now in this code we're stepping it one at a time.
We have i++. That auto increments it by 1.
We could also use the urinary operator for addition
and add two to each one. So in this case for every step i is going to step
every even value. Run it and
we get all the even values from 0 all the way up to 98.
We could even step by fives if we want, and as you can see it's
15, 20, 25 all the way up to 95. Another cool thing that we can do
is we can go backwards. So if we set our initial value to 100
then i > 0,
and subtract 1 from each one. We run this
and it counts from 100 down to 1. Since
i cannot equal 0, it has to be greater than 0. Finally if you go back to our
original for loop,
where we're printing every value from 0 to 99, we could also say hey,
if i == 25,
we want to break out. We saw the break statement and the continue statement
in the while loop lesson. They work here too in the for-loops.
in the for-loops. So it goes up to 25 and then breaks out.
One place you'll see for-loops is when you're working with arrays.
It's also one place you often see looping errors.
Let's look at the following example. We have an array. It's got five numbers in it.
Looping over the array, we add one to each
element. When we are done we should have an array that looks like this.
Each element is increased in value by one. Look what happens when we include an
equal sign.
In this case we’re including
5 as an index to update. Our array only has five indexes that go from
0 to 4. 5 will cause an error and your program will crash.
You're gonna see this error often, especially when you're starting out with
java.
Let's intentionally cause this error to see what happens.
So in this case I've created an array with a hundred elements in it.
I am initializing all them to be the value 42,
and I'm going to print out the array. We run it and as you can see
all the values in our array equal 42.
What happens if we accidentially say i <= 100?
In this case its including an extra value that's not part of our array.
This is a very common error, so when we run it we get
"Exception in thread, ArrayIndexOutOfBoundsException, 100"
So what we're saying is we've overrun our array, and the
place that we have in the error is 100. This is a very common error, so I wanted to make
sure that you saw this.
This is a better for-loop.
It's sometimes called the enhanced for-loop.
I don't make this stuff up. The way to read this control statement is,
for each i in array. So when you see the colon
read that as "in". The enhanced for-loop syntax
is the keyword "for", the type for each element in your collection,
and the collection. This loop is better because it doesn't care about an
index.
You don't even need to know how many elements are in the array. You iterate over
each item in the array,
and the compiler takes care of range checking for you. Two catches to this loop.
One, you can't modify each element as you visit it,
and two you don't know the current index.
You can certainly put an index in there on your own, but if you really need to,
just use the normal for-loop. Let's look at the enhanced for-loop in code.
So here's another way to work with for-loops.
This is the enhanced for loop. What we're saying here is, for every
integer in our array, we're going to set it to 42, just like before.
Let's run it, and they're all 0.
So that's one catch when working with the enhanced for-loop. You cannot modify
each individual element. If you need to modify each individual element in your
array,
you're probably better off working with the regular for-loop. This does show you
however
how to use the enhanced for-loop to iterate over an array.
In this case, we could have also done System.out.println (i).
and what this will do is
visit each element in our array. And it prints out zeros
again. We've been playing with numbers, but you can iterate over other
types.
Here's an example of iterating over a character array.
The output would be "a s d f"
I’ll leave it as an exercise for you to type this loop in. If you have questions,
leave it in the comments and I’ll gladly help you out! I'd say that
90% of the time, I use the enhanced for-each loop
and iterate over arrays. The Java for loop syntax is much simpler with enhanced
for-loops
and leads to safer code. That means it’s less likely
to break with weird errors. Both loops are almost
always the same speed. Normal for-loops can be slightly faster
if the array is an array if integers. In other array types
it makes no difference. You really shouldn't worry about it. It's a judgement
call on which one you should use, but
if you can iterate using a for-each instead of incrementing over a
normal loop,
go for the iterations. As always,
if you have questions, leave them in the comments below. And with that,
I'll see you in the next lesson. Hey thanks for watching the video.
There is a quick quiz for this on DeegeU.com if you'd like to gauge how much you learned.
If you like the videos you are seening, please let me know by liking the video
and hitting the subscribe button
for the DeegeU channel on YouTube. I'd really appreciate that. If you have concerns or
questions please leave them in the comments below
or on DeegeU.com. There's a poll on the front page
of DeegeU.com so you can let me know the topics covered
next. Thanks for watching, and see you in the next video!