JavaRush /Java Blog /Random EN /Loops in Java

Loops in Java

Published in the Random EN group

What are cycles

A program written in the Java language consists of certain code. Usually it is executed sequentially: line by line, from top to bottom. But there are also code constructs that change the linear execution of the program. They are called control constructs . Loops in Java - 1Thanks to them, the code can be executed selectively. For example, run one block of code instead of another. Loops are a kind of control constructs for organizing the repeated execution of the same piece of code. The code inside such a control structure is executed cyclically. Each code execution is an iteration of the loop . The number of iterations is controlled by the loop condition. The code that runs inside the loop is called the loop body . Suchtypes of cycles :
  1. Precondition Loops: The execution condition is defined before the first iteration.

  2. Post-conditional loops: The execution condition is determined after the first iteration (so they always execute at least once). Useful when you want to perform some action until some condition is met: for example, read the user's input until he enters the word "stop".

  3. Counter Loops: The number of iterations is determined by the simulated counter. The loop condition specifies its initial and final values. The counter is incremented every iteration. We can predetermine the number of iterations.

    These loops are useful when you need to loop through all the elements in a collection. Loops with a counter are called "loops for...". “For each element of some collection, perform the following actions.”

    There are cases where the execution of the loop can be interrupted before its condition is reached. For example, if we have a collection of 100 numbers and we need to understand if it contains negative numbers. We can start iterating over all the numbers using the “for” loop. But when we find the first negative number, we don't have to iterate over the remaining numbers. We can interrupt the execution of the loop if its further execution does not make sense. Such situations are called loop breaks.

  4. Unconditional loops are loops that run indefinitely. For example: “While 1=1, print “1=1””. Such a program will continue to run until it is manually interrupted.

    These loops are also useful when used in conjunction with breaking the loop "from the inside". Use them carefully so as not to cause the program to freeze.

    You can learn more about loops in the Java programming language at the 4th level of the CodeGym course. Particularly with while and for loops.

Loops in Java

Now let's look at loops in Java. There are several types of them in this PL:
  • while— loop with precondition;
  • do..while— loop with postcondition;
  • for— loop with counter (loop for);
  • for each..— the “for each…” loop is a kind of for for iterating over a collection of elements.

while, do.. whileand forcan be used as unconditional loops. You can compare the syntax of loops in different programming languages ​​at the fourth level of the CodeGym course. For example for and while loops. Let's take a brief look at each of these types.

while loop

This loop in Java structurally looks like this:
while (expression) {
     statement(s)
}
Here:
  • expressionis a loop condition, an expression that must return booleana value.
  • statement(s)- loop body (one or more lines of code).
Before each iteration, the value of the expression will be evaluated expression. If the expression evaluates to true , the body of the loop is executed - statement(s). Example:
public class WhileExample {
    public static void main(String[] args) {
        int countDown = 10;

        while (countDown >= 0) {
            System.out.println("До старта: " + countDown);
            countDown --;
        }

        System.out.println("Поехали !");

    }
}
Conclusion:

До старта: 10
До старта: 9
До старта: 8
До старта: 7
До старта: 6
До старта: 5
До старта: 4
До старта: 3
До старта: 2
До старта: 1
До старта: 0
Поехали !
Using while, you can create an infinite loop:
while (true) {
    // тело цикла
}
The statement is used to break the loop break. For example:
public class WhileExample {
    public static void main(String[] args) {

        int count = 1;
        while (true) {
            System.out.println("Строка №" + count);
            if (count > 3) {
                break;
            }
            count++; // Без наращивания цикл будет выполняться вечно
        }

    }
}
Conclusion:

Строка №1
Строка №2
Строка №3
Строка №4
You can practice writing your own loops already at the 4th level of the CodeGym course.

do..while loop

The structure do.. whilelooks like this:
do {
     statement(s)
} while (expression);
Here:
  • expressionis a loop condition, an expression that must return booleana value.
  • statement(s)- loop body (one or more lines of code).
Unlike while, the value of expression will be evaluated after each iteration. If the expression evaluates to true , the body of the loop will be executed again - statement(s)(at least once). Example:
public class DoWhileExample {
    public static void main(String[] args) {
        int count = 1;
        do {
            System.out.println("count = " + count);
            count ++;
        } while (count < 11);
    }
}
Conclusion:

count = 1
count = 2
count = 3
count = 4
count = 5
count = 6
count = 7
count = 8
count = 9
count = 10

for loop

This Java loop looks like this:
for (initialization; termination; increment) {
    statement(s)
}
Here:
  • initializationis an expression that initializes the execution of the loop. It is executed only once at the beginning of the loop. Most often, in this expression, the loop counter is initialized
  • termination- booleanan expression that regulates the end of the loop execution. If the expression evaluates to false , the loop forwill break.
  • incrementis an expression that is executed after each iteration of the loop. Most often, in this expression, the counter variable is incremented or decremented.
  • statement(s)is the body of the loop.
The expressions initialization, termination, incrementare optional. If we omit each of them, we get an infinite loop:
// бесконечный цикл
for ( ; ; ) {
    // code тела цикла
}
Loop example for:
public class ForExample {

    public static void main(String[] args) {
        for (int i = 1; i < 6; i++) {
            System.out.println("Строка №" + i);
        }
    }
}
Conclusion:

Строка №1
Строка №2
Строка №3
Строка №4
Строка №5
The for loop practice is presented at the fourth level of the CodeGym course.

for each loop

This Java loop is a kind of loop forfor iterating over collections and arrays. The structure for eachlooks like this:
for (Type var : vars) {
    statement(s)
}
Here:
  • vars- variable, existing list or array
  • Type var— definition of a new variable of the same type ( Type) as the collection vars.
This construction can be read like this: “For each var from vars, make ...”. Suppose we have an array of strings from the names of the days of the week. Let's print each element of this array:
public class ForExample {

    public static void main(String[] args) {
        String[] daysOfWeek =
                { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };


        for (String dayOfWeek : daysOfWeek) {
            System.out.println(dayOfWeek);
        }
    }
}
Java loops are taught in the CodeGym course at the fourth level of the Java Syntax quest. Try your hand at solving problems on this topic :) Loops in Java - 2
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION