Skip to main content

Command Palette

Search for a command to run...

8) Loops In Java

The way of iterating in Java

Updated
•3 min read•View as Markdown
8) Loops In Java
A

Product-oriented Software Engineer with a solid understanding of web programming fundamentals and software development methodologies such as agile and scrum.

Loops allow you to execute a block of code repeatedly as long as a specified condition is true. Java supports several types of loops.

For Loop

for (initialization; condition; increment/decrement) {
    // Code to be executed
}

Example: Counting from 1 to 5

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

// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5

Example: Looping through an Array

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

for (int i = 0; i < numbers.length; i++) {
    System.out.println("Element: " + numbers[i]);
}

While Loop

while (condition) {
    // Code to be executed
}

Example: Counting from 1 to 5

int i = 1;

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

Do-While Loop

This loop will execute the code block at least once because the condition is checked after the loop body.

do {
    // Code to be executed
} while (condition);

Example: Counting from 1 to 5

int i = 1;

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

For-Each Loop

The for-each loop is used to iterate over arrays or collections.

for (dataType element : arrayName) {
    // Code to be executed
}

Example: Iterating over an Array

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

for (int number : numbers) {
    System.out.println("Number: " + number);
}

Loop Control Statements

Break

Exits the loop immediately.

Example

for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        break;  // Exits the loop when i is 3
    }
    System.out.println("i = " + i);
}

// Output:
// i = 1
// i = 2

Continue

Skips the current iteration and moves to the next one.

Example

for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        continue;  // Skips the iteration when i is 3
    }
    System.out.println("i = " + i);
}

// Output:
// i = 1
// i = 2
// i = 4
// i = 5

My Recommendation

We should use…

  • for loop when the number of iterations is known.

  • while loop when the number of iterations is unknown, but a condition is given.

  • do-while when you need the loop to run at least once.

  • for-each when iterating over arrays or collections.

Learning Java

Part 9 of 26

In this series, I will break down the task of learning java into smaller actionable steps and work on them topic by topic while trying to provide observability into my learning process.

Up next

9) Strings in Java

Fundamental knowledge to effectively interact with strings in Java