Java Series: Part 4

Table of Contents

🔁 Part 4: Learn Java Loops — Repeat Tasks Like a Coding Pro

In the real world, we repeat things all the time:

  • Wake up → brush teeth → repeat every day
  • Watch one more episode → again and again 😅
  • Count to 10 → one number at a time

Java lets your code repeat actions automatically using loops — and it’s easier than you think.


🎯 What Is a Loop?

A loop is a way to tell your code:

“Do this thing over and over — until I say stop.”

There are 3 main types:

Loop TypeWhen to Use It
for loopYou know how many times to repeat
while loopRepeat while a condition is true
do-while loopLike while, but runs at least once

🧮 1. for Loop: Count Up Like a Pro

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

🧠 What’s Happening?

  • int i = 1 → start counting from 1
  • i <= 5 → keep going while i is 5 or less
  • i++ → increase i by 1 each time

➡ Output:

Step 1
Step 2
Step 3
Step 4
Step 5

🔁 2. while Loop: Repeat Until Something Changes

int x = 3;

while (x > 0) {
System.out.println("Counting down: " + x);
x--;
}

➡ Output:

Counting down: 3
Counting down: 2
Counting down: 1

✅ Runs as long as x > 0 is true

🔂 3. do-while Loop: Do It At Least Once

int number = 0;

do {
System.out.println("This runs once!");
} while (number != 0);

✅ Even if the condition is false, it runs once before checking

🎨 Real Example: Print All Even Numbers from 1 to 10

for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}

➡ Output:

2
4
6
8
10

⚠️ Common Mistakes to Avoid

❌ Forgetting to update the counter

while (true) {
// infinite loop! 😱
}

✅ Always make sure your loop can stop!

🎯 Mini Challenge: Countdown with a Twist

Write a loop that counts from 5 to 1, then prints “Liftoff!”

for (int i = 5; i >= 1; i--) {
System.out.println(i);
}
System.out.println("Liftoff! 🚀");

🧭 What’s Next? (Part 5 Preview)

In Part 5, you’ll learn how to:

✅ Group data using arrays
✅ Loop through lists of items
✅ Make your programs work with many values

🧪 Java Loop Cheat Sheet

// For loop
for (int i = 0; i < 10; i++) {
// repeat this 10 times
}

// While loop
while (condition) {
// repeat while condition is true
}

// Do-while loop
do {
// run once, then check condition
} while (condition);
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Want to keep up with our blog?

Get our most valuable tips right inside your inbox, once per month!

Related Posts

0
Would love your thoughts, please comment.x
()
x