Java While Loop

The Java while loop is to iterate a code block for a given number of times till the condition inside it is False. At the same time, the while loop starts by verifying the condition. If it is true, the code within this will run. If the condition is false, the while loop will not run at least once.

Java while loop syntax

By this, we can say, a while loop may compile zero or more time, and the syntax is

While( JCondition )  {
    Jstatement 1;
    Jstatement 2;
    ………….
    Jstatement N;
}
// This statement is from outside of it

First, Javac tests the While loop condition. If the condition result is True, the statement(s) Jstatement 1 to Jstatement N inside it will run. If it is False, the Javac will get out of the curly brackets and complete the declarations outside.

Curly braces are not required for a single-line while loop code in ths Programming. However, if we ignore them for multiple statements, the Javac will execute the first line only. It is safe to utilize braces all the time.

Flow Chart of a Java While loop

The following picture presents the While Loop flow chart

While Loop FLOW CHART

At the beginning of it, the While loop in Java programming language tests the condition.

  1. If the test results are True, the code inside it will run.
  2. Next, we have to use Increment and Decrement Operators within this to raise or lower the value.
  3. After the value is incremented again, Javac will test the condition. Javac will repeat the process as long as the test results are True.
  4. If the test results are False, Javac will terminate it.

Let’s view one example of a While loop for a better conclusion.

Java While Loop example

This programming while loop lets the user insert an integer value under 10. Next, the Javac compiler finds the sum of those numbers up to 10.

import java.util.Scanner;

public class Sample {

	private static Scanner sc;
	
	public static void main(String[] args) {
		int number, sum = 0;
		sc = new Scanner(System.in);	
		
		System.out.println("\n Please Enter the any integer Value below 10: ");
		number = sc.nextInt();
		
		while(number <= 10)  {
			sum = sum + number;
			number++;
		}
		
		System.out.format(" Sum of the Numbers From this is: %d ", sum);

	}

}

We are going to enter the number = 7. It means, total = 7 + 8 + 9 + 10 = 34

Java While Loop Example

We used the Java While loop, and the Condition inside will ensure that the given number is less than or equal to 10. In this example, the User given values: Number = 7. Next, we initialized the sum = 0

First Iteration

sum = sum + number

sum = 0 + 7 ==> 7

Next, the number will be incremented by 1 (number ++). Refer Java Increment & Decrement Operators article on the Java tutorial page to understand this ++ notation.

Second Iteration

Within the first Iteration, both Number and sum changed as Number = 8 and sum = 7

sum = 7 + 8 = 15

Third Iteration

From the Second Iteration, Number = 9 and sum = 15

sum = 15 + 9 ==> 24

Fourth Iteration: Within the third Iteration of the while loop, the values of both Number and sum changed as Number = 10 and sum = 24

sum = 24 + 10 ==> 34

Next, the number will increment by 1

Here Number = 11. So, the condition present will fail.

The last System.out.format statement will print the number of digits present in the given number as output.

TIP: Please refer to the Java for loop, Java do-while loop, and the difference between the while and do-while articles for more information on loops.

Java while loop multiple conditions

A while loop is not limited to checking a single expression. We can use the while loop to evaluate multiple conditions. Once those conditions become true, the Javac compiler enters the loop.

For example, a web hosting company charges users based on server usage. In such a case, we use two conditions with multiple variables in a Java while loop. In the following program, we declare two variables to store the minimum hosting price in dollars and the server usage a user gets for that initial amount.

The while loop checks whether the total price is less than or equal to 10 and the server usage is less than or equal to 80. Here, the Java logical operator (&&) makes sure both conditions are met. If either of them fails, the compiler exits the while loop.

Inside the loop, we are printing the server usage and the hosting price. Next, increment the price by $2 for each 10% of server usage. The loop continues until the price_in_dollars variable reaches 10.

public class example {
public static void main(String[] args) {
int price_in_dollars = 2;
int server_usage = 20;

while (price_in_dollars <= 10 && server_usage <= 80) {
System.out.println("Total Usage in this Month = " + server_usage + "%");
System.out.println("Web Hosting Price = $" + price_in_dollars);

price_in_dollars += 2;
server_usage += 10;
}

}
}
Total Usage in this Month = 20%
Web Hosting Price = $2
Total Usage in this Month = 30%
Web Hosting Price = $4
Total Usage in this Month = 40%
Web Hosting Price = $6
Total Usage in this Month = 50%
Web Hosting Price = $8
Total Usage in this Month = 60%
Web Hosting Price = $10

