JV

Java Fundamentals

19 lessons

Progress0%
1. Introduction to Java
1What is Java?
2. Variables and Data Types
1Primitive Types
3. Control Flow
ConditionalsLoops
4. Methods
Defining MethodsMethod Overloading
5. Object-Oriented Programming
Classes and ObjectsInheritanceInterfaces and Abstract Classes
6. Collections
ArrayList and LinkedListHashMap and HashSet
7. Exception Handling
Checked & Unchecked Exceptionstry-with-resources & Custom Exceptions
8. Generics
Generic Classes & MethodsWildcards & Type Erasure
9. Modern Java
Lambdas & Functional InterfacesStream API & Optional
10. File I/O
java.nio.file APIBuffered I/O & try-with-resources
All Tutorials
JavaControl Flow
Lesson 4 of 19 min
Chapter 3 · Lesson 2

Loops

Loops in Java

Java provides four loop constructs to repeat blocks of code.

for loop Best when the number of iterations is known. Consists of an initializer, condition, and update:

java
for (int i = 0; i < 10; i++) { … }

while loop Checks the condition before each iteration. Use when iterations are unknown:

java
while (input != null) { … }

do-while loop Executes the body at least once, then checks the condition:

java
do { … } while (condition);

for-each (enhanced for) loop Iterates over arrays and Iterable collections without an index:

java
for (String item : items) { … }

break and continue

  • break exits the nearest enclosing loop immediately.
  • continue skips the remainder of the current iteration and moves to the next.

Key points:

  • Prefer the for-each loop when you don't need the index — it is less error-prone.
  • Avoid modifying a collection while iterating it with for-each (use an Iterator instead).
  • Label + break can exit nested loops: outer: for(…) { … break outer; }.

Code Examples

for, while, and do-whilejava
public class Loops {
    public static void main(String[] args) {
        // for loop
        int sum = 0;
        for (int i = 1; i <= 5; i++) {
            sum += i;
        }
        System.out.println("Sum 1-5: " + sum);

        // while loop
        int n = 1;
        while (n < 32) {
            n *= 2;
        }
        System.out.println("First power of 2 >= 32: " + n);

        // do-while
        int count = 0;
        do {
            count++;
        } while (count < 3);
        System.out.println("Count: " + count);
    }
}

do-while always executes the body at least once. The while loop may never execute if the condition is false initially.

for-each, break, and continuejava
public class ForEachDemo {
    public static void main(String[] args) {
        String[] fruits = {"apple", "banana", "cherry", "date", "elderberry"};

        // for-each with continue
        System.out.println("Fruits not starting with 'b':");
        for (String fruit : fruits) {
            if (fruit.startsWith("b")) continue;
            System.out.println("  " + fruit);
        }

        // for with break
        System.out.println("First fruit longer than 5 chars:");
        for (String fruit : fruits) {
            if (fruit.length() > 5) {
                System.out.println("  " + fruit);
                break;
            }
        }
    }
}

continue skips the current iteration; break exits the loop entirely. for-each is idiomatic for array/collection traversal.

Quick Quiz

1. Which loop always executes its body at least once?

2. What does `continue` do inside a loop?

Was this lesson helpful?

PreviousNext