The main idea of loops is to repeat our code.

Photo by Benjamin Lizardo on Unsplash
  • while loops
  • for loop
  • Iterator and for each loop

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.
  • !password.equals(ACTUAL_PASSWORD) this is a boolean condition of our loop. If it’s true it keeps executing the body. After each iteration, it will check the condition again and if it’s false it will exit the loop and if it’s true it will execute the body and this process goes over again.
  • The body of the loop is the actual code that will be executed in a loop. Most of the time in a while loop’s body the variable that responsible for the condition should change based on a specific scenario so the program can exit our loop at some point. In our case, line 17 updates the password so if the password correct program will exit the loop.
  • while loops are good to use when we don’t know an exact number of iterations in advance.
do-while loop
  • The above program is the exact same program but written with a do-while loop.
  • In the do-while loop, the body goes first and then condition. The do-while will have at least one iteration(while can have zero iterations).

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.
  • i < 10; this is the condition part. It is exactly the same as a while loop if it’s true it will execute a body of a loop and if it’s false it will exit the loop.
  • i++ update action. We update a variable we declare in the init part so at some point our condition will be false and it can exit the loop.
for (int index = 10; index > 0; index--) {
System.out.println("Java is cool!");
}
  • The above snippet will print 10 times Java is cool!
  • The name of the variable we initialize can be anything. Same for a condition and update part. The idea of this example to show that you can design your loop as you want.
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’
  • Again, you can design as you want to design your loop. Just remember, it will keep running while your condition is true.
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.
  • If a program in the body of the loop will run continue , it will skip the current iteration and will go for the next one.
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.
  • We are breaking in the middle using break keyword and the last number it will print is 76. When the loop will go for the next iteration i will be 77 and a break will be executed so the program will exit from the loop.
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
  • continue keyword will skip the rest of the code and go for the next iteration.

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.
  • hasNext() will check if there are more elements.
  • next() will return the element and move the index of the iterator to the next element.

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.
  • String color is a single element of collection and it will get assigned one by one to each element from the collection.

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!

This article is part of the series of articles to learn Java programming language from Tech Lead Academy:1. Introduction to programming 
2. OS, File, and File System
3. Working with terminal
4. Welcome to Java Programming Language
5. Variables and Primitives in Java
6. Methods with Java
7. Java Math Operators and special operators
8. Conditional branching in Java
9. Switch statement in Java
10. Ternary operator in Java
11. Enum in Java
12. String class and its methods in Java
13. Loops in Java
14. Access modifiers in Java
15. Static keyword in Java
16. The final keyword in Java
17. Class and Object in Java
18. Object Oriented Programming in Java
19. OOP: Encapsulation in Java
20. Inheritance in Java
21. Abstraction in Java
22. Polymorphism in Java
23. Overriding vs Overloading in Java
24. OOP Design Principles in Java
25. Array in Java
26. Data Structures with Java
27. Collection framework in Java
28. ArrayList in Java
29. Set in Java
30. Map in Java
31. LocalDate in Java
32. Exception in Java
33. IO in Java
34. Design Patterns
35. Generics in Java
36. Multithreading in java
37. JUnit
38. Big O Notation for coding interviews
39. Top 17 Java coding interview questions for SDET

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