Table of Contents
A developer can control the flow of a program by executing a block of code repeatedly based on a condition by using looping statements which play a critical role In Java programming. Loops play a vital role while handling repetitive tasks and saves time and effort by automating iterations. Let us discuss more in detail about the definition of looping statements, their types, variations, and associated jump statements, with Java syntax and examples.
What is Loops in Java?
You can execute a set of instructions repeatedly based on a condition by using the looping statements. The repetition is continued until the specified condition is evaluated to false. Loops can be divided into the following two categories:
- Entry-controlled loops: You can check the condition before entering the loop body.
- Exit-controlled loops: You can execute the loop body at least once before checking the condition.
Types of Looping Statements
![Python Projects for kids](https://i0.wp.com/learnwithmira.in/wp-content/uploads/2024/12/images.jpeg?resize=294%2C171&ssl=1)
![Python Projects for kids](https://i0.wp.com/learnwithmira.in/wp-content/uploads/2024/12/images.jpeg?resize=294%2C171&ssl=1)
1.Entry-Controlled Loop
For Loop
This loop is used when you know the number of iterations beforehand. It includes three parts: initialization, condition, and increment/decrement.
- The keyword for, followed by parentheses, is the beginning of the for loop in Java. This keyword is enclosed of three parts: condition, initialization, and update which are separated by semicolons.
- Initialization: The starting value of the loop control variable is set by this. The starting loop is generally an integer (e.g., int i = 0).
- Condition: The execution of the loop is determined by this boolean expression. As long as the evaluation of the condition is true, the loop continues itself.
- Update: The loop control variable is modified after each iteration. This often uses increment (i++) or decrement (i–).
- The code which is to be executed after every iteration is enclosed in curly braces {}, and is called the body of the loop.
- These steps are performed by the loop during its iteration:
• The variable is initialized.
• The condition is checked.
• The body is executed if the condition is true.
• The loop variable is updated and then repeated.
Syntax:
for (initialization; condition; increment/decrement)
{
// Code to execute
}
Example:
public class ForLoopExample
{
public static void main(String[] args)
{
for (int i = 1; i <= 5; i++)
{
System.out.println("Iteration: " + i);
}
}
}
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
While Loop
This loop is used when you do not fix the number of iterations and it depends on a condition.
- In Java, a block of code is repeatedly executed by using while loop as long as the evaluation of a given condition is true.
- The condition is considered as a boolean expression which is evaluated before each iteration. The execution of the loop body is done only if the condition is true, otherwise, the loop is terminated.
- If the initial condition is false, the loop body skips entirely and allows the while loop to check the pre-condition.
- The logic must be included in the code inside the loop in order to eventually make the condition false; otherwise, an infinite loop will be executed.
- When the number of iterations is not fixed and is depended on the dynamic conditions, you can use the while loops.
- You can use a break statement for exiting the loop prematurely, and a continue statement for skipping the current iteration and moving to the next.
- While loops are commonly used in cases where input is read until you enter a specific value. It processes elements of a collection with unknown size or waits for an external event or condition.
Syntax:
while (condition)
{
// Code to execute
}
Example:
public class WhileLoopExample
{
public static void main(String[] args)
{
int count = 1;
while (count <= 5)
{
System.out.println("Count: " + count);
count++;
}
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
2. Exit-Controlled Loop
Do while Loop
- This loop makes sure that the loop body is executed at least once, as you can check the condition only after the loop is executed.
- A do-while loop is a post-condition loop in Java that helps in ensuring the code block to be executed at least once before checking the condition.
- The statements which are to be executed first are contained in the do block.
- You can evaluate the condition once the code block is executed. The loop is repeated if the condition is true; and is terminated if it is false.
- You can check the condition after the code block is executed, which makes it different from the while loop.
- Unlike the construction of the other loops, the while statement requires a semicolon (;) at the end.
- The scenarios where the code must be executed at least once (like prompting for user input), the do-while loop is considered as an ideal.
- The loop becomes infinite, if you define the condition incorrectly or miss the logic for making the condition false.
- You can exit the loop prematurely by using a break statement, and skip the current iteration and move to the next condition check by using a continue statement.
- Menu-driven programs, retrying failed operations, or validating user input are some of the cases which are commonly used.
Syntax:
do
{
// Code to execute
}
while (condition);
Example:
public class DoWhileExample
{
public static void main(String[] args)
{
int num = 1;
do
{
System.out.println("Number: " + num);
num++;
}
while (num <= 5);
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
In conclusion, entry-controlled loops and exit-controlled loops are used for distinct purposes in Java programming, which depends on when you evaluate the loop condition.
The condition is checked before the execution of the loop body by using the entry-controlled loops (like for and while). They make it suitable for scenarios where the condition is met before any iteration.
On the other hand, the condition is evaluated after the execution of the loop body by using the exit-controlled loops (like do-while). It ensures at least one execution regardless of the condition.
The programmers may choose the most appropriate loop structure according to their specific requirements. Also, they can enhance the code efficiency and logic clarity by understanding these loop types.
Variations in Looping Statements
Nested Loops:
Nested Loops can be understood as the loops within loops which helps in handling multidimensional data or complex iterations.
- The occurrence of the Nested loops takes place when one loop is placed inside another loop body.
- In Java, you can nest any type of loop (for, while, or do-while) within another loop.
- You can run the inner loop completely once the outer loop iterates itself.
- The number of overall iterations is controlled by the outer loop, while the repetitive actions are performed by the inner loop every time the outer loop iterates.
- Commonly used case of Nested loops includes multi-dimensional arrays or tables. For example, you can iterate a 2D matrix.
- Only the loops containing Break and continue statements in nested loops are affected unless you use the labelled loops.
- If the number of iterations is increased, the nested loops might deal with performance issues. This is because the total number of iterations is actually the product of the inner and outer loop limits.
- You can use the Nested Loops in algorithms to sort, search, and process multi-level data structures.
Example:
public class NestedLoopExample
{
public static void main(String[] args)
{
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 2; j++)
{
System.out.println("Outer loop: " + i + ", Inner loop: " +j);
}
}
}
}
Output:
Outer loop: 1, Inner loop: 1
Outer loop: 1, Inner loop: 2
Outer loop: 2, Inner loop: 1
Outer loop: 2, Inner loop: 2
Outer loop: 3, Inner loop: 1
Outer loop: 3, Inner loop: 2
Infinite Loops:
This loop occurs when the condition of the loop is always true. You need to use them with caution.
- A loop that runs indefinitely either due to the condition which has never terminated or the condition having no exit, is considered to be an infinite loop.
- In Java, if you configure any type of loop (
for
,while
, ordo-while
) improperly, it can become an infinite loop. - An infinite loop can be caused when:
- The termination conditions is incorrect or missed.
- The loop variable is not updated.
- The condition contains logical errors.
- The program might hang or crash if an infinite loop consumes too many resources.
- During execution, an infinite loop can be ended manually by using
Ctrl + C
(in most command-line interfaces) or by terminating the program in your IDE. - You can exit the infinite loops safely by using the Break statements.
- Sometimes, infinite loops can also be used intentionally. For example, you may use them in systems which are event-driven or servers that continuously wait for user input or process requests. The logic is often included in these loops for breaking out under certain conditions.
Example:
while (true)
{
System.out.println("This is an infinite loop");
break; // Exit the loop intentionally
}
Jump Statements
The jump statements in Java helps in controlling the flow within the loops.
1. break
Statement
The break
statement helps in terminating the loop immediately.
- You can use the
break
statement in Java for exiting a loop or switching statement immediately, despite of the current iteration or condition. - Once a
break
statement is encountered, you may transfer the control to the first statement after the loop or switch. - Break with a nested loop: You can exit only that specific inner loop which contains a
break
statement. - Labelled break statement: You can exit from a specific outer loop if a
break
statement includes a label. - Commonly used cases of
break
statement:
- For early termination of loop based on a specific condition.
- For exiting from nested loops using labelled break statements.
- For avoiding unnecessary iterations in a loop.
- You might get an unclear or hard-to-read code if the
break
statement is used improperly. It should be used carefully to maintain readability.
Example:
public class BreakExample
{
public static void main(String[] args)
{
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
break; // Exit the loop when i equals 3
}
System.out.println("Iteration: " + i);
}
}
}
Output:
Iteration: 1
Iteration: 2
2. continue
Statement
The continue
statement helps in skipping the current iteration and moving to the next one.
- You can skip the current iteration of a loop and move directly to the next iteration by using the
continue
statement in Java. - You can stop the execution of the remaining code in the loop body for that iteration and jump to the next iteration when encountered with the
continue
statement. - Continue with nested loops: Only the loop that contains the
continue
statement is affected. - Labelled continue statement: The iterations of an outer loop can be skipped by using the labelled
continue
statement. - Commonly used cases of
continue
statement:
- For skipping unwanted iterations which are based on specific conditions.
- For proper optimization of loops, unnecessary execution of code can be avoided for certain iterations.
- For improving readability in scenarios where specific conditions are required to skip some part of a loop.
- The code can become hard to follow if the
continue
statement is overused. Hence to maintain clarity, you need to use it judiciously.
Example:
public class ContinueExample
{
public static void main(String[] args)
{
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
continue; // Skip the iteration when i equals 3
}
System.out.println("Iteration: " + i);
}
}
}
Output:
Iteration: 1
Iteration: 2
Iteration: 4
Iteration: 5
In order to handle the repetitive tasks efficiently, you need to understand the looping statements in Java programming. Entry-controlled loops such as while
and for
makes sure that the conditions are met before execution, while the exit-controlled loops such as do-while
loop guarantees at least one execution. Variations such as infinite loops and nested loops, together with the jump statements (break
and continue
), allows additional control and flexibility. Hence, you can write concise, efficient, and powerful Java programs by mastering these concepts.
Interconversion Between for, while, and do-while Loops in Java
Loops are the crucial part of programming as they allow you to execute of a block of code repeatedly. There are three primary types of loops in Java: for
, while
, and do-while
. Although they are serving similar purposes, their syntax and typical use cases are different. In order to write a flexible and efficient code, you need to understand the interconversion between these loops, along with their variations like finite and infinite loops.
Interconversion between Loops
1. From for
to while
:
You can convert a for
loop into a while
loop by rearranging its components.
- If you want to convert a
for
loop into awhile
loop, you need to separate the initialization, condition, and update sections of thefor
loop into their respective positions in thewhile
loop. - You need to consider the following key-points during the conversion:
- The initialization must be placed before the
while
loop. - Ensure the condition is placed in the
while
loop header. - The update statement must be included at the end of the loop body for avoiding infinite loops.
- You must use extra care while handling
break
orcontinue
statements for maintaining the same flow of execution.
For example:
// For loop
for (int i = 0; i < 5; i++)
{
System.out.println(i);
}
// Equivalent While loop
int i = 0;
while (i < 5)
{
System.out.println(i);
i++;
}
Output:
0
1
2
3
4
2. From while
to do-while
:
You can convert a while
loop into a do-while
loop. The only difference is that the execution of a do-while
loop is done at least once, even if the condition is initially false.
- Although the
while
loop anddo-while
loop are similar, the key difference lies in when you check the condition. - The condition in a
while
loop is checked before the execution of the loop body. If the initial condition is false, you cannot execute the loop body even once. - The condition in a
do-while
loop is checked after the execution of the loop body. This ensures that the loop body is executed at least once, regardless of the condition. - For converting a
while
loop into ado-while
loop:
- The same condition and loop body should be retained.
- The condition check should be moved to the end of the loop.
- The loop body in a converted
do-while
loop runs at least once, even if the initial condition is false. - You need to guarantee that the loop body is executed at least once, in order to convert a
while
loop into ado-while
loop, especially when the user input is taken or the variables are initialized.
// While loop
int i = 0;
while (i < 5)
{
System.out.println(i);
i++;
}
// Equivalent Do-While loop
int j = 0;
do
{
System.out.println(j);
j++;
}
while (j < 5);
Output:
0
1
2
3
4
3. From do-while
to for
:
You can restructure a do-while
loop as a for
loop, especially if they have a simple initialization and update.
- Although similar purposes are served by both: the
do-while
loop andfor
loop, they differ in how you check the condition and where you place the initialization, condition, and update. - The execution of the loop body in a
do-while
loop occurs at least once before you check the condition. This ensures that the code inside the loop runs initially, regardless of the condition. - The initialization, condition, and update in a
for
loop are all part of the loop structure. The loop body might not execute at all if the initial condition is false, hence you need to check the condition before executing the loop body. - For converting a
do-while
loop into afor
loop:
- The initialization should be placed in the initialization section of the
for
loop. - The condition should be moved to the condition section of the
for
loop. - The update should be added in the update section of the
for
loop. - Make sure that the logic of the loop body remains the same.
- The converted
for
loop do not ensure at least one execution as thedo-while
loop. If the condition is initially false, the loop body will not run, unlike thedo-while
loop where at least one execution always occurs. - This conversion is useful when a more compact syntax is preferred or when the loop structure suits better for such situations where you predefine the number of iterations.
// Do-While loop
int i = 0;
do
{
System.out.println(i);
i++;
}
while (i < 5);
// Equivalent For loop
for (int i = 0; i < 5; i++)
{
System.out.println(i);
}
Output:
0
1
2
3
4
Finite and Infinite Loops
Finite Loops:
Finite loops can be executed for a specific number of iterations.
- A loop which is executed for a predetermined number of times or until the specified condition becomes false is a finite loop. The execution of this loop is limited which means that if a condition fails or after the specified number of iterations, its execution will terminate.
- Usually, for loops are used for finite loops because with the utilization of initialization, condition and update mechanism, the programmer can explicitly define the number of iterations.
- While loops can also be treated as finite loops. Only the programmer needs to structure it with a clear condition that eventually makes the output false and the loop is terminated.
For example:
// Finite loop
for (int i = 0; i < 10; i++)
{
System.out.println("Iteration: " + i);
}
Output:
Iteration:0
Iteration:1
Iteration:2
Iteration:3
Iteration:4
Iteration:5
Iteration:6
Iteration:7
Iteration:8
Iteration:9
Infinite Loops:
Infinite loops can be run indefinitely until broken explicitly. You may typically use them in event-driven programs or while waiting for the user input. Also, you need to be cautious in order to avoid unintentional infinite loops.
- Infinite loops are endless running loops as their exit condition is either never met or they do not have exit condition at all.
- Infinite loops can be created by using all the three loops (
for
,while
, anddo-while
) if the condition is always set to true or the condition is omitted altogether. for
loops can create infinite loops if you set the condition totrue
, or do not specify the condition (i.e.,for(;;)
).while
loops can create infinite loops if the condition is always true. Syntax,while (true)
.Do-while
loops can become infinite loops if the condition at the end is always true. Syntax,do { } while (true)
.- The key feature of infinite loops cannot be terminated on their own. They continue to execute unless a
break
statement interrupts explicitly, an exception occurs, or due to an external intervention (like when the program is manually stopped). - Generally, we use infinite loops intentionally in applications like servers or event-driven systems, where the program needs to wait continually for input or processing of events.
- To exit an infinite loop safely, you should use
break
statements or conditions inside the loop to avoid indefinite running of the program. - It could be dangerous if you do not handle the infinite loops carefully, as they may lead to excessive consumption of resource or crashing of application. Hence, to manage them effectively, it is essential to exit conditions properly, manage resources, and control the user.
// Infinite loop
while (true)
{
System.out.println("This loop will run forever unless broken.");
break; // Prevent infinite execution
}
Conclusion
The functional equivalence of for
, while
, and do-while
loops in executing repetitive tasks has been highlighted by the interconversion between them, besides their varied syntax and usage. A for
loop best suits in situations where the number of iterations are known, whereas a while
loop prefers conditional repetition with pre-checking. The do-while
loop guarantees that the loop body is executed at least once because of its post-checking nature. By understanding these differences, a developer can select the loop or convert them flexibly and efficiently based on their programming needs.
Find the perfect course!
All of our courses are designed to help you learn the fundamentals and ace your board exams. Grab a Free Demo Class Today!