Last Updated: 28 May, 2022
In Java or any other programming languages, loops play an important role in executing a set of instructions multiple times based on the given condition. Inside a loop block, the set of instructions is fixed and it executes repeatedly while some condition evaluates to true.
For Example, Suppose We have to print the same message 100 times, then rather than typing the same code 100 times, we can use a loop here.
Java provides three basic types of loops:
In this tutorial we are going to discuss while loop with definition, diagram and example.
Java while loop functionality is same as for loop only syntax is different it also used to run a set of instructions until a certain condition is met.
Java while loop Syntax:
while Loop execution flow:
Flowchart of Java while Loop
Example 1 : Java while Loop Program
Output
javabytechie.com
javabytechie.com
javabytechie.com
javabytechie.com
javabytechie.com
Java also allows to write one while loop inside another while loop, it is knowns as Nested while loop or Inner while loop in Java.
Syntax of Nested while loop in Java
Now, let's understand Nested while loop through the given example.
Example 2 : Java Nested while Loop
Output
Outer while loop
Inner while loop
Inner while loop
Inner while loop
Inner while loop
Outer while loop
Inner while loop
Inner while loop
Inner while loop
Inner while loop
Outer while loop
Inner while loop
Inner while loop
Inner while loop
Inner while loop
A loop that does not terminate that loop is known as an Infinite loop in Java.
Example 3 : Infinite while Loop in Java
Output
It's an Infinite Loop
It's an Infinite Loop
It's an Infinite Loop
It's an Infinite Loop
It's an Infinite Loop
It's an Infinite Loop
It's an Infinite Loop
It's an Infinite Loop
...
...
...
We can use continue and break statements inside while loop according to our requirement.
In Java, the continue statement is mainly used inside the loops such as for loop, while loop, do-while loop, etc. The purpose of the continue statement is to continue the current running flow of the Java program and skip the rest of the code at the specified condition.
A break statement is used to terminate the current processing of the loop, after the termination control returns from the loop immediately to the next statement after the loop.
Let's understand the below Java program where we are iterating a loop from 1 to 30 but printing the even value from 11-20.
Example 4 : Continue and Break Statements inside while Loop
Output
Even Number: 12
Even Number: 14
Even Number: 16
Even Number: 18
Even Number: 20
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com