Month End Sale: Get Extra 10% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now
while Loop in Java

while Loop in Java

25 May 2024
Beginner
411 Views
9 min read
Learn via Video Course & by Doing Hands-on Labs

Java Online Course Free with Certificate (2024)

while loop in Java

Java while loop is one of the most commonly used loops in Java. The while statement continually executes a block of statements while a particular condition is true. The test takes place before each iteration.

In this tutorial, we will learn What is while loop in Java, and while loop syntax in Java, and also look at some of the while loop programs in Java. To learn more about various concepts of Java Programming, do consider enrolling in our Java Certification Training right now!!

Read More: Top 50 Java Interview Questions and Answers Read More - Java Multithreading Interview Questions

What is a while loop in Java?

In Java Programming, the while loop is used to repeat the execution of a specific block of code based on a Boolean condition. It evaluates the condition to either be 'True' or 'False' and based on the boolean result the execution takes place. If the condition is true, the block of code inside the while is executed. But if the condition is false, the loop terminates immediately to carry on to the next statement which is just after the while loop.

Syntax of while loop in Java

while (condition) {
    // code to be executed
}

Parts of Java while Loop

1. Test Expression

In the Test Expression, the specified condition is checked. If the condition is evaluated to be 'True', the block of code inside the loop will be executed and it will move forward to the update expression. If the condition is false, the loop will terminate.

while (test_expression) {
    // body of the loop
}

Example:

int i = 1;
while (i <= 5) {
    // body of the loop
}
Here, 'i <= 5' is the test expression. This loop will be executed till the value of variable 'i' is less than or equal to '5'.

2. Update Expression

The Update Expression does an increment or decrement to the loop variable every time the execution of loop body occurs. It is written after the body of the loop. When the execution occurs and the loop comes to this expression the variable is incremented or decremented as specified in the expression. In short, it updates the value of the variable.

while (test_expression) {
    // body of the loop
    update_expression;
}

Example:

int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;  // update expression
}
Here, 'i++' is the update expression. It will increment the value of the variable 'i' by '1' after every iteration to make sure that at some iteration the value exceeds '5' and loop terminates.

Read More: Java Developer Salary Guide in India – For Freshers & Experienced

Flowchart of Java while Loop

Java while loop flowchart

How Does a while loop execute?

Now let's try to understand how exactly a while loop is executed in a Java Program.

  1. Initialization Firstly, all the variables that are to be used inside the loop are initialized. This initialization is done before the while loop starts.
  2. Condition Checking Then comes the step where the condition inside the while loop is checked. If the condition is evaluated to be 'True', the loop body is executed. If it evaluates to 'False', the loop is terminated and the program carries on with the next statement which is just after the loop.
  3. Body Execution The body of the while loop is executed if the condition is 'True' and then, the loop returns to the second step where the condition is checked again.
  4. Iteration Every time the loop body is executed, the loop variables are updated. They either increment or decrement and the value is changed for the next iteration accordingly.
  5. Loop Termination The while checks the condition till it becomes 'False' and if it does, the loop is terminated and the program moves on to the next statement just after the loop.

Examples of Java while loop

Let us look at some of the Java while loop examples in Java Compiler to understand it better.

1. Printing Numbers from 1 to 5

public class WhileLoopExample1 {
    public static void main(String[] args) {
        int i = 1;  // Initialization
        
        while (i <= 5) {  // Test expression
            System.out.println(i);  // Body
            i++;  // Update expression
        }
    }
}

Output

1
2
3
4
5

2. Calculating Factorial of a Number

public class WhileLoopExample2 {
    public static void main(String[] args) {
        int num = 5;
        int factorial = 1;
        int i = 1;  // Initialization
        
        while (i <= num) {  // Test expression
            factorial *= i;  // Body
            i++;  // Update expression
        }
        
        System.out.println("Factorial of " + num + " is: " + factorial);
    }
}

Output

Factorial of 5 is: 120

3. Countdown from 5 to 1

public class WhileLoopExample4 {
    public static void main(String[] args) {
        int i = 5;  // Initialization
        
        while (i >= 1) {  // Test expression
            System.out.println(i);  // Body
            i--;  // Update expression
        }
        
        System.out.println("Blast Off!");
    }
}

Output

5
4
3
2
1
Blast Off!
Summary

Through the above article, we learnt about while loop in Java, its structure, flowchart and also while loop example in Java Program. Do have a look on other loops in Java to have a proper understanding of them all. And if you are a beginner to Java Programming, get enrolled in our Java Programming Course to grab the comprehensive step by step guide to Java.

FAQs

Q1. What is a while loop in Java?

A while loop in Java executes certain block of code repeatedly until the specified condition evaluates to be true. It terminates as soon as the condition becomes false.

Q2. What is a while loop example?

Here is a while loop example:
count = 0
while count < 5:
    print(count)
    count += 1

Q3. What is do-while loop syntax?

Here is the syntax of do...while loop in Java:
do {
    // code block to be executed
} while (condition);

Q4. Why do-while loop is used?

A do...while loop is used when you want that certain block of code should run at least once before checking the loop condition.

Q5. How do I write a while loop?

To write a while loop:
  1. First, you need to initialize a variable outside of the loop.
  2. Use 'while' with a condition attached to it using the variable.
  3. Put an update expression after that so the loop eventually ends.
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Software Architecture and Design Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Solution Architect Certification Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Azure Developer Certification Training Jul 28 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Data Structures and Algorithms Training with C# Jul 28 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Microsoft Azure Cloud Architect Aug 11 SAT, SUN
Filling Fast
03:00PM to 05:00PM (IST)
Get Details
Angular Certification Course Aug 11 SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core Project Aug 24 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this