×

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if statement. When we need to continually run a block of statements, Java's while loop is used. While loops are viewed as iterative if statements. Use of the while loop is advised if the number of iterations is not fixed. Until the provided Boolean condition is true, a section of the program is iterated again using the while loop in Java. The loop automatically ends when the Boolean condition changes from true to false.

While loops are viewed as iterative if statements. The while loop is advised if the number of iterations is not fixed.

Execution of while loop:

  1. The while loop takes over control.
  2. The condition condition flow jumps to is tested.
  3. The flow enters the Body if Condition results in a true result.
  4. If the condition returns false, the flow exits the loop.
  5. The statements contained within the loop's body are performed.
  6. Updates are made.
  7. It then returns to Step 2.
  8. The while loop has come to an end, and the flow has changed.

Syntax:

while (condition) {
//code to be executed   
Increment / decrement statement  
}  

The components of a do-while loop are:

  1. Condition: An expression is being tested. If the criterion is satisfied, the loop's body is executed before control is passed on to the update expression. We end the while loop when the condition is no longer true.
    Example:
    I <=100
  • Update expression: Every time the loop's body is executed, this expression raises or lowers the loop variable.
    Example:
    i++;

Flowchart of Java While Loop

While loops are significant in this context because they occasionally fail to run. If the condition being tested returns a false result, the while loop's body is skipped, and the first statement after the while loop is executed.

Example:

We output integer numbers from 1 to 10 in the example below. Unlike the for loop, the variable used in the condition needs to be initialized and increased independently. If not, the loop will run indefinitely.

WhileExample.java
public class WhileEx {  
public static void main(String[] s) {  
    int a=2;
    while(a<=11){  
        System.out.println(a);
a++;
    }  
}  
}  

Output:

2
3
4
5
6
7
8
9
10
11

Java Infinitive While Loop

If you include true in the while loop, the loop will continue forever.

Syntax:

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

Example2:

public class WhileEx2 {    
public static void main(String[] s) {   
 // passing true to the condition causes the while loop to be infinite
    while(true) {
        System.out.println("while loop of infinity");
    }    
}    
}    

Output:

while loop of infinity
while loop infinity
while loop infinity
while loop infinity
while loop infinity
In the code above, we must type Ctrl + C to break the infinite loop.

Dry-Running Example 1: The program will execute in the following manner.

  1. Program is started.
  2. a is initialized with value 2.
  3. Condition is verified. 2<7 yields true.
    • "Hello Raju" gets executed 1st time.
    • Updation is done. Now a = 3.
  4. Condition is verified. 3<7 yields true.
    • "Hello Raju" gets executed 2nd time.
    • Updation is done. Now a = 4.
  5. Checking the condition 4<7 yields true.
    • "Hello Raju" gets executed 3rd time
    •  Updation is done. Now a = 5.
  6. Checking the condition 5<7 yields true.
    • "Hello Raju" gets executed 4th time
    • Updation is done. Now a = 6.
  7. Checking the condition 6<7 yields true.
    • "Hello Raju" gets executed 5th time
    • Updation is done. Now a = 7.
  8. Checking the condition that is 7<7 yields false.
  9. Flow of the loop goes outside the loop. Program terminates.

Example 2: This program will find the summation of numbers from 1 to 10.

// program to declare while loop 
class whileLoop {
    public static void main(String s[])
    {
        int k = 1, s = 0;


        // Exit the loop when k becomes greater than 4
        while (x <= 10) {
            // adding up k
            s = s + k;
            // Incresing the value of k for next loop
k++;
        }
        System.out.println("Summation is: " + s);
    }
}

Output:

Summation is: 55

Related Topics

Libraries in Java

The Java Class Library (JCL) specifically is a set of dynamically loadable libraries that Java Virtual Machine (JVM) languages can call at any run time, which is fairly significant because...

6 minutes read.

Time Class Operation in Java

The Java SQL package includes the time class. This class is merely a lightweight wrapper for java. util. THANKS TO THE recognize BC API can recognize this as a SQL...

3 minutes read.

Java Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

3 minutes read.

Difference between Aggregation and Composition in Java

What is Aggregation? Before we start discussing Aggregation, we have to know some general information about our classes in java. Generally we have two members in our classes , the first...

8 minutes read.

Java Tutorial

What is Java? Java is an object-oriented, robust, secured and platform-independent programming language. With the help of Java Programming, we can develop console, window, web, enterprise and mobile applications. Java language was...

22 minutes read.

Java Math rint() Method

The rint() method of Java Math class returns the double value which is close to the specified argument and is equal to mathematical integer. Syntax: public static double rint(double a) Parameters: The parameter ‘a’...

1 minute read.

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 minutes read.

How to open the Java control panel

The many methods for launching the Java control panel will be covered in this section. We will also go through how the Java Control Panel can be used. Java Control Panel The...

2 minutes read.

Package Program in Java

Package Program in Java The package program in Java helps us to understand the significance of packages in Java. Packages are mainly used to group together similar classes, interfaces and sub-packages....

6 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we...

7 minutes read.

Repdigit Numbers in Java

A combination of repeated and digit, the term is. A repdigit, also known as a monodigit or a positional number system, is a natural number in recreational mathematics made up...

3 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.

How to get ASCII value of char in Java

Introduction: On this application, you will learn how to find and show the ASCII value of char in Java. That is done with the use of type-casting and also everyday...

4 minutes read.

Java vs Go

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Scanner in Java

Static way of Programming: When a variable can’t change its value during run time is called a Static way of programming. In this programming a variable is directly assigned to a...

4 minutes read.

Centered Square Numbers in Java

In this tutorial, we will understand how to check the number is a centered square number. It is one of the prevalent interview questions of IT companies. Firstly, we will...

3 minutes read.