Loops

Updated: 3 years ago

Check out other lessons in Learning the Java syntax

We now know how to introduce conditions in our code. Now we are going to start implementing loops that will help us execute parts of our code in a repeatable pattern.

Loops are a way for us to execute parts of our code a desired amount of times. Loops are very useful and you'll be using them all the time. For example, you'll use loops to simplify outputting the contents of an array to the console.

For loop

package com.codescrubs;

public class Main
{
    public static void main(String[] args)
    {
        // for loop, loops 10 times
        for(int i = 0; i < 10; i++)
        { 
            System.out.println("i is " + i);
        }
    }
 }

This is an example of a for loop. The for loop has three parts. The first part is int i = 0, where we can setup any necessary variables. The second part i < 10 is the condition of the loop. The last part is i++, where we can modify variables after each loop.

Let's translate that into plain English. We have just setup a loop that starts with a variable i at 0, runs until i < 10 and after every loop i gets incremented by 1.

Outputting the contents of an array

Now let's use the array we've learned in a previous lesson with a loop to output the contents of the array.

 // Let's create our array
 int[] dailyTemperature = new int[5];
 dailyTemperature[0] = 24;
 dailyTemperature[1] = 22;
 dailyTemperature[2] = 21;
 dailyTemperature[3] = 25;
 dailyTemperature[4] = 24;

// Loop for every index in our array
for(int i = 0; i < dailyTemperature.size(); i++)
{
      // Output the contents of the array at index i
      System.out.println("Temperature: " + dailyTemperature[i]);
}

Cool. That was easy. We just needed one single print statement and a loop.

while loop

A while loop is a bit different than a for loop, because it only has a condition. A while loop will run as long as the condition is true.

// Let's create a counter
int i = 0;

// while loop, loops as long as the statement is true
while(i < 10)
{
     System.out.println("i is " + i);

     // Increment the counter, so we don't get an infinite loop
     i++;
}

It's the same output as above, but done with a while loop. The loop will stop running when i is 10 or larger.

Endless loops

When you are creating a loop, always make sure that your condition won't cause an endless loop. While having an endless loop while testing is not a problem (you can always shut down the process), having one in an application used by real users is a big no-no.

« Previous lesson:
Conditionals