×

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

Java InputStreamReader

What is InputStreamReader?An InputStreamReader is a converter between byte and character streams: It reads bytes and converts them to characters with the help of a charset. The charset it uses can...

4 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 minutes read.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

Java vs Golang

Java Java is both a programming language and a platform. Java is a high-level, dependable, object-oriented, and secure programming language. Java was developed in 1995 by Sun Microsystems, which is now an...

4 minutes read.

Java CountDownLatch

Another crucial classes for concurrent execution is CountDownLatch. It is a synchronisation tool that enables one or more threads to await until a series of tasks started by another thread...

4 minutes read.

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

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.

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

Abstract Class Program in Java

Abstract Class Program in Java Abstraction is a technique by which a developer hides the implementation details from the user and shows only the functionality.It is not only confined to the...

6 minutes read.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.