Loops in Java

  • while loops
  • for loop
  • Iterator and for each loop

While loops

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 (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.
  • 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

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());
}
}
}
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.
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);
}
}
}
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.
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);
}

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Basics of Selenium…

Make Week 2022: Running a successful hackathon remotely

Visualizing BloodHound Data with PowerBI — Part 2

How AI Is Used for Cloud Cost Optimization

DSLinux on a DSLite with an M3DS Real card and SuperCard SD

How to install Ubuntu 20.04 and dual boot alongside Windows 10

Hosting a Hugo blog on GitHub Pages with Travis CI

Day 43: Remove Bloatware from Windows PC with Clean ISO and PowerShell Script

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
Beknazar

Beknazar

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

More from Medium

Java Lambda Expressions

Java 11 : newbie

Pyramid Pattern of Numbers code in java

Java Programs