OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 1 : Looping Statements
Loops in Java – Syntax, Explanation & Examples
In Java, loops are used to execute a block of code repeatedly until a given condition is satisfied. They are essential when the number of iterations is known or unknown.
Types of Loops in Java
for
loopwhile
loopdo-while
loop- Enhanced
for
loop (for-each)
1. for
Loop
Syntax:
for (initialization; condition; update) {
// code to be executed
}
Example:
public class ForLoopDemo {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
}
}
Output:Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
2. while
Loop
Syntax:
while (condition) {
// code to be executed
}
Example:
public class WhileLoopDemo {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Number: " + i);
i++;
}
}
}
Output:Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
3. do-while
Loop
Syntax:
do {
// code to be executed
} while (condition);
Example:
public class DoWhileDemo {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Value: " + i);
i++;
} while (i <= 5);
}
}
Output:Value: 1
Value: 2
Value: 3
Value: 4
Value: 5
4. Enhanced for
Loop (for-each)
Syntax:
for (datatype var : array) {
// code using var
}
Example:
public class ForEachDemo {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
System.out.println("Element: " + num);
}
}
}
Output:Element: 10
Element: 20
Element: 30
Element: 40
📋 Comparison Table
Loop Type | Condition Check | Executes at Least Once | Use Case |
---|---|---|---|
for |
Before | No | When number of iterations is known |
while |
Before | No | Condition-driven loop |
do-while |
After | Yes | Run at least once |
for-each |
Internal | Yes | Array or collection traversal |
✅ Summary
- for – Best when count is known
- while – Best when condition controls iteration
- do-while – Executes at least once
- for-each – Simplified loop for arrays/collections
- Use
break
to exit loop early - Use
continue
to skip current iteration
=========================================================================
Comments
Post a Comment