Fundamentals 16 min read

Master Java Loop Statements: From Basics to Practical Examples

This article explains Java's loop constructs—including while, do‑while, for, nested loops, foreach, and bubble‑sort implementations—through detailed syntax descriptions, step‑by‑step execution processes, and multiple concrete code examples with expected outputs.

Lisa Notes
Lisa Notes
Lisa Notes
Master Java Loop Statements: From Basics to Practical Examples

while loop

Syntax:

while(逻辑表达式){
    语句块
}

Execution steps:

Evaluate the logical expression.

If the result is true, execute the statement block.

After the block finishes, re‑evaluate the expression.

Repeat steps 2‑3 until the expression evaluates to false, then exit the loop.

Example – sum of odd numbers not exceeding 50:

public class OddNumAddition {
    public static void main(String[] args) {
        int sum = 0;
        int num = 1; // first odd number
        while (num <= 50) {
            sum += num;
            num += 2; // next odd number
        }
        System.out.println("50 以内所有奇数的和是:" + sum);
    }
}

Program output:

50 以内所有奇数的和是:625

do‑while loop

Syntax:

do{
    语句或语句块
}while(逻辑表达式);

Execution steps:

Execute the statement block once.

Evaluate the logical expression.

If the result is true, repeat step 1; otherwise exit.

Example – sum of odd numbers not exceeding 100:

public class OddNumAddition {
    public static void main(String[] args) {
        int sum = 0;
        int num = 1;
        do {
            sum += num;
            num += 2;
        } while (num <= 100);
        System.out.println("100 以内所有奇数的和是:" + sum);
    }
}

Program output: 100 以内所有奇数的和是:2500 Demonstration of the loop‑body‑executed‑once property:

public class DoWhileTest {
    public static void main(String[] args) {
        boolean yesOrNo = false;
        int num = 0;
        do {
            num++;
        } while (yesOrNo);
        System.out.println("num=" + num);
    }
}

Output:

num=1

for loop

Syntax:

for(初始化表达式; 逻辑表达式; 迭代表达式){
    循环体
}

Execution steps:

Evaluate the initialization expression (executed once).

Evaluate the logical expression; if true, execute the body.

After the body, evaluate the iteration expression.

Repeat steps 2‑3 until the logical expression yields false.

Example – sum of integers from 1 to 100:

public class NumAddition {
    public static void main(String[] args) {
        int sum = 0;
        for (int num = 1; num <= 100; num++) {
            sum += num;
        }
        System.out.println("100 以内所有整数的和是:" + sum);
    }
}

Program output:

100 以内所有整数的和是:5050

Nested loops

Loops can be nested with the same or different types. Excessive nesting may degrade performance.

while‑while

while(条件1){
    while(条件2){
        ...
    }
}

do‑while‑do‑while

do{
    do{
        ...
    }while(条件1);
}while(条件2);

for‑for

for(初始化1; 条件1; 迭代1){
    for(初始化2; 条件2; 迭代2){
        ...
    }
}

Mixed combinations (e.g., while‑do‑while, while‑for, for‑while, etc.)

Example – fill and print an 8×8 two‑dimensional array where each element equals the sum of its indices:

public class NestedLoopTest {
    public static void main(String[] args) {
        int[][] array = new int[8][8];
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                array[i][j] = i + j;
            }
        }
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Program output (partial):

0 1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
2 3 4 5 6 7 8 9
3 4 5 6 7 8 9 10
4 5 6 7 8 9 10 11
5 6 7 8 9 10 11 12
6 7 8 9 10 11 12 13
7 8 9 10 11 12 13 14

Enhanced for (foreach) loop

Syntax:

for(元素类型 变量 : 数组或集合){
    循环体语句块
}

Used for traversing arrays or collections when the number of iterations is known. The loop variable type must match the element type, and the collection cannot be modified during iteration.

Example – iterate an int[] array:

int[] array = {1, 2, 3, 4, 5};
for (int ele : array) {
    System.out.println(ele);
}

Example – iterate a String[] array of names:

String[] names = {"王老师", "张老师", "李老师"};
for (String name : names) {
    System.out.println(name);
}

Bubble sort on a one‑dimensional array

Bubble sort repeatedly compares adjacent elements and swaps them if they are out of order, moving the largest unsorted element to the end of the array on each pass.

public class ArraySort {
    public static void main(String[] args) {
        int[] arr = {11, 22, 3, 44, 55};
        int len = arr.length;
        System.out.println("数组元素排序前的序列是:");
        for (int i = 0; i < len; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
        // Perform bubble sort
        for (int i = 0; i < len - 1; i++) {
            for (int j = 0; j < len - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        System.out.println("数组元素排序后的序列是:");
        for (int i = 0; i < len; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

Program output:

数组元素排序前的序列是:
11 22 3 44 55 
数组元素排序后的序列是:
3 11 22 44 55
Javaforeachbubble sortforwhilenested loopsdo-whileLoop Statements
Lisa Notes
Written by

Lisa Notes

Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.