Table of contents
1.
Syntax of Java While Loop
2.
Execution of while loop program in Java
3.
Parts of Java While Loop
3.1.
Test Expression
3.2.
Update Expression
4.
Examples of Java While Loop
4.1.
Example 1: Counting Down
4.2.
Java
4.3.
Example 2: Searching for a Value
4.4.
Java
4.5.
Example 3: Repeating User Input
5.
Frequently Asked Questions
5.1.
What happens if the test expression in a while loop never becomes false?
5.2.
Can while loops be nested inside other loops?
5.3.
Is it possible to exit a while loop without the condition becoming false?
5.4.
What is the difference between do-while and while loop in Java?
6.
Conclusion 
Last Updated: Nov 26, 2024
Easy

While Loop in Java

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

While loops are a basic but essential concept in Java programming. They allow you to repeat a block of code multiple times based on a certain condition. While loops keep executing as long as the condition remains true & stop as soon as it becomes false. 

While Loop in Java

Syntax of Java While Loop

The syntax of a while loop in Java is straightforward, designed to check a condition before executing the block of code within the loop. Here's how it looks:

while (condition) {
    // Statements to execute as long as the condition is true
}


In this structure:

  • condition: This is a boolean expression that the loop evaluates before each iteration. If the condition evaluates to true, the loop continues to execute the enclosed statements. If it evaluates to false, the loop terminates.
     
  • Statements: These are the lines of code that will be repeatedly executed for each iteration of the loop as long as the condition remains true.

For example, if we want to print numbers from 1 to 5, we can use the following while loop:

int i = 1; // Initialization
while (i <= 5) {
    System.out.println(i); // Print the number
    i++; // Update expression
}


This code will output the numbers 1 through 5, as the loop checks the condition i <= 5 before each iteration, and i is incremented after each print statement.

Execution of while loop program in Java

  1. Start: Marks the beginning of the loop process.
     
  2. Initialization: Set up initial values for variables.
     
  3. Condition Check: The loop condition (test expression) is evaluated.
  • If the condition is True:
  • Execute Loop Body: Perform the operations defined inside the loop.
  • Update Expression: Adjust the loop control variable as necessary.
  • Return to "Condition Check".
     
  • If the condition is False:
  • Exit Loop: Proceed to the next step after the loop.

 

Execution of while loop program in Java

If we try to understand with an example, consider a loop that counts backwards from 3:

  • Initialization: int i = 3;
     
  • Condition Check: while (i > 0)
     
  • Execute Loop Body: System.out.println(i);
     
  • Update Expression: i--;
     
  • Exit Loop: When i becomes 0, exit the loop.


The flowchart clearly shows that after initializing the variable, the condition is checked. If true, the body of the loop is executed followed by an update to the variable. The process cycles back to the condition check until the condition is false, at which point the loop ends.

Parts of Java While Loop

A while loop in Java consists of three main components that control its execution:

  1. Initialization: This step involves setting up a variable that the loop will use. Typically, this happens outside the while loop but is crucial for its operation. This variable often controls when the loop exits, based on the condition that is checked.
     
  2. Test Expression: The test expression is evaluated at the beginning of each loop iteration. This is the boolean condition that determines whether the loop will continue running or stop. If the expression evaluates to true, the loop executes the block of code inside it. If false, the loop terminates.
     
  3. Update Expression: While the update expression is not part of the while loop’s syntax directly, it’s critical for updating the state of the loop control variable. It is usually placed at the end of the loop's body. Properly managing the update expression is very important in  avoiding infinite loops, where the loop never ends if the condition never becomes false.

Test Expression

The test expression is the condition that is checked at the beginning of each iteration of the while loop. It must be a boolean expression that evaluates to either true or false. The loop continues executing as long as the test expression remains true.

The test expression can be a simple comparison, a method call that returns a boolean value, or a complex logical expression using operators like &&, ||, and !.

Point to remember : the test expression must involve variables that change within the loop, leading towards the condition becoming false, unlessyou intentionally want an infinite loop. This control of the loop helps in managing how many times the loop executes based on dynamic conditions.

For example : Consider a scenario where you want to double a number until it exceeds 100:

int number = 1; // Initialization outside the loop
while (number <= 100) { // Test Expression
    System.out.println(number);
    number *= 2; // Update Expression, modifies 'number' each time
}


