Java Loops Tutorial: for, while, do-while & More Explained (2026)
⏱️ Reading Time: 24 minutes | 🎯 Difficulty: Beginner | 🔄 Last Updated: August 21, 2026
What Are Loops in Java?
A loop is a control structure that repeatedly executes a block of code as long as a specified condition remains true.
Think of a loop as a conveyor belt in a factory — it keeps moving items through the same process until a stop condition is met. Without loops, you would have to write the same code hundreds of times.
1// Without a loop — tedious and error-prone 2System.out.println(1); 3System.out.println(2); 4System.out.println(3); 5// ... repeat 97 more times 6 7// With a loop — clean and scalable 8for (int i = 1; i <= 100; i++) { 9 System.out.println(i); 10}
Java provides five types of loops:
for— Fixed iteration countwhile— Condition-based, zero or more iterationsdo...while— Condition-based, at least one iteration- Enhanced
for(for-each) — Iterate arrays and collections - Nested loops — Loops inside loops
Why Do We Need Loops?
"I once had to validate 50 form fields manually. It took 200 lines. A senior rewrote it in 10 lines with a loop. That was the day I understood why loops exist." — Every developer's turning point.
Loops are the engine of repetition in programming. Here is where they shine:
| Scenario | Without Loops | With Loops |
|---|---|---|
| Print 1 to 1000 | 1000 lines of code | 3 lines |
| Validate all cart items | Manual check per item | Single loop over the list |
| Search a database | Check each record by hand | Loop + condition |
| Game frame rendering | Impossible | while (running) loop |
| Process log files | Open each line manually | Read line by line in a loop |
| API pagination | Hardcode each page | Loop until no more pages |
Real-world applications:
- E-commerce: Loop through cart items to calculate totals
- Social Media: Loop through posts to render a feed
- Banking: Loop through transactions to generate statements
- Gaming: Main game loop updates physics, AI, and rendering every frame
- Data Science: Loop through datasets to train machine learning models
The for Loop
The for loop is the most commonly used loop in Java. It is ideal when you know exactly how many times the loop should run.
Syntax
1for (initialization; condition; update) { 2 // Loop body — executes repeatedly 3}
The Three Parts
| Part | When It Runs | Purpose |
|---|---|---|
| Initialization | Once, before the loop starts | Declare and set the loop variable |
| Condition | Before every iteration | If true, loop continues; if false, loop stops |
| Update | After every iteration | Modify the loop variable (increment, decrement, etc.) |
Example: Counting Up
1public class ForLoopDemo { 2 public static void main(String[] args) { 3 for (int i = 1; i <= 5; i++) { 4 System.out.println("Iteration: " + i); 5 } 6 } 7}
Output:
1Iteration: 1 2Iteration: 2 3Iteration: 3 4Iteration: 4 5Iteration: 5
Execution Flow
Step 1: int i = 1 (Initialization)
Step 2: i <= 5? (Condition → true)
Step 3: Print i (Body)
Step 4: i++ (Update → i = 2)
Step 5: i <= 5? (Condition → true)
Step 6: Print i (Body)
... repeats until i = 6, then condition is false, loop ends
Reverse Loop (Counting Down)
1for (int i = 10; i >= 1; i--) { 2 System.out.println(i); 3} 4// Output: 10, 9, 8, ..., 1
Multiple Variables in for Loop
1for (int i = 1, j = 10; i <= 10; i++, j--) { 2 System.out.println("i = " + i + ", j = " + j); 3}
Infinite for Loop (DANGER)
1// NEVER run this in production! 2for (;;) { 3 System.out.println("Infinite!"); 4}
⚠️ Critical: Always ensure your loop condition eventually becomes
false. Otherwise, you create an infinite loop that freezes your program.
The while Loop
The while loop executes a block of code as long as its condition remains true. Use it when you do not know how many iterations are needed beforehand.
Syntax
1while (condition) { 2 // Loop body 3}
Example: User Input Validation
1import java.util.Scanner; 2 3public class WhileDemo { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 int number = 0; 7 8 while (number <= 0) { 9 System.out.print("Enter a positive number: "); 10 number = Integer.parseInt(input.nextLine()); 11 12 if (number <= 0) { 13 System.out.println("❌ Invalid! Try again."); 14 } 15 } 16 17 System.out.println("✅ You entered: " + number); 18 } 19 } 20}
Sample Run:
1Enter a positive number: -5 2❌ Invalid! Try again. 3Enter a positive number: 0 4❌ Invalid! Try again. 5Enter a positive number: 7 6✅ You entered: 7
When to Use while vs for
Use for when... | Use while when... |
|---|---|
| You know the iteration count | The count is unknown |
| Iterating over a range | Waiting for user input |
| Array index iteration | Reading data until EOF |
| Simple counter logic | Polling a server status |
The do...while Loop
The do...while loop is a variant of while that guarantees the loop body executes at least once because the condition is checked after the body runs.
Syntax
1do { 2 // Loop body — always runs at least once 3} while (condition);
Note the semicolon after the
whilecondition. It is required!
Example: Menu That Shows At Least Once
1import java.util.Scanner; 2 3public class DoWhileDemo { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 int choice; 7 8 do { 9 System.out.println("\\n--- MENU ---"); 10 System.out.println("1. Play Game"); 11 System.out.println("2. Settings"); 12 System.out.println("3. Exit"); 13 System.out.print("Choice: "); 14 15 choice = Integer.parseInt(input.nextLine()); 16 17 switch (choice) { 18 case 1 -> System.out.println("🎮 Starting game..."); 19 case 2 -> System.out.println("⚙️ Opening settings..."); 20 case 3 -> System.out.println("👋 Goodbye!"); 21 default -> System.out.println("❌ Invalid choice"); 22 } 23 } while (choice != 3); 24 } 25 } 26}
while vs do...while: The Critical Difference
1int x = 10; 2 3// while loop — body NEVER runs 4while (x < 5) { 5 System.out.println("while: " + x); // Nothing prints 6} 7 8// do...while loop — body runs ONCE 9do { 10 System.out.println("do-while: " + x); // Prints: do-while: 10 11} while (x < 5);
Use do...while when:
- You need a menu to display at least once
- You are prompting for input that must be validated at least once
- The first iteration sets up data needed for the condition check
The Enhanced for Loop (for-each)
The enhanced for loop (introduced in Java 5) provides a cleaner way to iterate over arrays and collections when you do not need the index.
Syntax
1for (dataType item : collection) { 2 // Use 'item' directly 3}
Example: Iterating an Array
1public class EnhancedForDemo { 2 public static void main(String[] args) { 3 int[] marks = {85, 90, 78, 95, 88}; 4 int total = 0; 5 6 for (int mark : marks) { 7 System.out.println("Mark: " + mark); 8 total += mark; 9 } 10 11 System.out.println("Total: " + total); 12 System.out.println("Average: " + (total / (double) marks.length)); 13 } 14}
Output:
1Mark: 85 2Mark: 90 3Mark: 78 4Mark: 95 5Mark: 88 6Total: 436 7Average: 87.2
Enhanced for vs Traditional for
| Feature | Traditional for | Enhanced for |
|---|---|---|
| Index access | ✅ Yes | ❌ No |
| Modify elements | ✅ Yes | ⚠️ Primitive values are copies |
| Readability | Moderate | ✅ Excellent |
| Null safety | Manual | Automatic (throws NPE if array is null) |
| Best for | Index-based logic | Simple iteration |
⚠️ You Cannot Modify the Array with Enhanced for
1int[] numbers = {1, 2, 3}; 2 3for (int num : numbers) { 4 num = num * 2; // Changes the local copy, NOT the array! 5} 6 7// numbers is still {1, 2, 3}
To modify elements, use a traditional for loop with an index:
1for (int i = 0; i < numbers.length; i++) { 2 numbers[i] = numbers[i] * 2; // Actually modifies the array 3}
Nested Loops
A nested loop is a loop inside another loop. The inner loop completes all its iterations for every single iteration of the outer loop.
How Nested Loops Work
Outer: i = 1
Inner: j = 1, 2, 3
Outer: i = 2
Inner: j = 1, 2, 3
Outer: i = 3
Inner: j = 1, 2, 3
Example: 3×3 Grid
1public class NestedLoopDemo { 2 public static void main(String[] args) { 3 for (int row = 1; row <= 3; row++) { 4 for (int col = 1; col <= 3; col++) { 5 System.out.print("(" + row + "," + col + ") "); 6 } 7 System.out.println(); // New line after each row 8 } 9 } 10}
Output:
1(1,1) (1,2) (1,3) 2(2,1) (2,2) (2,3) 3(3,1) (3,2) (3,3)
Time Complexity Warning
If the outer loop runs n times and the inner loop runs n times, the total iterations are n × n = n². For n = 1000, that is 1,000,000 iterations. Be mindful of performance with large nested loops.
The break Statement
The break statement immediately terminates the loop and transfers control to the first statement after the loop.
Example: Find First Match
1public class BreakDemo { 2 public static void main(String[] args) { 3 int[] numbers = {12, 45, 7, 89, 34, 56}; 4 int target = 89; 5 6 for (int num : numbers) { 7 System.out.println("Checking: " + num); 8 if (num == target) { 9 System.out.println("✅ Found " + target + "!"); 10 break; // Stop searching — we found it! 11 } 12 } 13 System.out.println("Search complete."); 14 } 15}
Output:
1Checking: 12 2Checking: 45 3Checking: 7 4Checking: 89 5✅ Found 89! 6Search complete.
Without break, the loop would unnecessarily check 34 and 56.
break in while Loop
1int i = 1; 2while (true) { // Intentional infinite loop 3 System.out.println(i); 4 if (i >= 5) { 5 break; // Exit condition inside the loop 6 } 7 i++; 8}
The continue Statement
The continue statement skips the rest of the current iteration and jumps to the next iteration of the loop.
Example: Skip Even Numbers
1public class ContinueDemo { 2 public static void main(String[] args) { 3 for (int i = 1; i <= 10; i++) { 4 if (i % 2 == 0) { 5 continue; // Skip even numbers 6 } 7 System.out.println("Odd number: " + i); 8 } 9 } 10}
Output:
1Odd number: 1 2Odd number: 3 3Odd number: 5 4Odd number: 7 5Odd number: 9
break vs continue
| Statement | Effect | Use When |
|---|---|---|
break | Exits the loop entirely | You found what you need; no more iterations needed |
continue | Skips to next iteration | Current item does not meet criteria; check the next one |
Labels in Loops
A label is an identifier followed by a colon (:) that you can attach to a loop. It allows break and continue to target a specific outer loop when working with nested loops.
Syntax
1labelName: 2for (...) { 3 for (...) { 4 break labelName; // Exits BOTH loops 5 } 6}
Example: Search a 2D Array
1public class LabelDemo { 2 public static void main(String[] args) { 3 int[][] matrix = { 4 {1, 2, 3}, 5 {4, 5, 6}, 6 {7, 8, 9} 7 }; 8 int target = 5; 9 boolean found = false; 10 11 search: 12 for (int i = 0; i < matrix.length; i++) { 13 for (int j = 0; j < matrix[i].length; j++) { 14 System.out.println("Checking [" + i + "][" + j + "] = " + matrix[i][j]); 15 16 if (matrix[i][j] == target) { 17 System.out.println("✅ Found " + target + " at [" + i + "][" + j + "]"); 18 found = true; 19 break search; // Exit both loops immediately! 20 } 21 } 22 } 23 24 if (!found) { 25 System.out.println("❌ Target not found."); 26 } 27 } 28}
Output:
1Checking [0][0] = 1 2Checking [0][1] = 2 3Checking [0][2] = 3 4Checking [1][0] = 4 5Checking [1][1] = 5 6✅ Found 5 at [1][1]
Without the search label, break would only exit the inner loop, causing unnecessary checks.
Best Practice: Use labels sparingly. They can make code harder to follow. Often, extracting nested loops into a method is cleaner.
Choosing the Right Loop
| Loop Type | Best For | Iteration Count | Example |
|---|---|---|---|
for | Known iteration count | Fixed | for (int i = 0; i < 10; i++) |
while | Condition-based, may run zero times | Unknown | Reading user input until valid |
do...while | Must run at least once | At least 1 | Menu display, game round |
Enhanced for | Arrays and collections | Collection size | for (String item : cart) |
| Nested loops | 2D data, patterns, combinations | Product of both loops | Matrix traversal, star patterns |
Decision Tree
Are you iterating over an array/collection without needing the index?
├── YES → Use enhanced for (for-each)
└── NO → Do you know how many times to loop?
├── YES → Use for
└── NO → Must the body run at least once?
├── YES → Use do...while
└── NO → Use while
Real-World Use Cases
Use Case 1: Shopping Cart Total (Enhanced for)
1public class ShoppingCart { 2 public static void main(String[] args) { 3 double[] prices = {299.99, 149.50, 899.00, 49.99}; 4 double total = 0; 5 double discountThreshold = 500.0; 6 7 for (double price : prices) { 8 total += price; 9 } 10 11 double discount = (total > discountThreshold) ? total * 0.10 : 0; 12 double finalTotal = total - discount; 13 14 System.out.printf("Subtotal: ₹%.2f%n", total); 15 System.out.printf("Discount: -₹%.2f%n", discount); 16 System.out.printf("Total: ₹%.2f%n", finalTotal); 17 } 18}
Use Case 2: Paginated API Fetcher (while)
1public class ApiPaginator { 2 public static void main(String[] args) { 3 int page = 1; 4 boolean hasMorePages = true; 5 6 while (hasMorePages) { 7 System.out.println("Fetching page " + page + "..."); 8 9 // Simulate API call 10 // List<Data> data = api.fetchPage(page); 11 // hasMorePages = !data.isEmpty(); 12 13 hasMorePages = (page < 5); // Simulate 5 pages 14 page++; 15 } 16 17 System.out.println("All pages fetched!"); 18 } 19}
Use Case 3: Prime Number Checker (for + break)
1public class PrimeChecker { 2 public static void main(String[] args) { 3 int number = 17; 4 boolean isPrime = true; 5 6 if (number <= 1) { 7 isPrime = false; 8 } else { 9 for (int i = 2; i <= Math.sqrt(number); i++) { 10 if (number % i == 0) { 11 isPrime = false; 12 break; // No need to check further 13 } 14 } 15 } 16 17 System.out.println(number + (isPrime ? " is prime! ✅" : " is not prime. ❌")); 18 } 19}
Optimization: We only check up to
√numberbecause ifn = a × b, one factor must be ≤√n.
Common Mistakes
Mistake 1: Off-by-One Errors
1// WRONG — Prints 0 to 9, not 1 to 10 2for (int i = 0; i < 10; i++) { 3 System.out.println(i + 1); 4} 5 6// CORRECT 7for (int i = 1; i <= 10; i++) { 8 System.out.println(i); 9}
Remember:
i < 10runs 10 times (0-9).i <= 10runs 11 times (0-10). Be precise with your boundary conditions.
Mistake 2: Infinite Loops
1// WRONG — i never changes, condition always true 2for (int i = 1; i <= 10; ) { 3 System.out.println(i); 4 // Forgot i++! 5} 6 7// WRONG — while with no update 8int x = 1; 9while (x <= 10) { 10 System.out.println(x); 11 // Forgot x++! 12}
Prevention: Always verify that your loop variable moves toward the termination condition.
Mistake 3: Modifying a Collection While Iterating
1// WRONG — ConcurrentModificationException! 2List<String> items = new ArrayList<>(List.of("A", "B", "C")); 3for (String item : items) { 4 if (item.equals("B")) { 5 items.remove(item); // CRASH! 6 } 7} 8 9// CORRECT — Use Iterator 10Iterator<String> iterator = items.iterator(); 11while (iterator.hasNext()) { 12 if (iterator.next().equals("B")) { 13 iterator.remove(); // Safe removal 14 } 15}
Mistake 4: Using Enhanced for to Modify Array Elements
1int[] nums = {1, 2, 3}; 2 3// WRONG — Does NOT modify the array 4for (int n : nums) { 5 n = n * 2; // Only changes local copy 6} 7 8// CORRECT — Use index-based for 9for (int i = 0; i < nums.length; i++) { 10 nums[i] = nums[i] * 2; 11}
Mistake 5: Missing Semicolon in do...while
1// WRONG — Compilation error! 2do { 3 System.out.println("Hello"); 4} while (false) // Missing semicolon! 5 6// CORRECT 7do { 8 System.out.println("Hello"); 9} while (false); // Semicolon required
Mistake 6: Declaring Loop Variable Outside and Reusing
1// Confusing — variable scope leaks 2int i; 3for (i = 0; i < 5; i++) { } 4System.out.println(i); // i is 5 here — surprising! 5 6// Better — declare inside the loop 7for (int j = 0; j < 5; j++) { } 8// j is not accessible here — clean!
Best Practices
-
Declare loop variables inside the loop — Limits scope and prevents accidental reuse.
1// Good 2for (int i = 0; i < 10; i++) { } 3 4// Avoid 5int i; 6for (i = 0; i < 10; i++) { } -
Use enhanced for for simple array/collection iteration — It is cleaner and less error-prone.
-
Prefer
breakover flags when searching — It is more readable and efficient.1// Good 2for (int num : numbers) { 3 if (num == target) { found = true; break; } 4} -
Avoid deep nesting — More than 2-3 levels of nested loops becomes hard to maintain. Extract into methods.
-
Use meaningful variable names —
rowandcolinstead ofiandjfor matrices. -
Be careful with floating-point loop conditions — Rounding errors can cause infinite loops.
1// DANGEROUS — may never end due to floating-point precision 2for (double d = 0.1; d != 1.0; d += 0.1) { } 3 4// SAFE — use integer counter and calculate inside 5for (int i = 1; i <= 10; i++) { 6 double d = i * 0.1; 7} -
Check for null before iterating — Null arrays throw
NullPointerException.1if (array != null) { 2 for (int item : array) { } 3}
Architecture & Performance Considerations
Loop Unrolling (JVM Optimization)
The Java JIT (Just-In-Time) compiler automatically optimizes small loops by unrolling them — replacing the loop with repeated statements to reduce branch overhead.
1// Original 2for (int i = 0; i < 4; i++) { 3 process(i); 4} 5 6// JVM may unroll to: 7process(0); 8process(1); 9process(2); 10process(3);
Enhanced for Loop Under the Hood
The enhanced for loop compiles to an Iterator for collections and a traditional index-based loop for arrays. For arrays, it is just as fast as a regular for loop.
Time Complexity of Nested Loops
| Structure | Iterations | Complexity | Example |
|---|---|---|---|
| Single loop | n | O(n) | Linear search |
| Nested loop (same size) | n² | O(n²) | Bubble sort |
| Nested loop (different sizes) | n × m | O(n×m) | Matrix multiplication |
| Triple nested loop | n³ | O(n³) | 3D grid traversal |
Performance Tip: If you have O(n²) nested loops processing large datasets (n > 10,000), consider algorithmic optimizations or data structure changes.
Parallel Streams (Modern Alternative)
For CPU-intensive operations on large collections, consider Java 8+ Streams:
1List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); 2 3// Sequential 4numbers.stream() 5 .map(n -> n * n) 6 .forEach(System.out::println); 7 8// Parallel (uses multiple CPU cores) 9numbers.parallelStream() 10 .map(n -> n * n) 11 .forEach(System.out::println);
Practice Programs
Exercise 1: Print Even Numbers 1 to 100
1public class EvenNumbers { 2 public static void main(String[] args) { 3 System.out.println("Even numbers from 1 to 100:"); 4 for (int i = 2; i <= 100; i += 2) { 5 System.out.print(i + " "); 6 } 7 System.out.println(); 8 } 9}
Exercise 2: Sum of Natural Numbers (while loop)
1import java.util.Scanner; 2 3public class SumNatural { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 System.out.print("Enter n: "); 7 int n = Integer.parseInt(input.nextLine()); 8 9 int sum = 0; 10 int i = 1; 11 12 while (i <= n) { 13 sum += i; 14 i++; 15 } 16 17 System.out.println("Sum = " + sum); 18 System.out.println("Formula check: " + (n * (n + 1) / 2)); 19 } 20 } 21}
Exercise 3: Reverse a Number (do...while)
1import java.util.Scanner; 2 3public class ReverseNumber { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 System.out.print("Enter a number: "); 7 int num = Integer.parseInt(input.nextLine()); 8 int reversed = 0; 9 10 do { 11 int digit = num % 10; 12 reversed = reversed * 10 + digit; 13 num /= 10; 14 } while (num != 0); 15 16 System.out.println("Reversed: " + reversed); 17 } 18 } 19}
Exercise 4: Fibonacci Series
1import java.util.Scanner; 2 3public class Fibonacci { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 System.out.print("Enter number of terms: "); 7 int n = Integer.parseInt(input.nextLine()); 8 9 int first = 0, second = 1; 10 11 System.out.print("Fibonacci: "); 12 for (int i = 1; i <= n; i++) { 13 System.out.print(first + " "); 14 int next = first + second; 15 first = second; 16 second = next; 17 } 18 System.out.println(); 19 } 20 } 21}
Exercise 5: Number Pyramid
1public class NumberPyramid { 2 public static void main(String[] args) { 3 int rows = 5; 4 5 for (int i = 1; i <= rows; i++) { 6 for (int j = 1; j <= i; j++) { 7 System.out.print(j + " "); 8 } 9 System.out.println(); 10 } 11 } 12}
Output:
11 21 2 31 2 3 41 2 3 4 51 2 3 4 5
Mini Project: Pattern Generator & Number Analyzer
Build an interactive console application that generates patterns and analyzes numbers using all loop types.
1import java.util.Scanner; 2 3public class PatternGenerator { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 boolean running = true; 7 8 while (running) { 9 System.out.println("\\n========== PATTERN & NUMBER TOOL =========="); 10 System.out.println("1. Star Pyramid"); 11 System.out.println("2. Inverted Star Pyramid"); 12 System.out.println("3. Number Diamond"); 13 System.out.println("4. Multiplication Table"); 14 System.out.println("5. Factorial Calculator"); 15 System.out.println("6. Prime Checker"); 16 System.out.println("7. Exit"); 17 System.out.print("Select option (1-7): "); 18 19 int choice = Integer.parseInt(input.nextLine()); 20 21 switch (choice) { 22 case 1 -> { 23 System.out.print("Enter rows: "); 24 int rows = Integer.parseInt(input.nextLine()); 25 for (int i = 1; i <= rows; i++) { 26 for (int s = 1; s <= rows - i; s++) System.out.print(" "); 27 for (int j = 1; j <= 2 * i - 1; j++) System.out.print("*"); 28 System.out.println(); 29 } 30 } 31 case 2 -> { 32 System.out.print("Enter rows: "); 33 int rows = Integer.parseInt(input.nextLine()); 34 for (int i = rows; i >= 1; i--) { 35 for (int s = 1; s <= rows - i; s++) System.out.print(" "); 36 for (int j = 1; j <= 2 * i - 1; j++) System.out.print("*"); 37 System.out.println(); 38 } 39 } 40 case 3 -> { 41 System.out.print("Enter size: "); 42 int n = Integer.parseInt(input.nextLine()); 43 // Upper half 44 for (int i = 1; i <= n; i++) { 45 for (int s = 1; s <= n - i; s++) System.out.print(" "); 46 for (int j = 1; j <= 2 * i - 1; j++) System.out.print(j); 47 System.out.println(); 48 } 49 // Lower half 50 for (int i = n - 1; i >= 1; i--) { 51 for (int s = 1; s <= n - i; s++) System.out.print(" "); 52 for (int j = 1; j <= 2 * i - 1; j++) System.out.print(j); 53 System.out.println(); 54 } 55 } 56 case 4 -> { 57 System.out.print("Enter number: "); 58 int num = Integer.parseInt(input.nextLine()); 59 System.out.println("\\nMultiplication Table of " + num + ":"); 60 for (int i = 1; i <= 10; i++) { 61 System.out.printf("%d × %2d = %3d%n", num, i, num * i); 62 } 63 } 64 case 5 -> { 65 System.out.print("Enter number: "); 66 int num = Integer.parseInt(input.nextLine()); 67 long factorial = 1; 68 for (int i = 2; i <= num; i++) { 69 factorial *= i; 70 } 71 System.out.println(num + "! = " + factorial); 72 } 73 case 6 -> { 74 System.out.print("Enter number: "); 75 int num = Integer.parseInt(input.nextLine()); 76 boolean isPrime = true; 77 if (num <= 1) { 78 isPrime = false; 79 } else { 80 for (int i = 2; i <= Math.sqrt(num); i++) { 81 if (num % i == 0) { 82 isPrime = false; 83 break; 84 } 85 } 86 } 87 System.out.println(num + (isPrime ? " is a prime number! ✅" : " is not prime. ❌")); 88 } 89 case 7 -> { 90 System.out.println("👋 Goodbye!"); 91 running = false; 92 } 93 default -> System.out.println("❌ Invalid choice."); 94 } 95 } 96 } 97 } 98}
What This Project Covers:
whileloop for the main menudo...whilebehavior via menu-driven designforloops for patterns and calculations- Nested loops for pyramid generation
breakfor prime optimizationswitchexpressions for menu handling- Input validation and formatted output
Summary & Cheat Sheet
Quick Reference
| Loop | Syntax | Best For |
|---|---|---|
for | for (init; cond; update) { } | Known iteration count |
while | while (cond) { } | Unknown count, may run zero times |
do...while | do { } while (cond); | Must run at least once |
Enhanced for | for (Type item : array) { } | Arrays and collections |
| Nested | Loop inside loop | 2D data, patterns |
Control Statements
| Statement | Effect |
|---|---|
break | Exit the loop immediately |
continue | Skip current iteration, go to next |
break label | Exit labeled outer loop |
Key Takeaways
foris your default — Use it when you know how many times to iterate.whileis for uncertainty — Use it when the iteration count depends on runtime conditions.do...whileguarantees execution — Use it for menus and prompts that must show at least once.- Enhanced
foris for reading — Use it to iterate arrays/collections cleanly, but remember it cannot modify primitives. - Nested loops multiply complexity — A loop of
ninside a loop ofmgivesn × miterations. breaksaves time — Exit early when you have found what you need.continuefilters efficiently — Skip irrelevant items without nestedifblocks.- Labels are powerful but rare — Use them for complex nested loop exits, but prefer method extraction for readability.
What's Next?
Now that you can repeat actions efficiently, you are ready to:
- Arrays — Store and loop through multiple values
- Collections —
ArrayList,HashMap, and the Java Collections Framework - Methods — Organize loop logic into reusable functions
- Recursion — Solve problems where a function calls itself
- Algorithms — Sorting, searching, and data structure traversal
Loops are the heartbeat of every program. Combined with arrays and collections, they let you process thousands — or millions — of data points with just a few lines of code.
Found this guide helpful? Bookmark it and share it with fellow learners. For more Java tutorials, explore the Tech3Space Java Course.
Tags: #Java #Loops #ForLoop #WhileLoop #DoWhile #ForEach #Programming #Tech3Space #CodingForBeginners