Sitemap
Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Java Loops: For, While, and Do-While

6 min readFeb 18, 2025

--

Press enter or click to view image in full size

Loops in Java are fundamental control flow statements that allow developers to execute a block of code multiple times, reducing redundancy and improving efficiency. Java provides three main types of loops: for, while, and do-while. Each loop has its use cases, advantages, and potential pitfalls. This article will explore these loops in depth, with examples and best practices.

Not a Medium member? No problem! Read the full article here. Enjoy!

1. For Loop in Java

Definition

A for loop is used when the number of iterations is known beforehand. It consists of three parts:

  1. Initialization: Declares and initializes the loop control variable.
  2. Condition: Evaluate whether the loop should continue running.
  3. Iteration: Updates the loop control variable after each iteration.

Syntax

for(initialization; condition; iteration) {
// Code block to be executed
}

Example

public class ForLoopExample {
public static void main(String[] args) {
for(int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
}
}

--

--

Nithidol Vacharotayan
Nithidol Vacharotayan

Written by Nithidol Vacharotayan

I write about production failures in Java backend systems: Spring Boot, Kafka, Redis, PostgreSQL, and the trade-offs that only show up after launch.

Dev Genius
Dev Genius

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development