[Java] [Introduction to Java] Repetitive processing (while, do-while, for, extended for, break, continue)

14 minute read

Purpose

Those who have just started learning programming including Java language, those who have already learned are for review, This time I am writing to learn about repeat processing, repeat control statement.

[Introduction to Java]Variables and typesType conversionVariable scopeCharacter string operationOperation of arrayOperatorConditional branch ・Repeat process ← Now here ・About class (in preparation) ・Abstract class (in preparation) ・Interface (in preparation) ・Encapsulation (in preparation) ・About module (in preparation) ・About exception handlingAbout lambda expressionAbout Stream API

What is iterative processing?

It is to repeat a certain process while the condition is met and specify the number of times.

``


int a = 0;
System.out.println("a => "+ a);
a += 1;
System.out.println("a => "+ a);
a += 1;
System.out.println("a => "+ a);

It is possible to clearly describe a series of processes such as outputting a as above, outputting +1 and outputting again by repeating the process.

Iteration is also called loop, and this article deals with while statement, do-while statement, for statement, and extended for statement.

while statement

While the specified condition is satisfied (true), repeat processing is performed.

syntax


while( conditional expression) {
  Processing statement; //Executed if the conditional expression is true
}

The conditional expression after while must be an expression that returns boolean value (true,false).

Example of

``

while statement
int num = 0;
while(num <5) {
  System.out.println("num => "+ num);
  num++;
}

execution result


num => 0
num => 1
num => 2
num => 3
num => 4

It is possible to clearly describe a series of processing such as outputting the variable that appeared at the beginning, +1 and outputting again. This process is repeated while num is less than 5, when incremented for each loop num becomes 5, The while statement ends because false is returned when the condition is judged.

While statement

infinite loop

Iterative processing may continue to be executed without stopping. Please note the following points.

Infinite loop example 1


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

If num++ is not written in this code, the num variable remains 0. Since the conditional expression num <5 continues to return true, it becomes an infinite loop.

``

 Infinite loop example 2
int num = 0;
while(true) {
  System.out.println("num => "+ num);
  num++;
}

Next, if you do while(true) in the conditional expression. This is also always returned as true, so it becomes an infinite loop.

The repeating control statement used to prevent an infinite loop (to exit the loop) is explained in another article. Let’s remember that as well.

loop does not start

``

 useless example
while(false) {
  // process
}

If the conditional expression is while(false), a compile error will occur because the processing cannot be started.

nothing is output

In some cases, no error is output, but nothing is output.

``

 example where nothing is output
int num = 0;
while(num> 0) {
  System.out.println("num => "+ num);
  num--;
}

Nothing is output for the above execution result. Because it is comparing whether the condition of while is greater than 0, false is returned suddenly and the process ends without entering the loop.

If you set the num variable to 1 or more, the processing in the loop is executed.

``

 Improvement plan
int num = 3;
while(num> 0) {
  System.out.println("num => "+ num);
  num--;
}

execution result


num => 3
num => 2
num => 1

do-while statement

Similar to the while statement, while the specified condition is satisfied (true)**, the processing is repeated.

syntax


do {
  Processing statement;
}while(conditional expression );

As with the while statement, the conditional expression must be an expression that returns a boolean value (true, false).

do-while statement

``` example of java

int num = 0; do { System.out.println(“num => “+ num); num++; while(num <5);



#### **` execution result`**
```text

num => 0
num => 1
num => 2
num => 3
num => 4

This process is repeated while num is less than 5, when incremented for each loop num becomes 5, Since false is returned when the condition is judged, the do-while statement ends.

Difference between #while statement and do-while statement

The timing of condition judgment is different.

In the while statement, the condition is judged first, so the processing may not be executed as described above. However, in the do-while statement, there is a do block before the condition judgment the condition judgment will be performed later. Therefore, the process is executed once regardless of the conditions.

``

 Condition judgment example_while
int num = 0;
while(num> 0) {
  System.out.println("while_num => "+ num);
  num--;
}

Nothing is output in the above while statement.

``

 Condition judgment example_do-while
int num = 0;
do {
  System.out.println("do-while_num => "+ num);
  num--;
}while(num> 0);

execution result


do-while_num => 0

In the do-while statement, the processing is executed only once, and the conditional expression is false, so the do-while statement is completed.

Be aware of these differences.

Common points between #while and do-while statements

When there is only one statement to process while statement and do-while statement, it is possible to omit {} and describe.

``

while
int num = 0;
while (num <5) System.out.println("num => "+ num++);

execution result


while_num => 0
while_num => 1
while_num => 2
while_num => 3
while_num => 4

do-while

```for java

int num = 5; do System.out.println(“do-while_num => “+ num–); while(num> 0);



#### **` execution result`**
```text

do-while_num => 5
do-while_num => 4
do-while_num => 3
do-while_num => 2
do-while_num => 1

for statement

For the for statement, while the condition judgment is true, iterative processing is executed.

In the while statement and do-while statement, only the conditional expression was written in (), In the () of the for statement, count variable declaration, initialization, conditional expression, and count variable update are performed.

