C

Core Java tutorial for beginners

Clean • Professional

Core Java Loops – for, while, do-while & for-each Explained

4 minute

Loops in Java

Loops in Java are used to repeat a block of code multiple times. They help automate repetitive tasks, reduce errors, and make your code efficient.


What Are Loops in Java?

A loop executes a block of code repeatedly until a condition becomes false.

Types of loops in Java:

learn code with durgesh images

 

1. for Loop

 

Used when you know how many times you want to repeat a block.

Syntax:

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

Example: Print 1 to 5

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

Output:

1
2
3
4
5

2. while Loop

Used when you don’t know the exact number of iterations in advance.

Condition is checked before executing the block.

Syntax:

while (condition) {
    // code to execute
}

Example: Sum numbers until total < 50

int total = 0;
int num = 1;

while (total < 50) {
    total += num;
    num++;
}

System.out.println("Total: " + total);

Output:

Total: 55

3. do-while Loop

Executes the block at least once, then checks the condition.

Useful when code must run at least once regardless of condition.

Syntax:

do {
    // code to execute
} while (condition);

Example: Input validation

import java.util.Scanner;

Scanner sc = new Scanner(System.in);
int number;

do {
    System.out.print("Enter a positive number: ");
    number = sc.nextInt();
} while (number <= 0);

System.out.println("You entered: " + number);
sc.close();

4. for-each Loop

Used to iterate through arrays or collections without worrying about index.

Introduced in Java 5 (enhanced for loop).

Syntax:

for (type var : arrayOrCollection) {
    // code
}

Example: Iterating through an array

int[] numbers = {10, 20, 30, 40};

for (int num : numbers) {
    System.out.println(num);
}

Output:

10
20
30
40

Nested Loops

You can place one loop inside another. Useful for patterns, matrices, etc.

Example: Print 3x3 stars

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        System.out.print("* ");
    }
    System.out.println();
}

Output:

* * *
* * *
* * *

Example: Calculate Factorial Using Loops

import java.util.Scanner;

public class Factorial {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = sc.nextInt();

        int factorial = 1;
        for (int i = 1; i <= n; i++) {
            factorial *= i;
        }

        System.out.println("Factorial of " + n + " is " + factorial);
        sc.close();
    }
}

Output Example:

Enter a number: 5
Factorial of 5 is 120

🏆 Top 5 Java Interview Questions - Java Loops

1. Difference between for and while loops

Answer:

Featurefor Loopwhile Loop
InitializationDone inside the loop headerDone before the loop
Condition CheckChecked at the start of each iterationChecked at the start of each iteration
Increment/DecrementDone in the loop headerDone inside the loop body
Use CaseWhen number of iterations is knownWhen number of iterations is unknown or based on a condition
Syntaxfor(initialization; condition; increment)while(condition)

Example:

for(int i=0; i<5; i++) System.out.println(i); // 0 to 4
int i=0;
while(i<5) { System.out.println(i); i++; } // 0 to 4

2. What is the difference between while and do-while?

Answer:

Featurewhile Loopdo-while Loop
Condition CheckChecked before executing loop bodyChecked after executing loop body
Execution GuaranteeMay not execute at all if condition is falseExecutes at least once
Syntaxwhile(condition) { ... }do { ... } while(condition);

Example:

int i = 0;
while(i>0) { System.out.println(i); } // Won’t print
do { System.out.println(i); } while(i>0); // Prints 0

3. When should you use a for-each loop?

Answer:

  • Use for-each loop (enhanced for loop) to iterate over arrays or collections when you don’t need index.
  • Simplifies code and reduces errors.

Example:

int[] numbers = {1,2,3,4};
for(int num : numbers) {
    System.out.println(num);
}

4. Can we use a for loop without initialization or increment?

Answer:

  • Yes, both initialization and increment/decrement are optional in a for loop.
  • Example: Infinite loop
for( ; ; ) {
    System.out.println("Infinite loop");
    break; // to prevent infinite execution
}
  • Any or all parts of the loop header can be omitted.

5. What is a nested loop? Give an example

Answer:

  • A nested loop is a loop inside another loop.
  • Inner loop executes completely for each iteration of outer loop.

Example:

for(int i=1; i<=3; i++) {
    for(int j=1; j<=2; j++) {
        System.out.println("i=" + i + ", j=" + j);
    }
}

Output:

i=1, j=1
i=1, j=2
i=2, j=1
i=2, j=2
i=3, j=1
i=3, j=2

 

Article 0 of 0