🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Java Loops — for, while, do-while with Examples

Java BasicsLoops🟢 Free Lesson

Java Loops — for, while, do-while with Examples

Learning Objectives

  • Choose between for, while, and do-while loops
  • Trace loop initialization, condition, body, and update steps
  • Control loop flow with break and continue
  • Diagnose and fix infinite loops

Overview

A loop repeats a block of code while a condition holds. Loops power tasks such as printing a list of numbers, reading input until a sentinel value, searching an array, and retrying a failed network call. Java gives you three loop forms, and each fits a different habit of thought.

Every loop has four parts: something sets up state before repeating, a boolean condition decides whether another pass runs, the body does the work, and an update step changes state so the condition eventually becomes false.

The for Loop

Use a for loop when you know how many times to repeat. Its header packs three clauses: a start value, a continuation condition, and an update.

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

Execution flows in order. First int i equals 1 runs once. Then the condition is checked. If true, the body runs, then i plus plus executes, then the condition is checked again. The loop stops when the condition turns false. With the code above, the program prints five lines.

Common patterns include counting down, stepping by two, and starting from zero. Starting from zero matches array indexes, which always begin at zero in Java.

for (int i = 0; i < 10; i += 2) {
    System.out.print(i + " ");
}

The while Loop

Use a while loop when you do not know the count in advance but you do know the repeating condition. Check the condition before each pass.

int attempts = 3;

while (attempts > 0) {
    System.out.println("Attempts left: " + attempts);
    attempts--;
}

System.out.println("Done");

If you forget to change attempts inside the body, the condition never turns false and the loop runs forever. That is the classic infinite loop. Always ask what update will eventually end the loop before you write the first line of the body.

The do-while Loop

A do-while checks its condition after the body, so the body always runs at least once. It fits menus and prompts where you must ask the user something before you can decide whether to ask again.

int choice;

do {
    System.out.println("Enter 1 to continue or 0 to quit");
    choice = 1;
    System.out.println("Choice was: " + choice);
} while (choice == 1);

The only structural difference from while is the placement of the check. In real code, choice would come from user input; this simplified version shows the shape without needing a scanner yet.

Choosing the Right Loop

SituationPreferred loopWhy
Known count or array scanforCounter lives in the header
Unknown count, test firstwhileCondition is the driving state
Run at least once, then retestdo-whileGuarantees one execution
For each element of a collectionenhanced forClean read-only traversal

The enhanced for loop, sometimes called for-each, visits every element without writing an index. It is ideal for printing or summing when you do not need position information.

int[] values = {2, 4, 6, 8};
int total = 0;

for (int value : values) {
    total += value;
}

System.out.println(total);

break and continue

break exits the innermost loop immediately. continue skips the rest of the current pass and jumps to the next update and condition check. Use both sparingly; heavy use of break often signals that a helper method or clearer condition would read better.

for (int i = 0; i < 10; i++) {
    if (i == 3) {
        continue;
    }
    if (i == 7) {
        break;
    }
    System.out.print(i + " ");
}

That snippet prints 0 1 2 4 5 6 and then stops before 7.

Key Takeaways

💡

  • for fits counted repetition, while fits condition-driven repetition, do-while runs once first
  • Every loop needs an update that will eventually make the condition false
  • Enhanced for loops traverse collections cleanly without index math
  • break ends a loop; continue skips to the next iteration
  • If a loop hangs, inspect the update step first

Practice Questions

  1. Print the integers from 10 down to 1 using a for loop.
  2. Rewrite a for loop that sums the first 20 positive integers as a while loop.
  3. Explain why a do-while loop is a natural fit for a password retry prompt.

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Java Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement