Java Loops (for, while, do-while) — Full Beginner Guide

Java Loops: for, while and do-while (With Examples)

✨ Quick Summary

In this post, you’ll learn how to repeat tasks in Java using Loops. We will cover for, while, and do-while loops with simple beginner-friendly examples.

Java Beginner Loops for / while / do-while

In our previous post, we learned about Conditional Statements like if-else and switch.

Now, let’s learn one of the most important concepts in programming: Loops.

A loop is used when you want to repeat a block of code multiple times.


1) for Loop

The for loop is used when you already know how many times you want to repeat a task.

Syntax


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

Example: 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);
        }
    }
}

2) while Loop

The while loop is used when you don’t know the exact number of repetitions. It will run until the condition becomes false.

Syntax


while(condition) {
    // code to repeat
}

Example: Print numbers from 1 to 5


public class WhileLoopExample {
    public static void main(String[] args) {

        int i = 1;

        while (i <= 5) {
            System.out.println(i);
            i++;
        }
    }
}

3) do-while Loop

The do-while loop is similar to while loop. But the difference is:

do-while always runs at least one time even if the condition is false.

Syntax


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

Example


public class DoWhileExample {
    public static void main(String[] args) {

        int i = 1;

        do {
            System.out.println(i);
            i++;
        } while (i <= 5);
    }
}

4) break and continue in Loops

Java provides two important keywords inside loops:

  • break → stops the loop immediately
  • continue → skips the current iteration and moves to the next

Example: break


public class BreakExample {
    public static void main(String[] args) {

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

Example: continue


public class ContinueExample {
    public static void main(String[] args) {

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

Conclusion

Loops are extremely important in Java because they help you:

  • ✅ Repeat tasks
  • ✅ Save time and reduce code
  • ✅ Build real-world programs

In the next post, we will learn about Java Arrays and how to store multiple values in one variable!

Comments

Post a Comment

Popular posts from this blog

Inheritance in Java (Single, Multilevel, Hierarchical)

The Java Blueprint: Your First Step into Software Development

Java Variables and Data Types: Storing Your Data