While Loop In Java With Examples

While Loop In Java: A while loop is a control flow statement in Java that allows the repeated execution of a code block as long as a certain condition remains true. It is a pre-test loop, meaning the condition is checked before the loop body is executed. In Java, the while loop syntax consists of the keyword “while” followed by a condition enclosed in parentheses, and then the code block to be executed, enclosed in curly braces.

For example, consider the following code snippet:

While Loop Syntax

while (condition)
{ 
// codes inside the body of while loop 
}

How does a While Loop In Java work?

The condition is verified first in the While loop and returns the true value. Then, the execution flows enter the method body area and execute the statements. If the condition returns false, then the execution flow comes out from the loop and jumps to the statements outside of the while loop.

Program: Simple While Loop In Java
package java_Basics;
public class Whileloop_Example 
{
   public static void main(String[] args) 
   {
      int i = 1;
      while (i <= 10)
      {
         System.out.println("Value Of I:- " + i);
         ++i;
      }
   }
}

Output:

Value Of I:- 1
Value Of I:- 2
Value Of I:- 3
Value Of I:- 4
Value Of I:- 5
Value Of I:- 6
Value Of I:- 7
Value Of I:- 8
Value Of I:- 9
Value Of I:- 10

In this example, the loop will iterate as long as the condition i < 10 Remains true. The loop body contains a statement that prints the current I value, followed by an increment operation to update the value I and ensure the loop eventually terminates. The output of this code would be the numbers 0 through 10, each on a separate line, since the loop will execute ten times before the condition becomes false.

Note: While executing the while loop, we need to use an increment or decrement statement inside the loop body area so that the value of the variables changes regularly on each iteration. At some time, the condition returns false. In this way, we can end the execution of the while loop; otherwise, the loop will run indefinitely.

Ref: Article

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment