Support Online
Skip to main content

How to Use Loops in Java?

Using loops in programming instead of writing repetitive tasks increases readability and reduces code repetition.
In this guide, you will learn the while, do-while, for and foreach loops in Java with examples.

🧠 Technical Summary

Main topic: Use of loop structures in Java
Purpose: To carry out repetitive operations in a dynamic, manageable and error-free manner


🔁 Java Loop Types

1. while Loop

Repeats the block of code as long as a condition is true.

int x = 3;
while (x > 0) {
System.out.println("x değeri: " + x--);
}

This loop runs until x becomes 0, decreasing x by 1 each time.

Important: An operation (e.g. x--) must be added to make the condition false at the end of the loop. Otherwise it will continue forever.

2. do-while Loop

It checks the condition afterwards. The block of code runs at least once.


int y = 3;
do {
System.out.println("y değeri: " + y--);
} while (y < 0);

In this example, "y value: 3" is output even if the condition is false from the beginning.

Area of Use:

Situations where it is desired to receive input from the user at least once or to start the process before the condition.

3. for Loop

Ideal for situations where you know how many times it will work.


for (int z = 3; z > 0; z--) {
System.out.println("z değeri: " + z);
}

This loop runs as z takes values from 3 to 1.

Advantage:

Since the start, condition and variable increment are defined on the same line, the code is clean and error-free.

4. foreach Loop (Advanced For)

Easily navigates all elements in a collection or array.


int[] sayilar = {0, 1, 2};
for (int sayi : sayilar) {
System.out.println(sayi);
}

This loop prints each element of the array in order: 0, 1, 2.

Advantage:

There is no need to know the number of elements. It is a standard method for arrays, lists or sets.


⚠️ Infinite Loops

💥 Accidental Infinite Loop

If you don't update the variable used in the condition, the loop will not finish.


int sayac = 3;
while (sayac > 0) {
System.out.println("Sonsuza kadar dönecek...");
// HATA: sayac azaltılmadı!
}

Solution:

Add an action that will break the condition:


sayac--;

♾️ Conscious Infinite Loop

In some cases, it can be used intentionally in continuously running tasks.


while (true) {
System.out.println("Bu metin sürekli basılacak.");
// CTRL+C ile durdurabilirsiniz.
}

However, in modern applications, Timer or scheduled tasks are preferred instead.


🔍 Loop Types Comparison

Loop TypeCondition Check TimeMinimum Number of RunsUsage Area
whilePreviously0Conditional indefinite repetitions
do-whileAfter1Tasks to run at least once
forPreviously0A certain number of repetitions
foreachInternalUp to collection lengthSeries and collections

❓ Frequently Asked Questions (FAQ)

  1. What is the difference between while and for loops?

The for loop is preferred if the number of iterations is known. while loop is suitable for conditional repetition.

  1. Why is foreach popular?

Automatically navigates every element in arrays or lists. It removes the obligation to keep a meter.

  1. Are infinite loops harmful?

Yes, if it's not intentional. It may cause the program to crash or crash the system.

  1. Which command is used to stop loops?

break terminates the loop immediately. continue just skips that step and continues the loop.

  1. How is cycle performance measured?

On large data sets, you can measure processing time using System.nanoTime() or Instant.now().


🏁 Conclusion

In this guide, you learned how while, do-while, for and foreach loops work in Java and which one should be preferred in which case. Now you can write repetitive operations in a cleaner, safer and optimized way.