Skip to content

Loops

In Java, loops allow us to repeat blocks of code. Let’s break down the structure of a for loop:

As we are catering to our "quit" condition in the while loop itself we can now set the loop to run infinitely until the user types in quit. When using while loops with a true condition it is important to have break; exit condition that occur when the loop is no longer required to ensure no risk of an infinite loop.java

public static void main(String[] args) {
for(int i = 0; i < 5; i++){
System.out.println("Hello This is my message " + (i + 1));
}
}

The ‘for’ loop has three conditions set as parameters within our ( ) brackets and separated by semicolons ; .

  1. Initialisation int i = 0 First we are declaring a variable initialised to zero, This variable will be the count of iterations occurring in our for loop.

  2. Condition i < 5 Here we are telling our for loop to iterate while our i variable is less then five. The condition is evaluated before each iteration of the loop. The loop will continue to run whilst this condition is true.

  3. Increment i++ After each iteration the loop will execute this statement, here we are telling our for loop to increment i by 1 using an augmented assignment operator.

As the loop runs, the statement System.out.println("Hello This is my message " + (i + 1)); will execute. Notice that we are adding 1 to i inside the println() method. This means the output will display the numbers 1 through 5, rather than starting from 0 because the increment of our condition is executed after our value is evaluated.

Output:

Terminal window
Hello, This is my message 1
Hello, This is my message 2
Hello, This is my message 3
Hello, This is my message 4
Hello, This is my message 5
  • The variable i starts at 0, but we add 1 inside the println() statement to display the numbers from 1 to 5 in the output.
  • The loop condition (i < 5) ensures the loop stops after 5 iterations, and the increment (i++) progresses the variable i by 1 each time.

While loops are similar to for loops in functionality but differ in syntax, lets have a look at how our while loop works:

Basic while loop example

public static void main(String[] args) {
while (i > 0){
System.out.println("Hello This is my message " + (i + 1));
i--;
}
}
  • In situations where we know ahead of time the variables that will end a loop a for loop is preferred as it is cleaner and easier to follow.
  • while loops are better in situations where we don’t know exactly how many times we need to repeat a process. As an example awaiting a user’s input.

Example of a While Loop with User Input:

public static void main(String[] args) {
String input = "";
Scanner scanner = new Scanner(System.in);
while (!input.equals("quit")){
System.out.print("Input: ");
input = scanner.next().toLowerCase();
System.out.println(input);
}
}

Here our program can take any number of inputs and return that input back to the user, while waiting for our “quit” command. Once the quit input has been recognised our program ends the while loop and stops running.

In Java there is another type of loop called a Do While loop, it is very similar to a while loop but has a requirement that it is executed at least once. Let’s have a look at the syntax:

Do While Loop

String input = "";
Scanner scanner = new Scanner(System.in);
do {
System.out.print("Input: ");
input = scanner.next().toLowerCase();
System.out.println(input);
}
while (!input.equals("quit"));
  • while loops - check the condition first prior to executing
  • do while loops - check the condition last and execute at least once (even if the condition is false).

Note: while loops are the more common practice do while loops have some use cases however the general preference is to implement while loops where required.

The last type of loop we want to have a look at is the for-each loop in Java, for-each loops are used to iterate over Arrays or Collections and provide a more concise and readable way of accessing the elements of these data structures.

First, let’s look at a traditional for loop used to iterate over an array:

String[] cars = {"Nissan", "Mazda", "Ford"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}

In the above code:

  • The loop runs for each index of the cars array, from i = 0 to i < cars.length.
  • In each iteration, the value at the current index (cars[i]) is printed. For example, when i = 0, cars[0] will be "Nissan", and the loop will continue printing each car name in the array.
  • The loop stops when it reaches the last element of the array, ensuring that it doesn’t attempt to access an invalid index.

Now, let’s have a look at the for-each loop, which is a simplified way to iterate over arrays and collections:

In the above code:

  • We no longer need to declare the bounds of our loop as the language and syntax is written to know that we want each car from our pool of cars to return
  • Will return the exact same results on our first loop

A for-each loop does have its limitations

  • Forward-Only Iteration: The for-each loop is designed to iterate over the collection from the first element to the last. It cannot iterate backward like a traditional for loop can (i.e., from the end to the beginning).
  • No Access to the Index: In a for-each loop, you don’t have direct access to the index of the current element. This means you can’t reference the position of an element, which might be necessary if you need to perform an operation based on the index (e.g., modifying an array or collection at a specific position).
  • No Modification of Collection Elements: Since we don’t have access to the index, it’s also important to note that you cannot modify the elements of an array or collection in place in a for-each loop. You can only access their values.

Lets look at the small program we made in the while loop module:

public static void main(String[] args) {
String input = "";
Scanner scanner = new Scanner(System.in);
while (!input.equals("quit")){
System.out.print("Input: ");
input = scanner.next().toLowerCase();
System.out.println(input);
}
}

This program has a small problem, It has been designed to return either a user’s input or to terminate the program when the user types in quit. At the moment the way the program is written the quit input will echo prior to the program exiting which may not be ideal for the intended function.

One way to solve this problem is to check the input before printing it.

public static void main(String[] args) {
String input = "";
Scanner scanner = new Scanner(System.in);
while (!input.equals("quit")){
System.out.print("Input: ");
input = scanner.next().toLowerCase();
if (!input.equals("quit")){
System.out.println(input);
}
}
}

A break; statement can be used to terminate the loop when a specific condition is met. It immediately exits the loop, ignoring any remaining code within it. Here’s an updated version using break:

public static void main(String[] args) {
String input = "";
Scanner scanner = new Scanner(System.in);
while (!input.equals("quit")){
System.out.print("Input: ");
input = scanner.next().toLowerCase();
if (input.equals("quit")){
break;
}
System.out.println(input);
}
}

The continue; statement moves control to the beginning of the loop, skipping the rest of the current iteration. This can be useful if you want to ignore specific inputs but continue processing the rest of the loop.

public static void main(String[] args) {
String input = "";
Scanner scanner = new Scanner(System.in);
while (!input.equals("quit")){
System.out.print("Input: ");
input = scanner.next().toLowerCase();
if (input.equals("pass")){
continue;
}
if (input.equals("quit")){
break;
}
System.out.println(input);
}
}

Here when a user types in pass the loop is re-executed from the System.out.print("Input: "); line meaning the user’s input will not be echoed in the terminal.

Now that we have updated our break condition we can refactor our code:

public static void main(String[] args) {
String input = "";
Scanner scanner = new Scanner(System.in);
while (true){
System.out.print("Input: ");
input = scanner.next().toLowerCase();
if (input.equals("pass")){
continue;
}
if (input.equals("quit")){
break;
}
System.out.println(input);
}
}

As we are catering to our "quit" condition in the while loop itself we can now set the loop to run infinitely until the user types in quit. When using while loops with a true condition it is important to have break; exit condition that occur when the loop is no longer required to ensure no risk of an infinite loop.