Looping statements in Java make it easy to repeat tasks in your code. Just like hitting the snooze button on your alarm multiple times, loops help you perform certain actions again and again without writing the same code repeatedly. Let’s explore how these loops work and see some real-life examples to understand them better!
Looping Statements
Flow Control Statements
These are the statements that control the flow of the execution of a program. Flow control statements are essential programming tools that help manage the execution flow of your Java program. They dictate the sequence in which various statements, instructions, or function calls are carried out. With these statements, you can:
- Make decisions based on specific conditions
- Repeat code blocks multiple times
- Navigate to different sections of the program
- Effectively manage complex program logic.
There are three ways to control flow, by using.
Looping Statements
Loops are one of the coolest tools in programming! They allow you to execute a block of code repeatedly as long as a specified condition is true. Loops save time, reduce redundancy, and make your code clean and efficient.
Types of Looping Statements in Java
Java provides three main types of looping statements:
- For loop
- While loop
- Do while loop
1. For Loop
- The for loop provides a more compact way to write loop structures that need to be executed a specific number of times.
- Think of the for loop as your go-to choice when you know exactly how many times you want to repeat a task.
- For comes with three properties in its syntax.
- Initialization of a variable
- The condition will be built with the help of the initialization variable.
- Increment/decrement of the initialization variable.
Syntax:
for (initialization; condition; increment/decrement) {
// Statements to execute
}
JavaExample:
Let’s print “Hello, World!” five times:
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i < = 5; i++) {
System.out.println("Hello, World! - " + i);
}
}
}
Explanation:
- The loop starts with int i = 1 (initialization).
- It checks if i <= 5 (condition). If true, it runs the code inside the loop.
- After each execution, i++ increases i by 1 (update).
Output:
Hello, World! - 1
Hello, World! - 2
Hello, World! - 3
Hello, World! - 4
Hello, World! - 5
2. While Loop
- The while loop is great when you’re unsure how many times you need to repeat the task, it keeps going until a condition is no longer true.
- The while loop executes a block of code as long as the specified condition remains true.
- The while comes with a condition and is associated with True Statement Block (TSB), while will execute the TSB until the condition remains true.
Syntax:
while (condition) {
// Statements to execute
}
JavaExample:
Imagine you want to keep printing numbers as long as they’re less than 5:
public class WhileLoopExample {
public static void main(String[] args) {
int count = 1;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
}
}
Explanation:
- The loop checks if count < 5 (condition).
- If true, it prints the value of the count and then increments the count by 1.
- At a count of 5, the loop will not execute because the condition is false, So JVM comes out of the while loop.
Output:
Count: 1
Count: 2
Count: 3
Count: 4
3. Do-While Loop
- The do-while loop is similar to the while loop, but it executes the code block at least once before checking the condition.
- The do-while loop is like a dare, it will execute the code at least once, even if the condition is false.
Syntax:
do {
// Statements to execute
} while (condition);
JavaExample:
Let’s print numbers from 1 to 3 using a do-while loop:
public class DoWhileLoopExample {
public static void main(String[] args) {
int count = 1;
do {
System.out.println("Count: " + count);
count++;
} while (count < = 3);
}
}
Explanation:
- The do block runs first and prints the value of the count.
- Then it checks the condition (count <= 3).
- If the condition is true, it repeats the loop; otherwise, it stops.
Output:
Count: 1
Count: 2
Count: 3
Loop Type | When to Use | At Least One Execution? |
for | When the number of repetitions is known. | No |
while | When the condition decides repetitions. | No |
do-while | When you need at least one execution. | Yes |
Summary
- Loops are incredibly useful in programming, and Java provides three main types: for, while, and do-while.
- Each loop has its unique use case, and understanding them will make your programming journey much smoother.
- Remember:
- Use for loops when you know how many times you want to repeat.
- Use while loops for unknown iterations based on a condition.
- Use do-while loops when you want the code to execute at least once.
Must Read
Decision-Making Statements in Java
– Learn how to control the flow of your program using if, if-else, switch, and other decision-making constructs.
Jumping Statements in Java
– Understand how to alter the flow of loops using break, continue, and return statements in Java.
Keywords in Java
– Learn about the reserved keywords in Java and their specific functions.
Java User Input
– Learn how to handle user input in Java using Scanner class and other methods.
Operators in Java
– Get to know the various operators in Java and how to use them in expressions.
FAQ’S
Can I nest one loop inside another?
Absolutely! You can use nested loops for more complex tasks like iterating over rows and columns in a matrix.
How do I avoid infinite loops?
Make sure the loop condition eventually becomes false. If not, the program will keep running the loop indefinitely.
What is the difference between while and do-while loops?
The while loop checks the condition before executing the loop body, while the do-while loop executes the body first and then checks the condition. A while loop checks the condition first, so it might not execute at all if the condition is false. A do-while loop always runs at least once before checking the condition.
Can I use multiple conditions in a loop?
Yes, you can use logical operators like && (AND) and || (OR) to combine conditions in loops.
What happens if a loop condition is never false?
The loop becomes an infinite loop, which may cause the program to crash or hang. Always ensure that the loop condition can eventually be evaluated as false.