syntax


for (Formula 1; Formula 2; Formula 3;) {
  Processing statement;
}

The flow of for statement is as follows.

  • In formula 1, declare and initialize a variable (counter variable) that indicates the number of iterations. ・The condition is judged by the formula 2.
  • When the condition judgment is true, the processing statement is executed.
  • After the processing is executed, the counter variable is updated by Expression 3.
  • Evaluate the condition again using Equation 2.
  • If the judgment in Expression 2 is false, the for statement is terminated.

Let’s actually see the code and the execution result.

Example of

``

for statement
for(int i = 0; i <5; i++) {
  System.out.println("i => "+ i);
}

execution result


i => 0
i => 1
i => 2
i => 3
i => 4

In this way, the same processing as the while statement and do-while statement can be written in the for statement.

For statement omitted

The for statement is also executed by the following description method.

Declaring counter variables and omitting initialization

``

for statement omitted description method_Example 1
int num = 0;
for(; num <5; num++) {
  System.out.println("num => "+ num);
}

execution result


num => 0
num => 1
num => 2
num => 3
num => 4

Instead of declaring and initializing the counter variable with the for statement, it is done in advance. The description method like this also works.### Omitting updating of counter variables

``

for statement omitted description method_Example 2
for(int num = 0; num <5;) {
  System.out.println("num => "+ num++);
}

execution result


num => 0
num => 1
num => 2
num => 3
num => 4

The num variable is incremented and updated in the processing statement. The description method like this also works.

Note that if you forget the increment, you will end up with a infinite loop.

For statement various description method and notes

There are some rules about how to write in () of for statement, so let’s see.

Expression 1 must be a sentence

The following is an error because it only describes variables in expression 1.

``

 compilation error
int num = 1;
for(num; num <5; num++) {
  System.out.println("num => "+ num);
}

Equation 1 must be a statement, as shown below.

``

 Improvement plan
int num = 1;
for(num += 1; num <5; num++) {
  System.out.println("num => "+ num);
}

execution result


num => 2
num => 3
num => 4

Expression 1 has only one declarative expression

The following is an error because multiple declaration expressions are written in expression 1.

``

 compilation error
for(int i = 0, int = j = 0; i <5; i++) {
  System.out.println("i => "+ i);
  System.out.println("j => "+ (j+=2));
  System.out.println("===============");
}

There must be only one declarative expression in expression 1 as shown below.

``

 Improvement plan
for(int i = 0, j = 0; i <5; i++) {
  System.out.println("i => "+ i);
  System.out.println("j => "+ (j+=2));
  System.out.println("===============");
}

execution result


i => 0
j => 2
===============
i => 1
j => 4
===============
i => 2
j => 6
===============
i => 3
j => 8
===============
i => 4
j => 10
===============

Expression 3 can be entered multiple times

By separating the expression with a comma, you can insert multiple update processing of the counter variable. Let’s rewrite the above code.

``

 Example of putting multiple in Expression 3
for(int i = 0, j = 2; i <5; i++, j+=2) {
  System.out.println("i => "+ i);
  System.out.println("j => "+ j);
  System.out.println("===============");
}

execution result


i => 0
j => 2
===============
i => 1
j => 4
===============
i => 2
j => 6
===============
i => 3
j => 8
===============
i => 4
j => 10
===============

You can output the same result.

Extended for statement

As a more convenient way to write the for statement, use it to retrieve all elements of an array or collection in order and process them.

syntax


for (variable declaration: reference variable name) {
  Processing statement;
}

Let’s actually see the code and the execution result.

``

 Example of extended for statement
int[] numbers = {1, 2, 3, 4, 5};
for(int val :numbers) {
  System.out.println(val);
}

execution result


val => 1
val => 2
val => 3
val => 4
val => 5

The flow of assigning each element of numbers to the val variable and outputting it is repeated.

Let’s compare the same processing by writing it in a for statement.

In case of

``

for statement
int[] numbers = {1, 2, 3, 4, 5};
for(int i = 0; i <numbers.length; i++) {
  System.out.println("numbers[" + i + "] => "+ numbers[i]);
}

execution result


numbers[0] => 1
numbers[1] => 2
numbers[2] => 3
numbers[3] => 4
numbers[4] => 5

By describing with an extended for statement, the description of counter variable declaration, initialization, conditional expressions, and counter variable update processing becomes unnecessary. It can be described more simply than the for statement.

Notes on extended for statement

The type declared in the variable must match the type of the referenced variable. The following is an error.

``

 compilation error
String[] names = {"Tanaka", "Sato", "Suzuki"};
for(int val :names) {
  System.out.println("name => "+ val);
}

While the reference variable is an array of String type, the variable declaration is an int type.

Be careful to match the type of the reference variable and the variable that receives each element.

``

 Improvement plan
String[] names = {"Tanaka", "Sato", "Suzuki"};
for(String val :names) {
  System.out.println("name => "+ val);
}

execution result


name => Tanaka
name => Sato
name => Suzuki

Common point between #for statement and extended for statement

