Skip to content
Code To Live By » Java Tutorial » Loops in Java

Loops in Java

  • by

Similar to our post about Conditional Statements, Loops in Java provide a way to begin adding more complex “control flow” to your code. Loops will allow us to “iterate” over some segment of code.

While Loop

A while loop will check some condition and execute a block of code for as long as that condition is true.

while (condition) {
	// Execute this block of code
}

You may notice this is quite similar to the basic “If Statement” from our section on Conditional Statements. The difference here is that an if statement will only execute once, whereas a while loop will execute for long as that condition is true, potentially infinitely. As such, when working with loops you must be mindful of your “exit condition” so that your loops do not run forever.

Lets say we wanted to print numbers 1-10, we may have a while loop that looks something like this:

int index = 1;
while (index <= 10) {
	System.out.println(index);
	index++;
}

In this case our exit condition is our “index” variable being greater than 10, so we need to increment index within our loop. If we were to neglect to include this then our loop would print “1” over and over until we either cancelled the process or ran out of memory.

For Loop

“For” loops provide a more compact way to include some of the “boilerplate” code that you might need for loops. If we were to dissect the while loop from above a little bit further we can identify three distinct parts of our loop structure:

  • Initialization of our loop variable: int index = 1;
  • Our loop condition: index <= 10
  • Incrementing our loop variable: index++;

If we were to rewrite this as a for loop we might end up with:

for (int index = 1; index <= 10; index++) {
	System.out.println(index);
}

In cases such as our example for printing numbers 1 – 10 a for loop allows us to simplify the surrounding code because we can combine these things into our loop statement.

Foreach Loop

A “foreach” loop allows us to loop over each index in a array, list, or other collection. We will be talking more about what exactly a “collection” is in a future post, but for now know that is also a simple way to loop over each of the elements.

Lets say we wanted to print the first seven letters of the alphabet.

List<String> list = List.of("A", "B", "C", "D", "E", "F", "G");
for (String letter : list) {
	System.out.println(letter);
}

Our output would look something like this

A
B
C
D
E
F
G

Nested Loops

Similar to Conditional Statements, we can also put a loop inside of a loop to create a “nested” loop. We can mix and match for the types of loops as well

while (condition) {
	for (initialize; condition2; increment) {
	    // Execute this block of code
	}
}

Now you have a good idea of how to use loops in Java!

Leave a Reply

Your email address will not be published. Required fields are marked *