Java Tutorial menu

Java Loops

A loop runs the same block of code again and again while a condition is true.

The while Loop

A while loop checks the condition first, then runs the block:

Example

java
public class Main {
  public static void main(String[] args) {
    int count = 1;
    while (count <= 3) {
      System.out.println("Count: " + count);
      count++;
    }
  }
}
Output
Count: 1
Count: 2
Count: 3

Always change the loop variable inside the loop. If count never grows, the condition stays true forever and you get an infinite loop.

The do...while Loop

A do...while loop runs the block once first, then checks the condition. It always runs at least one time:

Example

java
int n = 10;
do {
  System.out.println("n is " + n);
  n++;
} while (n < 5);
Output
n is 10

The for Loop

Use for when you know how many times to repeat. It puts the start, the condition and the step on one line:

Example

text
for (start; condition; step) {
  // code
}

Example

java
public class Main {
  public static void main(String[] args) {
    // 7 times table
    for (int i = 1; i <= 5; i++) {
      System.out.println("7 x " + i + " = " + (7 * i));
    }
  }
}
Output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

The for-each Loop

The for-each loop goes through every item in an array, one by one:

Example

java
public class Main {
  public static void main(String[] args) {
    String[] fruits = {"Mango", "Banana", "Guava"};
    for (String fruit : fruits) {
      System.out.println(fruit);
    }
  }
}
Output
Mango
Banana
Guava

break and continue

KeywordWhat it does
breakLeaves the loop completely
continueSkips the rest of this round and goes to the next one

Example

java
public class Main {
  public static void main(String[] args) {
    for (int i = 1; i <= 10; i++) {
      if (i == 4) {
        continue;   // skip 4
      }
      if (i == 7) {
        break;      // stop at 7
      }
      System.out.print(i + " ");
    }
  }
}
Output
1 2 3 5 6 

Adding Numbers with a Loop

Loops are often used to build a total:

Example

java
int sum = 0;
for (int i = 1; i <= 100; i++) {
  sum += i;
}
System.out.println("Sum: " + sum);
Output
Sum: 5050

Exercise

Exercise

Which loop always runs its block at least once?

Learn Java with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp