JavaCore java
Need for loop in Java
Why Do We Need Loops?
- In programs, we often need to do the same task repeatedly.
- Using only
if-else
is not suitable → it checks a condition only once. - Writing the same statement again and again is cumbersome.
Example Without Loop
System.out.println("Hi");
System.out.println("Hi");
System.out.println("Hi");
System.out.println("Hi");
👉 Very repetitive and not efficient.
Example With Loop
for (int i = 1; i <= 4; i++) {
System.out.println("Hi");
}
👉 Much shorter and easier to maintain.
Loops in Java
Java provides 3 main types of loops:
- for loop → repeat code a fixed number of times.
- while loop → repeat code while a condition is true.
- do-while loop → similar to while, but executes at least once.
Key Idea:
Loops make code clean, efficient, and dynamic → we can run tasks multiple times programmatically instead of manually repeating code.