Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax
3.
Parts of Java While Loop
4.
Example 
5.
Test Expression
6.
Update Expression
7.
How Does a While loop execute?
8.
Example
9.
Flowchart For while loop (Control Flow)
10.
Examples of Java While Loop
10.1.
Example 1: Counting Down
10.2.
Java
10.3.
Example 2: Searching for a Value
10.4.
Java
10.5.
Example 3: Repeating User Input
11.
Frequently Asked Questions
11.1.
What happens if the test expression in a while loop never becomes false?
11.2.
Can while loops be nested inside other loops?
11.3.
Is it possible to exit a while loop without the condition becoming false?
12.
Conclusion 
Last Updated: Jun 12, 2024
Easy

While Loop in Java

Author Sinki Kumari
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

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

In this article, we'll talk about the syntax of while loops, their parts, how they execute.

Syntax

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Parts of Java While Loop

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

  • 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.
     
  • 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.
     
  • 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.

Example 

int i = 1; // Initialization
while (i <= 5) { // Test Expression
    System.out.println(i);
    i++; // Update Expression
}


In this example:

  • Initialization: We start with i set to 1.
     
  • Test Expression: The loop continues as long as i is less than or equal to 5.
     
  • Update Expression: We increment i by 1 at the end of each loop iteration to ensure the loop eventually terminates when i exceeds 5.

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.

How Does a While loop execute?

Now, let's see how while loop work and execute the loop:

  1. The test expression is evaluated first. If it's true, the loop body is executed. If it's false, the loop terminates & control passes to the next statement after the loop.
     
  2. After executing the loop body, the update expression is evaluated, modifying the variable(s) being tested.
     
  3. The test expression is evaluated again. If it's still true, the loop body is executed once more. If it's false, the loop terminates.
     
  4. Steps 2 & 3 are repeated until the test expression becomes false.

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

Flowchart For while loop (Control Flow)

  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".
     
  1. If the condition is False:
  • Exit Loop: Proceed to the next step after the loop.

 

Flowchart For while loop (Control Flow):

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.

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

}

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);


}
}

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.

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 Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Previous article
Difference between JDK, JRE and JVM
Next article
Math Functions in Java
Live masterclass