In this code

  • Initialization: The variable number starts at 1.
     
  • Test Expression: The condition number <= 100 is checked.
     
  • Update Expression: Each loop iteration doubles number, and once number exceeds 100, the loop stops.

Update Expression

The update expression is a critical part of managing the flow of a while loop in Java. It directly influences the loop’s continuation or termination by modifying the loop control variable used in the test expression. 

The update expression is typically placed at the end of the loop body. It can be an increment, decrement, or any other operation that alters the value of the variable(s) being tested.

Let’s look at an example where we need to decrement a value from 10 to 1, printing each value:

int count = 10; // Initialization
while (count > 0) { // Test Expression
    System.out.println(count);
    count--; // Update Expression
}


In this code:

  • Initialization: Starts with count at 10.
     
  • Test Expression: Checks if count is greater than 0.
     
  • Update Expression: Decreases count by 1 each time the loop runs. When count reaches 0, the condition count > 0 becomes false, thus ending the loop.
     

The update expression (count--) ensures the loop does not run indefinitely and that each desired value is processed before the loop exits.

Note : Without an update expression, the loop condition would never change, leading to an infinite loop. Therefore, it's essential to include an appropriate update expression to ensure the loop progresses and terminates as intended.


Example

int i = 1;
while (i <= 5) {
    System.out.println("i = " + i);
    i++;
}

 

  • The test expression i <= 5 is evaluated. Since i is initially 1, the condition is true, & the loop body is executed, printing "i = 1".
     
  • The update expression i++ is evaluated, incrementing i to 2.
     
  • The test expression is evaluated again. Since i is now 2, which is still less than or equal to 5, the condition is true, & the loop body is executed, printing "i = 2".
     
  • Steps 2 & 3 are repeated until i becomes 6. At that point, the test expression i <= 5 becomes false, & the loop terminates.
     

The output of this code will be

i = 1
i = 2
i = 3
i = 4
i = 5

Examples of Java While Loop

Finally, look at few of the examples

Example 1: Counting Down

This simple example demonstrates a while loop that counts down from 10 to 1, printing each number:

  • Java

Java

int count = 10;

while (count > 0) {

   System.out.println(count);

   count--;  // Decrement count after each iteration

}
You can also try this code with Online Java Compiler
Run Code

 

Output

10
9
8
7
6
5
4
3
2
1

Example 2: Searching for a Value

Imagine you have an array of integers and you need to find whether a specific value exists in the array. A while loop can efficiently handle this task:

  • Java

Java


class CN {
public static void main(String[] args) {
int[] numbers = {3, 45, 1, 10, 33};
int target = 10;
int i = 0;
boolean found = false;

while (i < numbers.length && !found) {
if (numbers[i] == target) {
found = true; // Target found, exit loop
}
i++; // Move to the next index
}
System.out.println("Target found: " + found);


}
}
You can also try this code with Online Java Compiler
Run Code

 

Output

Target found: true

Example 3: Repeating User Input

A common use of while loops is to process user input until a particular condition is met, such as entering a correct password:

Scanner scanner = new Scanner(System.in);
String password;
do {
    System.out.print("Enter your password: ");
    password = scanner.nextLine();
} while (!password.equals("correctPassword"));
System.out.println("Access granted.");

Frequently Asked Questions

What happens if the test expression in a while loop never becomes false?

If the test expression never becomes false, the while loop will continue indefinitely, resulting in an infinite loop. This can cause your program to freeze or behave unpredictably.

Can while loops be nested inside other loops?

Yes, while loops can be nested within other while loops or different types of loops like for loops. Nesting is useful for handling multi-dimensional data structures or complex looping requirements.

Is it possible to exit a while loop without the condition becoming false?

Yes, you can exit a while loop prematurely using the break statement. When executed, break immediately terminates the loop, regardless of the condition.

What is the difference between do-while and while loop in Java?

The primary difference is that in a do-while loop, the condition is evaluated after executing the loop's body, ensuring at least one execution. In contrast, the while loop evaluates the condition first, possibly skipping execution if the condition is false.

Conclusion 

In this article, we have learned about while loops in Java. We discussed the syntax, parts of a while loop, how it executes, & looked at a flowchart to understand its control flow. We also showed several examples to see how while loops can be used in different scenarios. While loops are a fundamental concept in Java programming & are essential for creating repetitive tasks & iterating over data structures.

You can refer to our guided paths on the Code360. 

Live masterclass