Loops in Java
Introduction to loops in Java
Loops in programming are control structures that make it possible to execute a set of instructions several times, as long as a given condition is met. Their main purpose is to automate repeated tasks, which reduces the need to write repeated code. Instead of writing several lines of code by hand for each iteration, loops let us repeat one block of code a certain number of times or until some condition becomes false. The most commonly used loops are the for, while and do-while loops, each suited to different situations.
Comparing the performance of different kinds of loops
In Java, the performance of different loops depends on the number of iterations and on the logic itself:
- The for loop: Efficient when we know the exact number of iterations in advance. A good choice for arrays and for iterating through fixed data structures.
- The while loop: Better for situations where the number of iterations is not known in advance. It can be less efficient if the condition stays true for a long time.
- The do-while loop: Similar to the while loop, but the code is always executed at least once, which can be important in certain cases.
In practice the performance differences between these loops are minimal for most applications, except when working with very large data sets.We can also add the foreach loop here.
The foreach loop is not considered a separate kind of loop; it belongs to the group of iterative loops, like the for loop. While the classic for loop is used to iterate through an array with explicit indices and control variables, the foreach loop simplifies iterating through collections (such as arrays, lists or maps), automatically going through each element without explicit indexing. Although it works differently, it can be seen as a specialized form of the for loop adapted to collections.
The for loop algorithm – diagram
This algorithm shows how the repetition of statements is controlled with three expressions: 1 – a variable is defined and initialized; 2 – a logical expression is set as the loop condition; 3 – the change of the control variable during the loop is defined

Here is a concrete example of the 3 expressions used to control the flow: 1 – the variable "i" is defined and initialized to zero; 2 – the logical expression i<n is set as the loop condition; 3 – the control variable changes by "+1" in each cycle

The while and do-while loop algorithms – diagrams
It defines the repetition of a group of statements as long as some condition (a logical expression) is met. This loop is usually used when the number of cycles is not known in advance. It is possible that the statements are not repeated even once.

It defines the repetition of a group of statements as long as some condition (a logical expression) is met. This loop is usually used when the number of cycles is not known in advance and when, for some reason, it is important that there is at least one cycle. At least one cycle must be executed.

