Java Basics – Part 2: Control Flow and Loops

Java Basics – Part 2

1 if / else Statements

Conditions must be inside parentheses ( ).

double number = Math.random();

if (number < 0.33) {
    System.out.println("Small");
} else if (number > 0.66) {
    System.out.println("Large");
} else {
    System.out.println("Medium");
}

You can also use the ternary operator:

String result = number < 0.5 ? "Low" : "High";

2 for Loop

for (int i = 0; i < 10; i++) {
    System.out.print(i + " ");
}

Floating-point or countdown loops:

for (double i = 2; i > -2; i -= 0.5) {
    System.out.print(i + " ");
}

Infinite loop (use break to exit):

for (;;) {
    double x = Math.random();
    if (x < 0.03) break;
    System.out.print("Running ");
}

3 while Loop

Head-controlled: condition checked before the block.

int i = 0;
while (i < 5) {
    System.out.println("Hello");
    i++;
}

Use break to exit early or continue to skip one iteration.

4 do-while Loop

Foot-controlled: condition checked after the block → runs at least once.

int i = 0;
do {
    System.out.println("Hello");
    i++;
} while (i < 5);

Practical example: retry a connection until successful.

5 Comparing while vs do-while

double n = Math.random();

while (n < 0.5) {
    System.out.println("Hit while");
    n = Math.random();
}

do {
    System.out.println("Hit do-while");
    n = Math.random();
} while (n < 0.5);

6 Nested Loops and Break/Continue

for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 3; col++) {
        if (col == 2) continue; // skip column 2
        System.out.println(row + "," + col);
    }
}

Summary

  • if-else chooses code based on conditions.
  • for, while, do-while control repetition.
  • Use break / continue for loop control.
  • Random values demonstrate conditional branching.

Leave a Reply

Your email address will not be published. Required fields are marked *