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)); }}Explanation of the For loop structure
Section titled âExplanation of the For loop structureâThe âforâ loop has three conditions set as parameters within our ( ) brackets and separated by semicolons ; .
-
Initialisation
int i = 0First we are declaring a variable initialised to zero, This variable will be the count of iterations occurring in ourforloop. -
Condition
i < 5Here we are telling our for loop to iterate while ourivariable 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. -
Increment
i++After each iteration the loop will execute this statement, here we are telling ourforloop to incrementiby1using an augmented assignment operator.
Loop Execution and Output
Section titled âLoop Execution and Outputâ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:
Hello, This is my message 1Hello, This is my message 2Hello, This is my message 3Hello, This is my message 4Hello, This is my message 5- The variable
istarts at 0, but we add 1 inside theprintln()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 variableiby 1 each time.
While Loops
Section titled âWhile Loopsâ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--; }}Key Differences Between For and While Loops:
Section titled âKey Differences Between For and While Loops:â- In situations where we know ahead of time the variables that will end a loop a
forloop is preferred as it is cleaner and easier to follow. whileloops 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.
Do While Loops
Section titled âDo While Loopsâ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 vs do while
Section titled âwhile vs do whileâwhileloops - check the condition first prior to executingdo whileloops - 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.
For Each Loops
Section titled âFor Each Loopsâ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.
Traditional for Loop Example
Section titled âTraditional for Loop Exampleâ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
carsarray, fromi = 0toi < cars.length. - In each iteration, the value at the current index (
cars[i]) is printed. For example, wheni = 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.
For-Each Loop
Section titled âFor-Each Loopâ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
carfrom our pool ofcarsto return - Will return the exact same results on our first loop
Limitations
Section titled âLimitationsâA for-each loop does have its limitations
- Forward-Only Iteration: The
for-eachloop is designed to iterate over the collection from the first element to the last. It cannot iterate backward like a traditionalforloop can (i.e., from the end to the beginning).
- No Access to the Index: In a
for-eachloop, 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-eachloop. You can only access their values.
Break and Continue
Section titled âBreak and Continueâ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); }}Continue
Section titled âContinueâ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.
while(true) Refactored Solution
Section titled âwhile(true) Refactored Solutionâ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.