You can read this lesson for the C/C++ language on the following page: Loops in C/C++
To practice examples from this area, go to the page: Loops – examples (C, C++, Java).
Why do we need a loop statement?
Let's look at the following problem. We want to print a sequence of natural numbers. In this example let it be the first 10 natural numbers. The statement that prints the number 1 is:
System.out.print("1");
If we want to print the other numbers too, we could repeat the previous statement 10 times (using Copy – Paste) and change only the value of the number that is shown
System.out.print("1, ");
System.out.print("2, ");
System.out.print("3, ");
System.out.print("4, ");
System.out.print("5, ");
...
The for loop in Java
This could still be done this way for a few numbers, but what if we need to print 100 or 1000 numbers? Of course, we would not do it this way.
The idea of loops is that the statements that repeat are written only once, and a loop statement, such as the statement for, executes these statements several times, i.e. as many times as needed.
In this example the statement that repeats is
System.out.print(..
So we will write it only once and put it into the body of the for statement, which is the loop:
In general, the for statement is written as:
for (inicijalizacija; uslov_petlje; izraz_petlje) {
niz_naredbi;
}
In our example there is only one statement; it is written inside curly braces and looks like this:
for (inicijalizacija; uslov_petlje; izraz_petlje) {
System.out.print(..
}
The conditions that determine the number of repetitions are written in parentheses: initialization, loop_condition, loop_expression, separated by semicolons.
Initialization means that we introduce (define) a control variable, e.g. "i", which means that we reserve memory for it and give it an initial value (initialize it).
In this example:
int i = 1;
The loop condition is a logical expression that can be true (true) or false (false). In our example it is:
i <= 10;
The loop will repeat as long as this condition is met. If we did not change the variable "i" during the loop (and we can change it through the loop expression), the condition would always be true, i.e. the loop would never stop (an infinite loop). To stop it, we have to make the condition false at some point. We can change the control variable i with the:
loop_expression, which is usually an expression of the form
i = i + korak;
where step is an integer that says by how much the variable "i" increases or decreases (if the step is negative). In our example the value of "i" should increase by 1 in each cycle, so the loop expression will be:
i = i + 1;
This means that the new value in the memory location of i is 1 bigger than the previous one. The for loop now looks like this:
for (int i = 1; i <= 10; i = i + 1) {
System.out.print(..
}
The statement will now repeat 10 times, i.e. as long as i<=10. What remains is what to put into the parentheses of the print statement. If we wrote "1", it would print 1,1,1,1,1,1...
We need a variable that has the value 1 in the first cycle, 2 in the second, etc. That can be exactly the variable i that we use to control the number of cycles. Now we can finally write:
for (int i = 1; i <= 10; i = i + 1) {
System.out.print(i + ", ");
}
Of course, this task could also be solved with the statementSystem.out.print("1,2,3,4,5,6,7,8,9,10");
but here we only wanted to show the for statement for loops and when and why they are used.
The for loop is used when we know in advance how many cycles there will be; if we don't, we use the while or the do-while loop, which are covered later.
For the loop_expression you can use the operator "++" to increase the variable "i" by 1, instead of the expression i=i+1
for (int i = 1; i <= 10; i++) {
System.out.print(i + ", ");
}
Task: add the first 10 natural numbers with a for loop.
This task could also be solved with the statement
System.out.print("" + (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10));
but we want to show how the sum is obtained with a for loop (useful when there are many numbers). The idea is to add one natural number in each cycle to a variable that holds the sum. In the loop these natural numbers are represented by the variable "i" as in the previous example (convenient, because this variable changes from 1 to 10 with step 1, so through the cycles it actually represents the natural numbers to add).
First we introduce a variable for the sum:
int zbir=0;
Then we add the numbers to the sum one by one. Without a loop that would look like this:
zbir = zbir + 1;
zbir = zbir + 2;
zbir = zbir + 3;
zbir = zbir + 4;
...
zbir = zbir + i;
...
zbir = zbir + 10;
but instead we use a loop:
for (int i = 1; i <= 10; i = i + 1) {
zbir = zbir + i;
}
The final sum is formed only when the for loop ends. The complete example is shown below.
class Sabiranje {
public static void main(String[] args) {
int zbir = 0;
for (int i = 1; i <= 10; i = i + 1) {
zbir = zbir + i;
}
System.out.println("sum=" + zbir);
}
}
And after running:
Program output:
sum=55
EXAMPLE: Average grade
Task text: Read the number of subjects n, then read the grades in n subjects, add them up and compute the average grade. Show the result on the screen.
Hints: Read n through an input dialog. Since there are several grades to read, use a for loop. Add up the grades in the for loop as in the previous example. Only when the final sum of the grades is computed, i.e. after the for loop, can the average be computed.
The while loop – condition at the start
In general the loop looks like this:
while (uslov_petlje) {
NAREDBE
}

Unlike for, which is used when we know the number of cycles in advance, while is used when we don't know in advance when the loop will stop.
In the picture you can see the loop (a closed circle) that contains the statements to repeat. These statements will repeat as long as the given CONDITION is met. It is a logical expression or a variable of type boolean that can be true or false. The first time the condition is false, the loop stops and the program continues outside the while loop.
Let's look at the following example:
EXAMPLE: Quiz
Task text: Read the points won for the current question in a quiz. Find after how many questions the candidate reaches 30 points, if 1–10 points can be won for each question. Stop counting after at most 10 questions.
int brojBodova;
int ukupnoBodova = 0;
Scanner ucitavac = new Scanner(System.in);
We will read the points in a loop and add them to the total number of points:
while (ukupnoBodova < 30) {
System.out.println("Enter the number of points");
brojBodova = ucitavac.nextInt();
ukupnoBodova = ukupnoBodova + brojBodova;
}
When the total reaches 30 points, the loop stops. To count the cycles we introduce an integer variable whose initial value is zero, and after each cycle this number increases by 1;
int brojBodova;
int ukupnoBodova = 0;
Scanner ucitavac = new Scanner(System.in);
int brojCiklusa = 0;
while (ukupnoBodova < 30) {
System.out.println("Enter the number of points");
brojBodova = ucitavac.nextInt();
ukupnoBodova = ukupnoBodova + brojBodova;
brojCiklusa++; //The number of cycles increases by 1
}
Finally, we make sure that there are at most 10 cycles. This can be done by extending the existing condition
ukupnoBodova < 30
with an extra condition:
ukupnoBodova < 30 && brojCiklusa < 10
The whole code is now given below:
import java.util.Scanner;
class Kviz {
public static void main(String[] args) {
int brojBodova;
int ukupnoBodova = 0;
Scanner ucitavac = new Scanner(System.in);
int brojCiklusa = 0;
while (ukupnoBodova < 30 && brojCiklusa < 10) {
System.out.println("Enter the number of points");
brojBodova = ucitavac.nextInt();
ukupnoBodova = ukupnoBodova + brojBodova;
brojCiklusa++; //The number of cycles increases by 1
}
System.out.println("The total number of points is " + ukupnoBodova);
}
}
The do-while loop – condition at the end
This kind of loop is similar to the while loop, except that the condition is at the end of the loop, not at the start:
do {
NAREDBE
} while (uslov_petlje);

In practice this means that in a do-while loop the statements must be executed at least once, while in a while loop they may not be executed at all. The statements to repeat are inside the loop and repeat as long as the condition has the value true.
Let's look at the following example:
EXAMPLE: Temperature
Task text: Read the temperature values measured every hour at a measuring station. Stop reading when the value -100 is read. Find the number of temperatures read.In this example we don't know in advance how many cycles will be needed (the number of temperatures read) – that is exactly the value we have to find. The loop will run as long as the value read is different from -100 (we assume that such a temperature is not possible, so this value is used to stop the loop).
In the first part of the task we define the variable temperatura (temperature):
Scanner ucitavac = new Scanner(System.in);
double temperatura;
Since we use a do-while loop, at least one temperature will be read inside the loop. Further reading depends on whether the value read is different from -100. The loop then looks like this:
do {
temperatura = ucitavac.nextDouble();
} while (temperatura != -100);
If the first value read is -100, only that first temperature is read and the loop does not continue. The complete example now looks like this:
import java.util.Scanner;
class Temperatura {
public static void main(String[] args) {
Scanner ucitavac = new Scanner(System.in);
double temperatura;
int brojCiklusa = 0; // number of temperatures read
do {
temperatura = ucitavac.nextDouble();
brojCiklusa++;
} while (temperatura != -100);
// the last value read (-100) only marks the end, so it is not counted
System.out.println("Number of temperatures read: " + (brojCiklusa - 1));
}
}
The number of temperatures read is equal to the number of cycles. To find the number of cycles we use the integer variable brojCiklusa (number of cycles), as in the previous example.
Tasks for which a for loop is more convenient, because we know the number of cycles in advance, can still be solved with a while or do-while loop. The example of adding the first 10 natural numbers with a while loop would look like this:
int zbir = 0;
int i = 1; // initialization – before the loop
while (i <= 10) // loop condition
{
zbir = zbir + i;
i = i + 1; // loop expression – inside the loop
}
System.out.println("sum=" + zbir);
Since only the loop_condition is inside the parentheses of the while loop, the initialization, which was also inside the parentheses in the for loop, is written before the loop here, while the loop_expression, which sets the step of the control variable, is written as one of the statements inside the while loop.
Nested loops
You can read about nested loops in C/C++ on the following page: Nested loops in C/C++
A loop can also be inside another loop, as one of the statements of the outer loop:
for (inicijalizacija1; uslov_petlje1; izraz_petlje1) {
for (inicijalizacija2; uslov_petlje2; izraz_petlje2) {
niz_naredbi
}
}
Nested loops – example 1
Nested loops make it possible to run loops inside other loops. For example, a for loop can contain another for loop, where the inner loop runs for each pass of the outer loop. This is useful for problems that need iterations through multidimensional structures, such as matrices.
Example:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.println(i + ", " + j);
}
}
This can be explained with the following example:
EXAMPLE: Matrix
Task text: Print a matrix of 10 rows and 10 columns that looks like the picture:
Program output:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
Solution:
To print one row of numbers we use a for loop
for (int j = 0; j < 10; j++) {
System.out.print((j + 1) + " ");
}
Here the value (j+1) is used to print the first row, because the initial value of j is 0, not 1.
Since 9 more such rows have to be printed, the for statement has to be repeated 9 more times. We will add another for loop (the outer one), so that the previous for loop becomes a statement nested inside the outer for loop.
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
System.out.print((j + 1) + " ");
}
System.out.println(); //New line – after each row
}
The control variable i now represents the current row, and the control variable j, which belongs to the inner loop, represents the index of the current column. This code needs a small change, because
System.out.print((j+1)+" ");
always prints the numbers 1 – 10, while for e.g. i = 3 (the 4th row) it should print values (i*10) bigger, in this case 30 bigger (31-40). This means the statement should be changed to:
System.out.print(10 * i +(j+1)+" ");
for-each petlja
for each loops were introduced in Java 5 and are used with arrays of data when we need to go through the elements of the array iteratively. For example, if we defined the following array:
String[] planete = {"Merkur", "Venera", "Zemlja", "Mars", "Jupiter", "Saturn", "Uran", "Neptun"};
To print the previously defined array of Strings, which is the set of planets of the Solar System, it is convenient to use the for-each loop. The statement is also written as for, but without the control expressions with the variable "i". Instead, the following syntax is used:
for (String planeta : planete) {
System.out.println(planeta);
}
Here planeta (planet) is a variable of the same type as the elements of the array "planete". In each next cycle the value of the variable planeta will be the element at the next position of the array. So after the previous statement runs, the standard output will show:
Merkur
Venera
Zemlja
...
The same example could also be done with an ordinary for loop:
for (int i = 0; i < planete.length; i++) {
System.out.println(planete[i]);
}
This example is simpler with the for-each loop, but there are some examples that cannot be done that way, and an ordinary for loop must be used. For example, if we want to print an array of integers backwards:
for (int i = 10; i > 0; i--) {
System.out.println(i);
}
That would print the following:
10
9
8
...
for-each loops with collections and arrays of objects in Java
The for-each loop is convenient for going through a collection or an array of Java objects. Suppose the following collection of objects (ArrayList) is defined in Java:
ArrayList<Zaposleni> sviZaposleni = new ArrayList<>();
The list is a collection of objects of the class Zaposleni (employee). If we create 3 such objects and put them into the list, we would use a for-each loop to print the data, as in the following picture:
import java.util.ArrayList;
public class Preduzece {
public static void main(String[] args) {
ArrayList<Zaposleni> sviZaposleni = new ArrayList<>();
// creating the employee objects
Zaposleni zaposleni1 = new Zaposleni("Mihajlo Petrovic", 800000, 10);
Zaposleni zaposleni2 = new Zaposleni("Luka Pekez", 1200000, 20);
Zaposleni zaposleni3 = new Zaposleni("Sara Jaksic", 90000, 15);
// adding objects to the list
sviZaposleni.add(zaposleni1);
sviZaposleni.add(zaposleni2);
sviZaposleni.add(zaposleni3);
// printing the employee data
for (Zaposleni z : sviZaposleni) {
System.out.println("Employee " +
z.imeIPrezime + " has a salary of " +
z.plata + " and " + z.radniStaz +
" years of service");
}
}
}
The class Zaposleni would be:
public class Zaposleni {
String imeIPrezime;
double plata;
int radniStaz;
public Zaposleni(String imeIPrezime, double plata, int radniStaz) {
this.imeIPrezime = imeIPrezime;
this.plata = plata;
this.radniStaz = radniStaz;
}
}
In newer versions of Java the foreach loop can be written as follows:
// printing the employee data (Java 8 and newer: the forEach method and a lambda expression)
sviZaposleni.forEach(z -> {
System.out.println("Employee " +
z.imeIPrezime + " has a salary of " +
z.plata + " and " + z.radniStaz +
" years of service");
});
Optimizing loops
Optimizing loops includes reducing the number of iterations or using more efficient algorithms to improve performance. Key tips:
- Avoid unnecessary computation inside the loop (e.g. compute constant values outside the loop).
- Use break when you can stop the loop earlier.
- Always check the conditions to avoid infinite loops.
An example of an optimized loop:
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
break; // Stops the loop when the target is found
}
}
Additional resources
Related links:
- Control structures in Java: Explore the other control structures in Java, such as if-else statements and switch cases, which are often used together with loops. Selection statements in Java
- Recursion in Java: Learn more about recursion, a technique that can sometimes replace loops for certain tasks, with detailed examples and explanations. Recursive algorithms
- Arrays in Java: Understanding arrays is essential when you work with loops. Dive into how arrays work and how to iterate through them with loops. Arrays in Java
External resources:
- Java documentation: loops: The official Oracle documentation gives comprehensive information about loops in Java, including syntax and examples. Oracle – documentation on loops
- Java tutorials on W3Schools: A beginner-friendly guide to loops in Java, with interactive examples. W3Schools – Java for loop
- GeeksforGeeks: Loops in Java: A detailed article covering all kinds of loops in Java with practical examples. GeeksforGeeks – Loops in Java
You can find loop examples on the page: Loops – basic examples
Additional examples: Test preparation: loops
Related articles
Loops in C++ – examples
Arrays – examples
The Fibonacci sequence
The Internet of Things
Selection statements – examples
Check your knowledge
Open the quiz
Mini quiz: loops in Java
1. Which loop do you choose when you know the number of repetitions in advance?
2. How many times is the body of the loop for (int i = 1; i <= 10; i++) executed?
3. Which loop is executed at least once, even when the condition is false right away?
4. What does for (String p : planete) print?
Check your knowledge
Open the quiz
Quiz: Loops in Java
1. How many times is for (int i = 1; i <= 10; i++) executed?
2. When do we use while instead of for?
3. What does for (String p : planete) System.out.println(p); print?
4. How many times is the body of the inner loop executed for a 10 × 10 table?
LOOPS IN THE PROGRAMMING LANGUAGE JAVA
Loops are a key element in programming that allow certain blocks of code to be executed repeatedly, as long as a certain condition is met. In Java, loops are a basic control structure that allows programmers to automate repetitive tasks, iterate through data, or manage complex algorithms. By using loops, programs become more efficient and easier to maintain. In this article, we'll explore the different types of loops in Java, how they work, and when to use them for best results.Instead of manually writing multiple lines of code for each iteration, loops allow us to repeat a block of code a specified number of times or until a condition becomes false. The most commonly used loops are for, while, and do-while loops, each adapted to different situations.Performance comparison between different loop types
In Java, the performance of different loops depends on the number of iterations and the logic itself:- for loop: Effective when we know the exact number of iterations in advance. It's a good choice for arrays and iterating through fixed data structures.
- while loop: Better for situations where the number of iterations is not known in advance. It can be less efficient if the condition remains true for a long time.
- do-while loop: Similar to the while loop, but the code will always be executed at least once, which can be important in certain cases.
In practice, the performance differences between these loops are minimal for most applications, except when dealing with very large data sets.Here we can also add a foreachloop.
The foreach loop is not considered a separate type of loop, but belongs to the group of iterative loops, similar to the for loop. While the classic for loop is used to iterate through an array with explicitly specified indices and control variables, the foreach loop simplifies iterating through collections (such as arrays, lists, or maps), automatically looping through each element without the need for explicit indexing. Although functionally different, it can be considered a specialized form of the for loop adapted to collections.
Algorithm for loop-diagram
Algorithm while, as well as do-while loops, diagrams
You can read this lesson in C / C ++ on the following page: Loops in C/C++
Where does the need for the loop command come from
Let's look at the next problem. We want to print a number of natural numbers. Now, in this case, there are a number of the first 10 natural numbers. The order to print number 1 is:System.out.print ("2,");
System.out.print ("3,");
System.out.print ("4,");
System.out.print ("5,");
...
The idea of using a cycle is to write repeating commands only once, and using the command to create a cycle, for example, command for, these commands repeatedly executed, i.e. as many times as necessary.
In this example, a repeating command is
So, we will write it only once and insert within the command for which represents the cycle:
In general, the command for is written:
{
array_of_commands;
}
{
System.out.print (..
}
Initialization means that we introduce (define) a control variable, for example, which means that we reserve for its memory and give it the initial value (initializing). In this example:
expression_of_the_loop and this is usually expression like:
{
System.out.print (..
}
It is necessary to put a variable that will have a value of 1 in the first cycle, in the second 2, etc. It can be exactly variable and that serves to control the number of cycles. Now we can finally write:
{
System.out.print( i+”, ”);
}
The cycle for is normally used when we know in advance how many cycles will be, and if we do not know, then either the while or do-while cycle will be used, which will be discussed later.
For expression_frames, operator "++" can be used to increase the value of a variable and for a value of 1 instead of "i = i + 1"
{
System.out.print( i+”, ”);
}
Example: Sum of natural numbers:
Text of the task: Summarize the first 10 natural numbers using the cycle.And this task could be solved by the order
System.out.print ("" + (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10));
but we want to show how to use the cycle for a given sum (it is convenient when there are many numbers). The idea is to add in each cycle a natural number in a variable that represents a sum. These natural numbers would be marked with a variable in the cycle as in the previous case (it is convenient because this variable changes from 1 to 10 during the cycle with step 1, so that it through cycles actually represents those natural numbers to be added.
First, you need to introduce a variable that will represent a sum:
int sum = 0;
Then one should be added to the collection. Written without a cycle, it would look like:
sum = sum + 2;
sum = sum + 3;
sum = sum + 4;
...
sum = sum + i;
...
sum = sum + 10;
{
sum= sum+ i;
}
{
for(int i = 1; i<=10; i= i+1)
{
System.out.println("sum = "+ sum);




