The main idea of loops is to repeat our code.

Photo by Benjamin Lizardo on Unsplash
  • while loops

While loops

Loops allow us to repeat a block of code a specific number of times depending on a condition.

while loop
  • The above code will keep asking for a password until the user provides the correct password.
do-while loop
  • The above program is the exact same program but written with a do-while loop.

For loop

For loop also allows us to repeat a block of code. The main difference is that for loop has a structure to work with a specific number of iterations. As discussed above the while loop is good when we don’t know how many times we will need to iterate, but for loop is a good fit when we know an exact number of times we need to iterate.

for (int i = 0; i < 10; i++){
System.out.println("Hello, World!");
}
  • The above snippet will print 10 times Hello, World!
There are three main parts of for loop
for (init action, boolean expression, update action) {
body of loop
}
  • int i = 0; this is the init action part. We can initialize the variable here and this variable will play the role of a ‘counter’ for our condition.
for (int index = 10; index > 0; index--) {
System.out.println("Java is cool!");
}
  • The above snippet will print 10 times Java is cool!
for (char ch = 'a'; ch <= 'z'; ch++) {
System.out.println(ch);
}
  • The above snippet will print the alphabet starting from ‘a’ and ending with ‘z’
for (;;) {
System.out.println("Good Day!");
}
  • This is an infinite loop! So if a condition will never change to false, your program will stack in the loop forever. Well, until the power goes off or memory gets overflow.

Now let’s talk about break and continue keywords with loops.

  • If a program in the body of the loop will run break , it will exit the loop immediately.
for (int i = 1; i <= 100; i++) {
if (i == 77) {
break;
}
System.out.println("Number: " + i);
}
  • The above loop without break supposed to print numbers from 1 to 100.
for (int i = 1; i <= 100; i++) {
if (i == 7 || i == 77 || i == 97) {
continue;
}
System.out.println("Number: " + i);
}
  • It will print numbers from 1 to 100 but skip 7, 77, 97

Iterator and for each loop

Iterator is an interface that allows us to iterate the collections or data structures. For each loop is a simplified version of an iterator.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> colors = new ArrayList<>();
colors.add("black");
colors.add("white");
colors.add("yellow");
colors.add("red");

Iterator<String> iterator = colors.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}

Output:

black
white
yellow
red
  • We went over each element of our list using iterator.

Not every data structure can be used together with Iterator. Let’s say if you are creating your own custom data structure it will not work by default with Iterator. The class should implement an Iterable interface and then it can be used with Iterator and with for each loop. Note, an array cannot be used with Iterator but it can work with for each loop.

import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> colors = new ArrayList<>();
colors.add("black");
colors.add("white");
colors.add("yellow");
colors.add("red");

for (String color : colors) {
System.out.println(color);
}
}
}

Output:

black
white
yellow
red
  • For each loop is a simplified version of iterating the collection of data.

Let’s see few more examples:

int[] numbers = {1, 2, 3, 4, 5, 6, 7};
for (int num : numbers) {
System.out.println(num);
}
char[] letters = {'a', 'b', 'c', 'd', 'e'};
for (char ch : letters) {
System.out.println(ch);
}
Set<Double> set = new HashSet<>();
set.add(13.5);
set.add(1.3);
set.add(66.9);
set.add(345.0);

for (Double d : set) {
System.out.println(d);
}

That’s all for loops in Java. Happy Coding!

Software Developer, Java Instructor https://www.techleadacademy.io/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store