Table of Contents
1. Introduction
In programming, loops are fundamental constructs that allow us to execute a block of code repeatedly under certain conditions. Java provides various loop structures, and one of the simplest among them is the while loop. The while loop repeatedly executes a target statement as long as a given condition is true
. A while loop is recommended when the number of iterations is not known beforehand.
Example:
Consider we want to print numbers from 1 to 5. Here, our goal is to use a while loop to iterate through these numbers and print them out. The expected output would be a simple sequence of numbers, each on a new line:
1 2 3 4 5 6 7 |
1 2 3 4 5 |
2. The Syntax of a While loop
1 2 3 4 5 6 |
while (condition) { // Body of the loop // Statements to execute } |
- Condition: This is a Boolean expression that must evaluate to
true
for the loop to continue executing. Once the condition evaluates tofalse
, the loop stops. - Body of the Loop: This section contains the statements that are executed on each iteration of the loop as long as the condition remains
true
.
3. Basic While Loop Example
Let’s implement our initial goal of printing numbers from 1 to 5 using a while loop:
1 2 3 4 5 6 7 8 9 10 11 12 |
public class WhileLoopExample { public static void main(String[] args) { int number = 1; // Starting number while (number <= 5) { // Condition to check System.out.println(number); // Print the current number number++; // Increment the number } } } |
Output:
1 2 3 4 5 6 7 |
1 2 3 4 5 |
Explanation:
- We start with a variable
number
initialized to 1. - The condition
number <= 5
is checked. If it’strue
, the loop’s body executes. - Inside the loop, we print the current value of
number
and then increment it by 1 usingnumber++
. - This process repeats until
number
becomes 6, at which point the conditionnumber <= 5
evaluates tofalse
, and the loop terminates.
If you are still confused by the above concept, let’s understand it with the help of a flow diagram:
Let’s try to print only even numbers now:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class WhileLoopMain { public static void main(String[] args) { int i=1; while(i<11) { if(i%2==0) System.out.print(" "+i); i++; } } } |
Output:
1 2 3 |
2 4 6 8 10 |
4. Infinite While Loop
An infinite loop occurs when the condition in a while loop always evaluates to true. This can happen due to several reasons, such as:
- The loop condition is explicitly set to a boolean
true
. - The condition involves variables that are never modified within the loop, leading to a perpetual
true
state. - Logical errors in the loop’s design prevent the condition from ever becoming false.
Let’s illustrate an infinite loop with a simple example where the loop condition remains true
indefinitely:
1 2 3 4 5 6 7 8 9 |
public class InfiniteWhileLoopExample { public static void main(String[] args) { while (true) { System.out.println("This line will be printed endlessly"); } } } |
In this example, the condition specified in the while loop is the boolean value true
, which means the loop will never terminate on its own. The print statement will execute repeatedly without end.
One common use case is in server applications that continuously listen for incoming client requests. Here’s a simplified example:
1 2 3 4 5 6 7 8 9 10 11 12 |
public class ServerListener { public static void main(String[] args) { while (true) { // Listen for client connections // Accept a connection when one is made // Handle the connection // Loop back to listen for more connections } } } |
In this scenario, the server needs to run indefinitely, always waiting to accept and process new client connections. The infinite loop is crucial for the persistent operation of the server.
5. Exercise
Let’s apply our knowledge of while loops by writing a program.
Given an array of integers like {32, 45, 53, 65, 43, 23}
, your task is to search for a specific element within this array. If the element exists, your program should output ‘PRESENT’; if it doesn’t, it should output ‘NOT PRESENT’.
I would recommend that you try it yourself first and then look at the code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package org.arpit.java2blog; public class WhileLoopMain { public static void main(String[] args) { WhileLoopMain bse=new WhileLoopMain(); int arr[] ={32,45,53,65,43,23}; System.out.println(bse.findElementInArr(arr, 53)); } public String findElementInArr(int arr[],int elementTobeFound) { int i=0; while(i<arr.length) { if(arr[i]==elementTobeFound) { System.out.println(elementTobeFound+" is present in the array "); return "PRESENT"; } i++; } return "NOT PRESENT"; } } |
1 2 3 4 |
53 is present in the array PRESENT |
6. Conclusion
The while loop in Java is a powerful tool for executing a set of statements repeatedly based on a condition. Its simplicity makes it particularly useful in situations where the number of iterations required is not predetermined. By understanding and effectively utilizing the while loop, we can implement solutions to a wide range of programming problems, from simple tasks like printing a sequence of numbers to more complex algorithms that depend on dynamic conditions. Always remember to ensure that the loop will eventually terminate by modifying a condition within the loop’s body, thereby preventing infinite loops.