A loop allows us to execute a block of code MULTIPLE TIMES based on a condition.
Instead of writing the same lines again and again, loops make code **shorter**, **efficient**, and **less error-prone**.
Imagine we want to print a name 100 times, without a LOOP, we have to write -
System.out.println("Athira");
System.out.println("Athira");
System.out.println("Athira");
// ... and so on, 100 times Very lengthy and hard to maintain!
We can automate repetition efficiently.
(1) Define where to start (initialization),
(2) Set a condition to continue running,
(3) And decide how many times to repeat.
This way, we write less code, avoid repetition, and make our programs clean and maintainable.
Java provides three main types of loops:
| Loop Type | Description |
| --------------- | ----------------------------------------------------------- |
| FOR loop | Used when the number of iterations is KNOWN in advance. |
| WHILE loop | Used when the number of iterations is NOT KNOWN ahead. |
| DO-WHILE loop | Similar to WHILE, but EXCECUTES ATLEAST ONCE |
All loops involve these key components:
1️ Initialization → Setting up the starting point
2️. Condition → When to stop the loop
3️. Update/Increment → Progressing toward the stop condition
4️. Body → The code we want to repeat