Welcome to our lesson on Java's for loop. We use loops to repeat some action multiple times without the need to write the code for every iteration. A for loop can be likened to a set task — say, visiting each planet in our solar system one by one. By the end of this journey, you will understand and be able to use the basic for loop and the enhanced for loop in Java.
Imagine lining up your favorite planet toys in order. You take one, put it in line, and repeat until you run out of toys. This is precisely how the basic for loop works in Java!
Here's the syntax:
This loop does the following:
- First, we do the
initialization - Then, while the
conditionis true, we keep executing thetaskinside the loop body - After each iteration, we execute
post-iteration actionsthat change the state in some way
Now, let's demonstrate this with code that prints numbers 1 through 5:
Here, we defined an int variable i, assigned it to 1 first, and then repeated System.out.println(i); while i <= 5, incrementing i by 1 after every iteration. By the way, i++ is a short form for i += 1, which is i = i + 1 - so it's just adding 1 to the current value of i, but in a short way! This operation is called increment.
Now, remember flipping pancakes? You pour one pancake, let it cook, then pour the next one, continuing until the batter is finished. Guess what? The enhanced for loop operates in a similar fashion!
Here's an example of printing all elements of an array:
Quite the pancake flipper, isn't it?
You'd typically use a basic for loop when you need to perform a task a specific number of times. In contrast, an enhanced for loop is your go-to when you have a collection (like an array, list, map, or set) and need to perform an action for each item in that collection.
Let's illustrate with both loops printing numbers from an array:
Basic for loop:
Enhanced for loop:
