Java Loops

Java Loops

Introduction

Loops in Java allow executing a block of code multiple times based on a condition. There are three main types of loops:

do-while loop: Similar to while, but executes at least once.

for loop: Used when the number of iterations is known.

while loop: Used when the number of iterations is unknown and depends on a condition.

For Loop

Example 1: Print numbers from 1 to 5

We will use a for loop to print numbers from 1 to 5.

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

Explanation: The loop starts with i = 1 and runs until i <= 5, incrementing i in each iteration.


While Loop

Example 2: Print even numbers from 2 to 10

We will use a while loop to print even numbers from 2 to 10.

public class WhileLoopExample {
    public static void main(String[] args) {
        int i = 2;
        while (i <= 10) {
            System.out.println(i);
            i += 2;
        }
    }
}

Explanation: The loop starts with i = 2 and runs while i <= 10, printing i and increasing it by 2 each time.


Do-While Loop

Example 3: Print “Hello” three times

We will use a do-while loop to print “Hello” three times.

public class DoWhileExample {
    public static void main(String[] args) {
        int count = 0;
        do {
            System.out.println("Hello");
            count++;
        } while (count < 3);
    }
}

Explanation: The loop executes the block once before checking the condition count < 3.


Real-World Examples

Example 4: Count the number of digits in a number

Let’s count the number of digits in a hardcoded number.

public class CountDigits {
    public static void main(String[] args) {
        int number = 12345;
        int count = 0;
        
        while (number > 0) {
            number = number / 10;
            count++;
        }
        
        System.out.println("Number of digits: " + count);
    }
}

Explanation: The loop repeatedly divides number by 10 and increments count until number becomes 0.

Example 5: Reverse a number

Let’s reverse a hardcoded number.

public class ReverseNumber {
    public static void main(String[] args) {
        int number = 1234;
        int reverse = 0;
        
        while (number > 0) {
            int digit = number % 10;
            reverse = reverse * 10 + digit;
            number = number / 10;
        }
        
        System.out.println("Reversed number: " + reverse);
    }
}

Explanation: The loop extracts the last digit using %, adds it to reverse, and removes the last digit using /.


Interview Questions

1. What is the difference between while and do-while loops?

Answer: A while loop checks the condition first, whereas a do-while loop executes at least once before checking the condition.

2. What is the output of the following code?

public class LoopTest {
    public static void main(String[] args) {
        int i = 5;
        while (i > 0) {
            System.out.println(i);
            i--;
        }
    }
}

Output:

5
4
3
2
1

3. Will this loop run infinitely?

public class InfiniteLoop {
    public static void main(String[] args) {
        for (int i = 1; i > 0; i++) {
            System.out.println(i);
        }
    }
}

Answer: Yes, because i keeps increasing and never becomes negative.

4. What happens if we use break in a loop?

Answer: The loop terminates immediately when break is encountered.

5. What happens if we use continue in a loop?

Answer: The loop skips the current iteration and proceeds to the next iteration.

6. What will be the output of the following code?

public class LoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                continue;
            }
            System.out.println(i);
        }
    }
}

Output:

1
2
4
5

Explanation: When i == 3continue skips that iteration.

7. What is the best way to loop through an array in Java?

Answer: Use an enhanced for loop.

public class ArrayLoop {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40};
        for (int num : numbers) {
            System.out.println(num);
        }
    }
}

8. Can a for loop run without a condition?

Answer: Yes, an infinite loop can be written as for(;;) {}.

9. What is the difference between break and return?

Answer: break exits a loop, while return exits the entire method.

10. How can we optimize nested loops?

Answer: Reduce nesting, use break, and consider using data structures like maps or sets.