Get startedGet started for free

For loops

1. For loops

So far, we have written code that runs once from top to bottom. But what if we want to do the same thing multiple times — like printing or performing an operation on each item in an array? That's where loops come in.

2. Loops

A loop lets us repeat an action several times. In Java, the most common type of loop is the `for` loop. We use it when we know in advance how many times something should repeat.

3. for loop syntax

Let's take a closer look at the syntax. A for loop starts with the keyword for, followed by parentheses that contain three parts: the starting point, the stopping point, and the update step. These are separated by semicolons. The variable i is what we call the iterator. It keeps track of where we are in the loop. The thing we're looping over - like a String or an array - is called the iterable. Let's break down this example: We're saying: "Start with i equal to zero." Then: "Keep looping as long as i is less than 5." And after each loop: "Increase the iterator by one." Inside the curly braces, we put the code we want to repeat. Each time the loop runs, that block of code executes once.

4. for loop example

Let's say we have a word like `"Hello"`. We want to print each letter. We can loop through the `String` using `i` as the iterator, representing the index. On the first pass, `i` is zero, and we get the first character. Then `i` increases to one, and we get the second character, and so on, until we reach the end of the word.

5. for loop through an array

We use the same approach to loop through an array. Arrays also use index numbers, starting from zero. So we can loop from zero up to `array.length`, and access each element using its index.

6. Adding to array in a loop

Here, we loop over an array using the iterator `i` and add it to each element of the array. We print the elements before and after for comparison as well.

7. Infinite loops

One thing we need to be careful about are infinite loops. If we forget to update the iterator, or set the wrong stopping condition, the loop might never end. That can cause your program to freeze or crash. So it's important to make sure the loop is set up to stop when it should.

8. Break

If we ever want to exit a loop early, we can use the break keyword. This tells Java: "stop looping now, even if we haven't reached the end." However, using `break` is not considered a good coding practice so we need to use it wisely. The `while` loop, which we'll learn later, is usually a better option.

9. Recap

Loops are powerful because they let us repeat actions without repeating code. Here is a summary to help you.

10. Let's practice!

Now that we've seen how a for loop works, let's practice looping through a `String` and an array.