java
- IntroductionInstallation and SetupJava Syntax and StructureRunning Your First ProgramJava VariablesData Types in JavaOperators in JavaJava Input and OutputControl StatementsLoops in JavaMethods in Java (Functions)Arrays in JavaString Handling in JavaOOPS Concept in JavaClasses and ObjectsConstructor and Constructor Overloadingthis KeywordStatic MembersInheritanceAggregation in JavaMethod OverloadingMethod Overridingsuper KeywordFinal Keyword with Class, Method, and VariablesAccess Modifiers in javaEncapsulation in Java Polymorphism in JavaAbstraction in JavaAbstract ClassesInterfaces in JavaDifference between Abstract Class and Interface Nested and Inner Classes Exception HandlingJava PackagesWrapper Classes and AutoboxingJava Collections FrameworkFile Handling in JavaMultithreadingBasics of Java Memory Management and Garbage CollectionJava JDBC
Java Loops Tutorial for Beginners
Last Updated on: 22nd Oct 2025 20:16:46 PM
Welcome to this beginner-friendly tutorial on Loops in Java! Loops are essential control structures that allow you to repeat a block of code multiple times, making your programs more efficient and flexible. This tutorial is designed for beginners, with clear explanations and practical examples to help you understand how loops work. We'll use code snippets you can run in any Java environment (e.g., Eclipse, IntelliJ, or online compilers like Repl.it).
By the end, you'll confidently use loops to automate repetitive tasks. Let’s get started!
What Are Loops?
Loops execute a block of code repeatedly as long as a condition is met. They’re like a playlist on repeat: the music keeps playing until you stop it or the playlist ends.
Java provides three main types of loops:
-
for loop: Best for a known number of iterations.
-
while loop: Runs as long as a condition is true.
-
do-while loop: Like while, but guarantees at least one execution.
Beginner Tip: Loops rely on conditions (boolean expressions) to decide when to stop. Use them wisely to avoid infinite loops!
1. The for Loop
The for loop is used when you know how many times to repeat the code. It’s compact and commonly used for counting tasks.
Syntax:
for (initialization; condition; update) {
// Code to repeat
}
-
initialization: Runs once before the loop starts (e.g., int i = 0).
-
condition: Checked before each iteration; if true, the loop runs.
-
update: Runs after each iteration (e.g., i++).
Example Code
Let’s 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("Number: " + i);
}
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Explanation:
-
Initialization: int i = 1 sets the counter.
-
Condition: i <= 5 keeps the loop running while i is 5 or less.
-
Update: i++ increments i after each iteration.
-
When i becomes 6, the condition is false, and the loop stops.
Real-World Analogy: Like doing 5 push-ups: you count each one (1, 2, 3, 4, 5) and stop after the fifth.
2. The while Loop
The while loop runs as long as a condition is true. It’s ideal when the number of iterations isn’t fixed.
Syntax:
while (condition) {
// Code to repeat
}
-
condition: Checked before each iteration; if true, the loop runs.
-
You must update the condition inside the loop to avoid infinite loops.
Example Code
Let’s print numbers from 1 to 5 using a while loop.
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Number: " + i);
i++; // Update to prevent infinite loop
}
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Explanation:
-
i starts at 1.
-
The condition i <= 5 is checked before each iteration.
-
Inside the loop, i is incremented. When i becomes 6, the loop stops.
Real-World Analogy: Like eating cookies while the jar isn’t empty: you keep going until the condition (cookies left) is false.
Warning: Forgetting to update the condition (e.g., omitting i++) can cause an infinite loop, crashing your program!
3. The do-while Loop
The do-while loop is similar to while, but it guarantees the code runs at least once because the condition is checked after the loop body.
Syntax:
do {
// Code to repeat
} while (condition);
-
condition: Checked after each iteration; if true, the loop repeats.
-
Note the semicolon (;) after the while condition.
Example Code
Let’s ask the user to enter a positive number, ensuring at least one prompt.
import java.util.Scanner;
public class DoWhileExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive number: ");
number = scanner.nextInt();
} while (number <= 0);
System.out.println("You entered: " + number);
scanner.close();
}
}
Sample Run:
Enter a positive number: -5
Enter a positive number: 0
Enter a positive number: 10
You entered: 10
Explanation:
-
The do block runs first, prompting for input.
-
The condition number <= 0 is checked after. If true, the loop repeats.
-
It keeps asking until a positive number is entered.
Real-World Analogy: Like trying to unlock a door: you try at least once, then keep trying if the key doesn’t work.
4. Nested Loops
A loop inside another loop is called a nested loop. It’s useful for tasks like printing patterns or processing 2D data.
Example Code
Let’s print a 3x3 grid of stars.
public class NestedLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) { // Outer loop for rows
for (int j = 1; j <= 3; j++) { // Inner loop for columns
System.out.print("* ");
}
System.out.println(); // New line after each row
}
}
}
Output:
* * *
* * *
* * *
Explanation:
-
The outer for loop (i) controls rows.
-
The inner for loop (j) prints stars for each column.
-
System.out.println() adds a new line after each row.
Real-World Analogy: Like arranging chairs in a 3x3 grid: for each row, place 3 chairs.
5. Loop Control Statements
These modify loop behavior:
-
break: Exits the loop immediately.
-
continue: Skips the rest of the current iteration and checks the condition again.
Example Code with break and continue
public class LoopControlExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break; // Exit loop when i is 6
}
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println("Number: " + i);
}
}
}
Output:
Number: 1
Number: 3
Number: 5
Explanation:
-
continue skips even numbers (2, 4) by jumping to the next iteration.
-
break stops the loop when i reaches 6, so 7–10 are not processed.
Real-World Analogy: break is like leaving a party early; continue is like skipping a song you don’t like but staying for the next one.
6. Common Issues and Solutions
-
Problem: Infinite loop (e.g., while (true) {}).
-
Solution: Ensure the condition eventually becomes false (e.g., update a counter).
-
-
Problem: Off-by-one errors (e.g., loop runs one time too many/few).
-
Solution: Double-check the condition (e.g., <= vs <).
-
-
Problem: Scanner input in a loop skips prompts.
-
Solution: Use scanner.nextLine() after nextInt() to clear the newline character.
-
Example Fix for Scanner in Loop
import java.util.Scanner;
public class ScannerLoopExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String response;
do {
System.out.print("Do you want to continue? (yes/no): ");
response = scanner.nextLine();
} while (response.equalsIgnoreCase("yes"));
System.out.println("Stopped!");
scanner.close();
}
}
Sample Run:
Do you want to continue? (yes/no): yes
Do you want to continue? (yes/no): no
Stopped!
7. Practice Tips
-
Experiment: Try changing loop conditions or nesting loops to create patterns.
-
Test Code: Use an online compiler to run and tweak examples.
-
Common Mistake: Don’t forget to update loop variables in while or do-while loops.
-
Quiz Yourself: What does this print?
for (int i = 3; i <= 5; i++) {
System.out.println(i);
}
(Answer: 3, 4, 5)
Summary
-
for loop: Best for known iteration counts (e.g., counting 1 to 10).
-
while loop: Runs while a condition is true; needs manual updates.
-
do-while loop: Runs at least once; condition checked after.
-
Nested Loops: Loops inside loops for complex tasks like patterns.
-
Control Statements: break exits, continue skips iterations.
-
Next Steps: Combine loops with decision-making statements or input/output for interactive programs.
You’re now ready to automate repetitive tasks with loops in Java! Keep practicing, and happy coding! ![]()
.png)