Loops In Java
Introduction
When writing programs, one key principle is to avoid duplicating code whenever possible. Not only does this make your code smaller and easier to read, but it also simplifies maintenance and future changes. One powerful way to minimize redundancy and make your code more efficient is by using loops. Loops allow you to execute a block of code repeatedly until a certain condition or expression is met.
Common Loop Types in Java:
For
For-each
While
Do-While
The For Loop
The for loop is typically used when you know in advance how many times you need to iterate over a block of code and has three main components.
Initialization:
This statement is the first to be executed and is only run once. This is typically where a variable is initialised to facilitate the loop running a fixed number of times.
Condition:
This is the condition that is checked after each iteration of the loop. The loop will end when this condition evaluates to false.
Increment/Decrement:
This statement is executed after the loop body (code to be iterated over) but before the condition is checked. This is typically where a variable is incremented or decremented to assist in stopping the loop.
// Syntax for a for loop:
for (initialization; condition; increment/decrement) {
// Code to be iterated over
}
//Example
// Print the numbers one to five
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
The For Each Loop
The for-each loop is a simpler version of the for loop, used when iterating over collections (to be covered in a later topic). It's particularly useful when you need to process each element in a collection, one at a time.
// Syntax for a for-each loop:
for (datatype element : collection) {
// Code to be iterated over
}
//Example:
String[] students = {"Alice", "Bob", "Charlie", "Diana"};
// Print out each student's name
for (String student : students) {
System.out.println(student);
}
The While Loop
The while loop is used when you want to repeat a block of code an unknown number of times, as long as a specific condition remains true.
// Syntax for a while loop:
while (condition) {
// Code to be iterated over
}
// Example:
// Print the numbers one to five
int i = 1;
while(i <= 5){
System.out.println(i);
i++;
}
The Do While Loop
The do-while loop is similar to the while loop, but the key difference is that it executes the block of code at least once as the condition is evaluated after the code is executed.
// Syntax for the do-while loop:
do {
// Code to be iterated over
} while (condition);
// Example:
// Print the numbers one to five
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
Conclusion
Loops are an essential part of programming in Java, allowing you to perform repetitive tasks efficiently and keep your code clean and concise. Whichever loop you use, each type has its unique strengths and is suited to different use cases. By understanding how and when to use these loops, you'll be able to write more efficient and readable code.