JAVA - Zero to Hero / Java Fundamentals

Loops in JAVA

❔ What Are Loops?

Loops let you repeat a block of code multiple times.

They are used when you want to run the same code until a condition is false.

πŸ”„ for Loop

Used when the number of iterations is known.

πŸ”Έ Syntax:

for(initialization; condition; update) {
    // code to repeat
}

πŸ”Έ Code Example:

for (int i = 1; i <= 5; i++) {
    System.out.println("Count: " + i);
}
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

πŸ” Why use it?

When you know exactly how many times you want to loop.


⏳ while Loop

Used when the condition is checked before every iteration.

Ideal for situations where you don’t know how many times you'll loop.

πŸ”Έ Code Example:

int i = 1;

while (i <= 3) {
    System.out.println("i = " + i);
    i++;
}
i = 1
i = 2
i = 3

πŸ” Why use it?

When you want to loop based on a condition being true.


πŸ” do-while Loop

Same as while loop, but it runs at least once, even if the condition is false.

πŸ”Έ Code Example:

int i = 1;

do {
    System.out.println("Value is: " + i);
    i++;
} while (i <= 2);
Value is: 1
Value is: 2

πŸ” Why use it?

Use when the code should execute at least once, no matter what.


πŸ” Comparison Table: for, while, do-while Loops in Java

Feature

for loop

while loop

do-while loop

Control Type

βœ… Entry-controlled

βœ… Entry-controlled

βœ… Exit-controlled

When condition is checked?

βœ… Before the loop starts

βœ… Before the loop starts

βœ… After the loop executes once

Minimum executions

0 times (may not run at all)

0 times (may not run at all)

At least once (even if condition is false)

Use case

When number of iterations is known

When number of iterations is unknown

When loop must run at least once

Syntax

for(init; cond; update) {}

while(condition) {}

do { } while(condition);

  • Entry-controlled = Condition first, body later β†’ may not run at all.

  • Exit-controlled = Body first, condition later β†’ runs at least once.