When you start programming in Java, one of the most important concepts to understand is loops. Loops help you execute a block of code multiple times without writing it repeatedly. This makes your program efficient and easier to manage.
In this article, we’ll explore what loops are, their types, and how to use them effectively in Java with examples.
๐น What is a Loop in Java?
A loop in Java is a control structure that allows you to repeat a block of code as long as a specific condition is true. It helps reduce code repetition and makes programs more efficient.
For example, if you want to print numbers from 1 to 10, instead of writing 10 print statements, you can use a loop.
๐ธ Types of Loops in Java
There are three main types of loops in Java:
1. for Loop
The for loop is used when you know in advance how many times you want to execute a statement or block of statements.
Syntax:
for(initialization; condition; update) {
// code to be executed
}
Example:
for(int i = 1; i <= 5; i++) {
System.out.println("Number: " + i);
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
2. while Loop
The while loop is used when you don’t know in advance how many times you need to execute the block of code. It runs as long as the condition is true.
Syntax:
while(condition) {
// code to be executed
}
Example:
int i = 1;
while(i <= 5) {
System.out.println("Count: " + i);
i++;
}
3. do-while Loop
The do-while loop is similar to the while loop, but it executes the code at least once even if the condition is false. This is because the condition is checked after the loop body.
Syntax:
do {
// code to be executed
} while(condition);
Example:
int i = 1;
do {
System.out.println("Value: " + i);
i++;
} while(i <= 5);
๐ Enhanced for Loop (for-each Loop)
Java also provides an enhanced for loop (also known as the for-each loop) used mainly for iterating through arrays or collections.
Example:
int[] numbers = {10, 20, 30, 40};
for(int num : numbers) {
System.out.println(num);
}
⚙️ Infinite Loops
A loop becomes infinite when the condition never becomes false. This can cause your program to run endlessly.
Example:
while(true) {
System.out.println("This will run forever!");
}
Use infinite loops carefully, usually with a break statement to stop them when needed.
๐ง Conclusion
Loops are the building blocks of any programming language, allowing developers to handle repetitive tasks efficiently.
Understanding and mastering for, while, and do-while loops will help you write cleaner, more efficient Java programs.
Comments
Post a Comment