How to stop an Infinite while loop in Java?

Within this, if you skip to increment or decrement the number, it will run for infinite times, also called the infinite loop. Let me show you an example of Infinite.

package Test;

public class InfiniteExample {
	public static void main(String[] args) {
		int number = 1;
		
		while (number <= 10)  {
			System.out.format("Numbers = %d ", number);
		}
	}
}
1
1
1
1
1
1
.....
....

In this infinite While loop example, the number is forever 1, which is ever less than ten. So, it will go on executing the statement infinite times.

Let’s put an increment operator (number++) inside the preceding example.

 
package Test;

public class InfiniteExample {
	public static void main(String[] args) {
		int number = 1;
		
		while (number <= 10)  {
			System.out.format("Values = %d\n", number);
			number++;
		}
	}
}

Now, when it equals 10, the condition will fail. The output of this example

1
2
3
4
5
6
7
8
9
10

NOTE: We can use the Java break statement and Java continue statement to break or to stop the current iteration.

Java while loop true (break) example

The while loop true (always true) expression is handy when we want to run the while loop infinitely until a certain condition is met. For instance, a shared hosting company allows users to use their hosting server until their usage limit reaches 90%.

It’s a simple example, but it shows how the while loop’s true expression works. Here, we set the initial server usage to 20% and then used the while loop’s true condition, which always returns true. Inside the loop, we incremented the server usage by 20% on each iteration. Next, the if statement checks whether the server usage reaches 90%. If true, the break statement exits the loop.

public class example {
public static void main(String[] args) {
int server_usage = 20;

while (true) {
System.out.println("Total Usage in this Month = " + server_usage + "%");
server_usage += 20;

if (server_usage >= 90) {
break;
}
System.out.println("You have reached the Hosting Plan limit");
}
}
}
Total Usage in this Month = 20%
You have reached the Hosting Plan limit
Total Usage in this Month = 40%
You have reached the Hosting Plan limit
Total Usage in this Month = 60%
You have reached the Hosting Plan limit
Total Usage in this Month = 80%

Java while loop scanner for user input

One advantage of the while loop over the for loop is that we can use it to accept user input. For example, use a while loop to allow multiple user inputs until they enter the correct one (username).

In the following example, we take the hosting company price checker. This program allows the user to enter the total number of page views in a month. Within the Java while loop (true, which is always true), we use the else if statement. Here, the Java else if statement checks whether the page views are between 0 and 100000.

  1. If total views are below 10000, the hosting price is $5.
  2. If the views are below 25000, the hosting price is $20.
  3. For views below 100000, the price becomes $100.
  4. Otherwise, the user should opt for the enterprise custom model. Here, the break statement exits the compiler from the while loop.

TIP: If we use a menu-style program, we can use a proper condition inside the while loop to exit. In such a case, we can remove the break statement.

import java.util.Scanner;

public class example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

while (true) {
System.out.print("Enter the Total Views = ");
int views = sc.nextInt();

if (views <= 10000) {
System.out.println("Hosting Price = $" + 5);
} else if (views <= 25000) {
System.out.println("Hosting Price = $" + 20);
} else if (views <= 100000) {
System.out.println("Hosting Price = $" + 100);
} else {
System.out.println("You must Prefer the Custom Enterprise Hosting");
break;
}
}
}
}
Enter the Total Views = 22000
Hosting Price = $20
Enter the Total Views = 94000
Hosting Price = $100
Enter the Total Views = 200000
You must prefer the Custom Enterprise Hosting

How to read a file line by line using a Java while loop?

The while loop allows read a file line by line. To do so, we must import the BufferedReader and FileReader. The while loop condition checks whether the current line has any text.

Here, the readLine() function reads one line at a time from the given text file. If the current line is not null, the compiler enters the while loop. In the loop, we print the text in the line. This iteration process continues until readLine() returns null; eventually, the expression inside the while loop fails.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class example {
public static void main(String[] args) {
try {
BufferedReader r = new BufferedReader(new FileReader("C:\\Users\\..\\..\\hostPrice.txt"));
String line;
while ((line = r.readLine()) != null) {
System.out.println(line);
}
r.close();
} catch (IOException e) {
System.out.print("No file detected");
}

}
}
Basic Plan = $5
Popular Plan = $25
Premium Plan = $60
Advanced Plan = %100 

Comments are closed.