Home > Java > javaTutorial > body text

While Loop in Java

王林
Release: 2024-08-30 15:25:00
Original
656 people have browsed it

We use different loops to iterate through the program so as to get the desired outcome. One of the loops provided by JAVA is the while loop. All the loops provide similar functionality. The difference between these loops is of Syntax and the condition checking time. If there is no requirement as such to have a fixed number of iterations, then we use a while loop instead of other loops. While loop can be considered as repeated If loop. It executes only if the condition is met.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

According to the condition given in a while loop, Boolean values are outputted. If the resultant Boolean value is true, then the loop will be executed; otherwise, control will flow out of the loop, thereby terminating the while loop. This loop will continuously execute until the condition becomes false.

The syntax for while loop is shown below:

while (Boolean Condition)
{
//code snippet…
}
Copy after login

Here, after a while keyword, we give conditions in brackets. If this condition returns true, then the code written under curly braces will be executed. So as to terminate the while loop, the condition needs to be updated every time the loop is executed. The syntax for this is provided below:

while (Boolean Condition)
{
//Entered in the loop
//Code snippet…
Loop update;
}
Copy after login

Work Flow

Below is the workflow diagram of the while loop. When the main program is executed, and the program encounters a while loop in the program. The condition corresponding to the while loop is checked, which is written in brackets. If the condition is met to return true, then the control enters the loop body. This loop is executed until the condition returns false. Once this condition returns false, then while loop is terminated. Then the code written out of the while loop is executed, and accordingly, the result is generated.

While Loop in Java

Examples of While Loop in Java

Below are some of the code snippets which demonstrate the use of while loop

Example #1

This loop is an infinite loop because we have hardcoded True (1) here. Hence we should be very careful when working with a while loop and give proper terminating condition otherwise;, the loop will run into an infinite loop.

Note: You can paste this code in “notepad” with extension .java.

Code:

public class Main
{
public static void main ( String[] args)
{
while(true)
{
System.out.println ("infinite loop");
System.out.println ("press ctrl+c to exit");
}
}
}
Copy after login

Output: We will find the above two sentences printed infinite times. This is a no-terminating loop as the condition true is passed with no loop updating anywhere. To exit, we can close the console window if executing code in any online java compiler or press “ctrl+c” to exit.

While Loop in Java

Example #2

This is a simple program to iterate 10 times and print the numbers from 1 to 10. Once the condition returns false in a while loop, the control will come out of the loop. Here variable “i” is initialized with 1. “i” is compared as a precondition written (which is “i” should be less than or equal to 10). The “i” is incremented by one (because of i++) every time the loop is executed. When “i” becomes 11, the condition returns false, and the loop will be terminated printing numbers starting from one to ten on the output screen. Since we are using System.out.println to print the numbers, here “ln” after print ensures that every number I printed in the next line. If we would have used print instead of println then the numbers would have printed in the same line without spaces.

Code:

public class Main
{
public static void main( String[] args)
{
int i=1;
System.out.println("Printing numbers from 1 to 10");
while (i<=10)
{
System.out.println(i);
i++;
}
}}
Copy after login

Output:

While Loop in Java

Important Points when using a While Loop

1. Initialize every variable you are using in a while loop. It is advised to declare the variable outside the while loop since declaring a variable inside the loop may lead to an undesirable output.

2. The while loop in your java program must contain a closing statement for its termination. Otherwise, you will end up with an infinite loop which will waste a lot of memory. You will have to close the output window and restart the program execution. This, in turn, will waste a lot of time if you are running a big program.

3. While loop can be called as a “universal loop” because any other loop (for, do-while) can be written in the form of a while loop. However, the reverse is not true.

4. While it is an entry-controlled loop. If the condition is met, then only the code inside the while loop will be executed; otherwise, the while loop will be terminated, and the statement after while loop will be executed.

5. We can also write empty while loop. For example:

while ( x < 10 ) ;

Considering x is initialized with 1. This loop will simply be executed without affecting the data in the program. It is advisable not to have empty while loops since it delays the execution time of the program. Although it can be used in case, we deliberately want to delay the execution of the program.

6. We should not use a semicolon after the condition in a while loop. This will throw an error.

7. Break and continue statements followed by semi-colon can be used under a while loop. Continue statement is used to skip the immediate line of code, while a break statement is used to break the current loop and move the control out of the loop.

Conclusion

In a while statement, we want the system to repeat various smaller statements repetitively. To have these smaller statements together, we combine these statements to form a big single statement by making a block of curly braces.

The above is the detailed content of While Loop in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!