Tino Intro To Java

Last modified: January 07, 2023

While Loops and For Loops

While Loop

The syntax of a while loop in Java looks virtually the same as that in JavaScript.

A while loop allows a set of code to be executed infinitely as long as a certain condition maintains true. Its syntax is:

while (condition) {
  // code block to be executed
}

In Java, there is another flavor of while loop called "do while loop".

A do while loop allows you to run the block of code first without checking the condition, and only checks the condition after the first loop is finished. This can be very useful in many situations.

Its syntax is:

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

For Loop

The syntax of a while loop in Java looks almost the same as that in JavaScript.

A for loop allows a set of code to be executed for a defined number of times. Its syntax is:

for (int something = any integer; something < or <= another integer; something++ or ++something){
    // code block to be executed
}

Here is an example:

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

Continue and break

Like in JavaScript, when you need to exit out of a loop immediately, you can use the break statement.

When you need to skip the current loop, you can use the continue keyword.

Example:

// the following code prints everything except 3
for (int i = 0; i < 5; i++){
    if (i == 3) {
        continue;
    }
    System.out.println(i);
}

Nested Loops

Loops, regardless if they are while or for, can be combined inside one another.

Here is an example:

public class Demo {
    public static void main(String[] args){
        for (int i = 0; i < 5; i++){
            bool isOk = true;
            while (isOk){
                for (int j = 0; j < 100; j++){
                    // do something here...
                }
            }
        }
    }
}

When having nested for loops, be extra careful about the variable names. In the above example, the first for loop has a variable name "i", while the second for loop has a variable name "j". Had the second variable's name also been "i", the loop can get VERY MESSED UP. So, when having nested for loops, use different variables names.

Dark Mode

Outline