Menu
Courses / Java Basic / loops

loops

05 / 10 Part of Java Basic

Why Use Loops?


Loops let you repeat a block of code multiple times without writing it out manually. Java provides three main loop types: for, while, and do-while.



The for Loop


Best used when you know exactly how many times you want to repeat something.


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

The for loop has three parts separated by semicolons:



       
  • Initializationint i = 1 runs once, before the loop starts

  •    
  • Conditioni <= 5 is checked before every iteration; the loop stops once it's false

  •    
  • Updatei++ runs after every iteration



The while Loop


Best used when you don't know in advance how many times you'll loop — you just keep going until a condition becomes false.


int count = 1;

while (count <= 5) {
    System.out.println("Count: " + count);
    count++;
}


    Warning: Always make sure something inside the loop eventually makes the condition false. Forgetting to update count here would create an infinite loop that never stops.


The do-while Loop


Similar to while, but it checks the condition after running the loop body — guaranteeing the code runs at least once, even if the condition is false from the start.


int count = 1;

do {
    System.out.println("Count: " + count);
    count++;
} while (count <= 5);


The Enhanced for-each Loop


Used to iterate directly over the elements of an array or collection, without needing an index variable.


int[] numbers = {10, 20, 30, 40};

for (int num : numbers) {
    System.out.println(num);
}


break and continue


Two keywords give you finer control inside a loop:



break — exits the loop immediately


for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break; // stops the loop entirely once i reaches 5
    }
    System.out.println(i);
}
// Output: 1 2 3 4


continue — skips to the next iteration


for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        continue; // skips printing 3, but the loop keeps going
    }
    System.out.println(i);
}
// Output: 1 2 4 5


Nested Loops


A loop can contain another loop inside it — commonly used for working with grids or tables.


for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        System.out.println("i=" + i + ", j=" + j);
    }
}


Choosing the Right Loop



   
   
       
       
       
       
   
SituationBest Loop
Known number of repetitionsfor
Unknown repetitions, condition-basedwhile
Must run at least once regardless of conditiondo-while
Iterating over an array or collectionfor-each



    Coming up next: Arrays — how to store and work with collections of values under a single variable name.