Infinite for (Java) loop

In Java, as in almost any programming language, there are tools to ensure the repetition of a certain piece of code, or, as they are commonly called, loops. Java loops are represented by operators such as for and while, as well as their variations. As a rule, loops are used to go through one-dimensional and multi-dimensional arrays and iterable data structures (including collections) in order to find certain elements and further operations with them. However, this is not the only way to use a tool like the Java loop. Use cases will be provided as they are reviewed.

Java while loop : description and examples

The underlying loop operator in Java is while. A code fragment enclosed in its body will be repeated until the condition of the expression enclosed in brackets after it satisfies the logical value of truth. The general form of the while statement is as follows:

while (condition) {

// loop body

}

As soon as the value of the logical condition ceases to be true, the code enclosed in the body of the loop will cease to be executed and control will be transferred to the line immediately after it.

loops in java
If only one operator is enclosed in the loop body, then curly brackets can be omitted, however, it is considered a good form if they always stand. The figure above shows a block diagram of the operation of this operator.

For clarity, let's analyze the example presented in the figure below:

while java loop

The declared variable count initially has a value of 1. Next, we see a logical expression enclosed in brackets after the name of the operator. It will be true, i.e. return true, until the value of the count variable is less than or equal to 10. In the body of the loop, with each pass (iteration), the value of the variable increases by 1 and is displayed on the console screen. Please note that when the value of the variable reached 11, the loop stopped working.

If the value of the count variable was initially equal to 11, then the loop condition would be false, and the program would not even go into its body.

It is worth noting that Java syntax allows you to use a while statement without a body. We give an example. Suppose we have two variables i = 100 and j = 200, we are faced with the task of programmatically calculating their arithmetic mean - for this we can use the β€œhollow” while:

while (++ i <--j);

As a result, the value of either of the two variables will be equal to the average of their initial values. As you can see, the cycle worked perfectly without the body and performed all the necessary actions in conventional terms.

Do-while loop

In the previous examples, if the conditional expression initially returned false, then program execution would ignore the body of the loop and go further. However, situations often arise in which the execution of the code contained in the body of the loop is mandatory at least once, regardless of the truth of the conditional expression. In other words, it happens that checking the truth of a conditional expression is required not at the beginning, but at the end of the cycle. Such functionality can provide a kind of while loop called do-while. It has the following form:

do {
// loop body

} while (condition);

As we can see, the body of the loop goes to execution first, and only then the truth of the condition is checked - and so on each iteration.

java loop examples

The code above will work in much the same way as with the usual while. However, if we set the count variable to 11, the body of the loop would still execute once before the operator could verify the truth of the expression.

Description and examples for - Java loop

The for loop is a universal and efficient language form in Java. Before the fifth version of the Java SDK, there was only one traditional form of the for statement, and after the new one appeared - for each. In this section, we will familiarize ourselves with the traditional form of the operator. for Java loop looks like this:

for java loop

Before control is transferred to the code in the body of the loop, the variable i, which acts as a counter, is initialized first. Next, a conditional expression is checked, in which the counter is compared with a certain value, and if it returns true, the body of the loop is executed. Then the counter value changes to a predetermined step and the conditional expression is checked again, and so on, until the condition becomes false. The flow chart below illustrates all stages of the cycle.

for java loop

For a better understanding, here is an example of how the for Java loop works:

for java loop

We see that the loopVal variable is used as the counter. After each iteration of the loop, its value will increase by 1, and this will happen until it reaches 11. Note that the control variable can also be declared outside the for statement, but if you are not going to use this variable anywhere except in a loop, it is recommended to declare it directly in the statement. Keep in mind that the variable declared in the statement itself has scope within this loop itself.

There are situations when you need to declare several variables that control the cycle. For Java loop allows you to specify two or more variables separated by commas, and to do this both during their initialization and during iteration. Such an operator will have the following form:

for (int i = 1, int j = 10; i <j; ++ i, --j) {}

At each iteration, the value of the variable i will increase by 1, and the value of the variable j will decrease by 1. Iterations will be performed until i becomes greater than or equal to j.

Features of using the for statement

The for loop is a fairly flexible construct, since all three of its parts (initialization, condition, and increment / decrement) can be used for other purposes. For example, instead of a conditional expression with a control variable, you can substitute any logical variable.

boolean exit = false;

for (int i = 0;! exit; ++ i) {

exit = true;

}

In the example above, we can observe how the operation of the cycle is absolutely independent of the control variable i and the number of iterations depends solely on the moment at which the variable exit becomes true. Moreover, the control variable can be completely removed from the loop and this will not affect its operation in any way: for (;! Exit;) {}. Although this is not the most sensible way of programming, it can sometimes be useful. The main thing is to provide a situation in which the variable will take the value necessary to exit the loop so as not to turn it into infinite.

For Java loop can be declared in this way: for (;;) {}. This is a typical example of an infinite loop with special interrupt conditions. About how to interrupt this kind of cycles, we will talk a little later.

For each loop

The foreach Java loop is always used to iterate over the elements of an array or any data structure in sequence and perform certain repetitive operations on them. An example of this form of the for statement is presented below:

foreach java loop

Name is declared as an iterative variable, and the array of names strings declared earlier acts as the second argument of the operator. The variable name will alternately take on the values ​​of each element of the array until all its elements are retrieved. It should be noted that the type of the variable must be compatible with the type of elements that are stored in the array. Also, the name variable is read-only and attempting to change it will not lead to a change in the element itself in the array.

Loop interrupt statements

There are three loop interrupt statements: break, return, and continue. The first two are able to completely interrupt the operation of the loop, and continue interrupts only the operation of the current iteration. If you use a deliberately infinite Java loop in your code, these operators must be present in it. Consider a simple break example:

exit java loop

Although this for statement has 11 iterations, only 8 will be executed, because when the counter i is 7, a condition will work that has a break statement in its body.

The return statement acts in a similar way, with the difference that it not only provides an exit from the Java loop, but also from the method in which this loop is placed.

Using break as goto

It should be borne in mind that break interrupts the operation of only the cycle in which it is located directly in the body, i.e. if you use it in a nested loop, the outer loop will not stop working. To do this, the break statement can be used as a civilized form of goto.

In this version, this operator is used in conjunction with a label, which allows you to organize an exit not only from loops, but also from any block of code. A label is an appropriately named identifier followed by a colon. The label is declared at the beginning of the marked block of code. To interrupt the execution of the marked block, in the right place you need to declare: break label_name. Consider the example in the figure below:

java infinite loop

Three blocks are declared in the code with the label names One, Two, and Three, respectively. The break statement with the Two label is nested in all three blocks, but when it is triggered, the program will exit the Three and Two blocks and continue execution in the One block. Those. in the console we will see two messages: Three and One.

Conclusion

We got acquainted with the concept of loops in Java, the main while and for statements, as well as their do-while and for each forms, respectively. For a better understanding, we recommend that you do the exercises using these operators in various forms, as well as various ways of interrupting them and moving from one block to another.

Source: https://habr.com/ru/post/K947/


All Articles