JavaRush /Java Blog /Random EN /Loops in Java

Loops in Java

Published in the Random EN group

What are cycles

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

  2. Loops with postcondition: The execution condition is determined after the first iteration (so they are always executed at least once). Useful when you need to perform a certain action until a certain condition is realized: for example, reading 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. Each iteration the counter is increased. We can determine the number of iterations in advance.

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

    There are cases where the execution of a 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 looping through all the numbers using a for loop. But when we find the first negative number, we don't have to go through the remaining numbers. We can interrupt the execution of the loop if its further execution does not make sense. Such situations are called cycle interruption.

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

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

    You can learn more about loops in the Java programming language at level 4 of the JavaRush 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 language:
  • while— loop with precondition;
  • do..while— a cycle with a postcondition;
  • for— loop with a counter (loop for);
  • for each..— a “for each…” loop — a type of for for iterating through 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 training in the JavaRush course. For example, for and while loops. Let us briefly consider each of the presented types.

while loop

This loop in Java looks like this:
while (expression) {
     statement(s)
}
Here:
  • expression— a loop condition, an expression that should return booleana value.
  • statement(s)— loop body (one or more lines of code).
Before each iteration, the value of the expression will be calculated expression. If the result of the expression is 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) {
    // тело цикла
}
To interrupt the execution of a loop, the operator is used 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 at level 4 of the JavaRush course.

do..while loop

The structure do.. whilelooks like this:
do {
     statement(s)
} while (expression);
Here:
  • expression— a loop condition, an expression that should 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 result of the expression is 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:
  • initialization— an expression that initiates execution of the loop. Executed only once at the beginning of the loop. Most often, this expression initializes the loop counter
  • terminationbooleanan expression that regulates the end of the loop. If the result of the expression is false , the loop forwill break.
  • increment— an expression that is executed after each iteration of the loop. Most often, this expression involves incrementing or decrementing a counter variable.
  • statement(s)— body of the cycle.
The expressions initialization, termination, incrementare optional. If we omit each of them, we get an infinite loop:
// бесконечный цикл
for ( ; ; ) {
    // code тела цикла
}
Example loop 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
A workshop on the for loop is presented at level 4 of the JavaRush course.

Loop for each

This Java loop is a type of loop forfor iterating collections and arrays. The structure for eachlooks like this:
for (Type var : vars) {
    statement(s)
}
Here:
  • vars- variable, existing list or array
  • Type var— defining a new variable of the same type ( Type) as the collection vars.
This construction can be read as follows: “For each var from vars, make...”. Let's say we have an array of strings of 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 studied in the JavaRush 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