**If there is only one statement that processes both for statement and extended for statement, you can omit {} and describe it. **

In case of

``

for statement
for(int i = 0; i <3; i++)
  System.out.println("i => "+ i);

execution result


i => 0
i => 1
i => 2

For extended for statement


int[] numbers = {10, 20, 30};
for(int val: numbers)
  System.out.println("val => "+ val);

execution result


val => 10
val => 20
val => 30

** Local variable type inference (var) can be used. ** (I will write about local variable type inference in another article.)

In case of

``

for statement
for(var i = 0; i <3; i++) {
  // omitted
}

For extended for statement


for(var val :numbers) {
  // omitted
}

What is a repeat control statement

The iterative process described above was that conditions continue to be executed while true.

If you want to exit the iteration process under a specific condition, use the break control statements break statement and continue statement.

break statement

It is used to exit the current iteration process by interrupting it, or to exit the infinite loop of repeated statements. It is also used in the case of switch statement.

After exiting the loop, execute the following processing.

Example of

``

break statement
for(int i = 0; ;i++) {
  if(i == 5) {
    break;
  }
  System.out.println("i => "+ i);
}
System.out.println("processing after the for statement");

execution result


i => 0
i => 1
i => 2
i => 3
i => 4
Processing after the for statement

There is no conditional expression because you have forgotten to write expression 2. Therefore, it becomes an infinite loop. However, since there is a break; in the block of if(i == 5), the loop will be exited when **i becomes 5. **

And the processing after the for statement is executed.

continue statement

It is not used for interrupting the repetitive process being executed, but for skipping that process only, to perform conditional expression judgment and use it when continuing the repetitive process.

Example of

``

continue statement
for(int i = 0; i <10; i++) {
  if((i %3) == 0) {
    continue;
  }
  System.out.println("i => "+ i);
}
System.out.println("processing after the for statement");

execution result


i => 1
i => 2
i => 4
i => 5
i => 7
i => 8
Processing after the for statement

Since there is continue; in the block of if((i %3) == 0), ** Divide i by 3 and skip the process when the remainder is 0. (The loop continues as long as the condition judgment of Expression 2 is true)**

Then, after the for statement is completed, the subsequent processing is executed.

Label common to #break and continue statements

When the repeated statement is nested (when there are multiple), the break statement and continue statement described in the inner repeated statement are applied only to the inner repeated processing. If you want to get out of the outer loop or skip it, you can use the label.

syntax


Label name:
for (Formula 1; Formula 2; Formula 3;) {
  for (Formula 1; Formula 2; Formula 3;) {
    break or continue label name;
  }
}

Let’s see how the processing differs depending on the presence or absence of a label in the break statement and continue statement.

For ##break statement

If you do not use the label, it will be as follows. I want to end the loop when i and j are 1. I am implementing it on the assumption.

``

 no label
for(int i = 0; i <3; i++) {
  for(int j = 0; j <3; j++) {
    System.out.println("i: "+ i + ", j: "+ j);
    if(i == 1 && j == 1) {
      break;
    }
  }
}

execution result


i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
i: 1, j: 0i: 1, j: 1
i: 2, j: 0
i: 2, j: 1
i: 2, j: 2

The loop does not end, i is incremented and the next loop is entered.

If you use the label, it will be as follows.

``

 with label
loop:
for(int i = 0; i <3; i++) {
  for(int j = 0; j <3; j++) {
    System.out.println("i: "+ i + ", j: "+ j);
    if(i == 1 && j == 1) {
      break loop;
    }
  }
}

execution result


i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
i: 1, j: 0
i: 1, j: 1

When i and j are 1, the outer loop can be pulled out.

For continue statements

If you do not use the label, it will be as follows. I want to skip to the next loop that increments i when i and j are 1. I am implementing it on the assumption.

``

 no label
for(int i = 0; i <3; i++) {
  for(int j = 0; j <3; j++) {
    if(i == 1 && j == 1) {
      continue;
    }
    System.out.println("i: "+ i + ", j: "+ j);
  }
}

execution result


i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
i: 1, j: 0
i: 1, j: 2
i: 2, j: 0
i: 2, j: 1
i: 2, j: 2

Only skipped when i and j are 1.

If you use a label, it looks like this:

``

 with label
loop2:
for(int i = 0; i <3; i++) {
  for(int j = 0; j <3; j++) {
    if(i == 1 && j == 1) {
      continue loop2;
    }
    System.out.println("i: "+ i + ", j: "+ j);
  }
}

execution result


i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
i: 1, j: 0
i: 2, j: 0
i: 2, j: 1
i: 2, j: 2

When i and j are 1, we can skip to the next loop that increments i.

In this way, by using the label, it is possible to get out of the multiple loop and skip.

At the end

You learned the syntax for repeating the same process and the repeat control statement for interrupting or skipping the process depending on the condition. By using them properly, I can write the code neatly, and I do not have to write the same processing many times, so I would like to master it.

Reference site

** [Introduction to Java] Let’s master iterative processing! (for and while)** Extended for sentence (for-each sentence)