In today's free Java lesson, we will analyze loops – that is, the way in which we can execute a part of our program multiple times by writing the code only once. Java offers us three different types of loops to cover all scenarios: the while loop, the do-while loop, and the for loop.
WHILE LOOP
The while loop has the characteristic of executing a block of code as long as its condition remains true. If the condition that the while loop checks returns false, then the while loop stops executing its code and proceeds with the execution of the rest of the program.
The general syntax that defines the while loop is as follows:
While(Boolean_expression)
{
//Statements
}
The beginning of a while loop is defined by the keyword while
. Immediately after, inside parentheses, follows the condition whose result will determine whether the code inside the while loop will execute or not. As long as the condition returns true
, the while loop will continue to execute. If the condition becomes false
, then Java skips the code inside the while loop and continues with the rest of the program.
Let's look at a simple while loop example before we discuss one more important detail.
App.java
package com.example;
public class App {
public static void main(String[] args) {
int x = 1;
while (x <= 10) {
System.out.println(x);
x++;
}
}
}
Output
What we need to observe in this simple example is the line of code that increases the value of the variable x
by 1. This means that each time the while loop is executed, we affect the value of the x
variable so that eventually the condition of the while loop becomes false
, and the repetition cycle is completed. If you don’t make sure to include some code inside the loop that changes the value of the variable on which the condition depends, then there's a risk of ending up with a loop that never stops — this is called an infinite loop.
The following code is an example of an infinite loop.
int i = 1;
while(i >
0)
{
System.out.println(i++);
}
DO WHILE LOOP
The do-while
loop behaves almost like the while
loop but differs in the timing of when it checks the condition. While the while
loop checks the condition first, the do-while
loop performs the check at the end, after the code has already executed. This is a positive feature because there are cases where we need the loop’s code to run at least once.
The general structure of a do-while
loop is as follows:
do
{
//Statements
}while(Boolean_expression);
Let's look at a simple example of a do-while
loop.
App.java
package com.example;
public class App {
public static void main(String[] args) {
int y = 10;
do {
System.out.println(y);
y += 10;
} while (y <= 100);
}
}
Output
FOR LOOP
The two previous loops (while and do-while) repeat the execution of a specific code as long as the condition that defines them is true. This means that we are not dependent on a specific number of repetitions because it may not be known to us in advance. For this very reason, there is the third loop – the for
loop. This loop fills the gap left by the first two loops, meaning it executes a part of the code for a specific number of repetitions, which is known before the loop executes.
The general structure of a for
loop is defined as follows:
for(initialization;
Boolean_expression; step)
{
// Statements
}
Before we look at a simple example, let's explain the parameters that we need to define:
Initialization – We define the variable or variables that will be used by the for
loop.
Boolean_expression – The condition that, as long as it remains true, the for
loop will continue to execute.
Step – The arithmetic operation that will affect the variable defined in the initialization.
Now, let's look at a simple example with the for
loop.
App.java
package com.example;
public class App {
public static void main(String[] args) {
for (int j = 1; j <= 1024; j = j * 2) {
System.out.println(j);
}
}
}
Output
BREAK AND CONTINUE
There is a high likelihood that when searching on the Internet for code examples, you will see the break
and continue
statements included inside loops.
We have already encountered the break
statement in the switch
. In loops, it serves exactly the same function – it stops the loop at any moment, and the execution of the program continues with code that is outside the loop.
Let's look at a simple example of a while
loop that uses the break
statement.
App.java
package com.example;
public class App {
public static void main(String[] args) {
int k = 1;
while (k <= 10) {
System.out.println(k);
if (k == 6) {
break;
}
k++;
}
System.out.println("The final value of k is " + k);
}
}
Output
The logic we just implemented is very simple. We define a variable k
with an initial value of 1. As long as the value of k
is less than or equal to 10, we want to print the value of k
to the terminal. In the case where k
equals 6, we want to completely exit the loop and continue with the rest of the program, which in our case simply prints the final value of the variable k
.
The continue
statement has the property that, whenever it is triggered for a certain value, it skips the current execution of the loop and continues with the next iteration.
Let's look at a simple example of a for
loop that uses the continue
statement.
App.java
package com.example;
public class App {
public static void main(String[] args) {
for (int i = 10; i > 0; i--) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
}
}
Output
In this simple example, we define a local variable i
with an initial value of 10. As long as i
remains greater than 0, we will print the value of i
. However, if the value of i
is divisible by 2, we do not want to print the value but instead proceed to the next value of i
. The final result is that we only print the odd numbers and not the even ones.
Don't forget to make a small donation so that this blog can grow even more and have more features for delivering free lessons online.
0 Comments
What do you think about Ground of Code?