While loop is the basic looping statement in Java. It is used for executing statements repeatedly in programs. If the condition is true then the statement will be executed. When developers don’t know in advance, how many times the loop will be executed then they go for a while loop.
In this article, we will study the working of a while loop in Java. And, we also look at syntax, flowcharts, and programming examples.
What is a while loop in Java?
While loop is also called an entry-controlled loop because the condition is checked before loop execution.
If the condition is true then the body of the loop will be executed. This execution continues as long as the condition remains true.
If the condition is false then the body of the loop will be skipped and the control jumps to the outside of the loop (next statement).
Syntax
while (condition) {
// Code to be executed repeatedly
}
Explanation
while
Keyword: This starts the loop and tells Java to keep checking a condition.- Condition: Placed inside the parentheses
()
, this is a true-or-false test. If true, the loop runs. If false, the loop stops. - Curly Braces
{}
: The code inside these braces is the loop’s body. It gets executed repeatedly as long as the condition is true. - How It Works: The loop checks the condition first. If it’s true, the loop runs the code inside the braces and then checks the condition again. This repeats until the condition becomes false, and the loop stops.
Flowchart
let’s understand the working of a while loop with the help of a flowchart.
- First, control starts from the top.
- Then, the test condition is checked if it is true then the body of the loop will be executed.
- After the loop body execution, the control goes to the test condition again and now again test condition is checked if it is true again the body of the loop will be executed again.
- After the loop body execution a second time, again control goes to the test condition, and again the test condition is checked, suppose now the condition is false then the control jumps to outside of the while loop (means the next statement in the program).
Simple while loop program in Java
public class SimpleWhileLoop {
public static void main(String[] args) {
int number = 1; // Initialize the counter variable
// While loop that runs as long as number is less than or equal to 5
while (number <= 10) {
System.out.println("Number: " + number); // Print the current number
number++; // Increment the counter variable
}
}
}
Explanation
- Set-Up:
- Start with
number
= 1.
- Start with
- Loop Condition:
- Continue looping while
number
is less than or equal to 10.
- Continue looping while
- Inside the Loop:
- Print the current value of
number
. - Add 1 to
number
.
- Print the current value of
- Stop:
- The loop stops when
number
becomes greater than 10.
- The loop stops when
- Finish:
- The program ends after the loop.
Output
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
Number: 10
Prime number program using while loop in Java
public class PrimeNumberCheck {
public static void main(String[] args) {
int number = 29; // The number to check if it's a prime
boolean isPrime = true; // A flag to check the prime status
// Starting the loop with the smallest possible divisor
int i = 2;
// Loop to check divisibility starting from 2 up to the square root of the number
while (i <= Math.sqrt(number)) {
// If the number is divisible by any number other than 1 and itself
if (number % i == 0) {
isPrime = false; // Set the flag to false if it's divisible
break; // Exit the loop early since we found a divisor
}
i++; // Increment the loop counter
}
// Check the flag to see if the number is prime
if (isPrime && number > 1) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}
}
Explanation
- Variable Initialization:
int number = 29;
: This is the number we want to check if it’s a prime. You can change this number to test other values.boolean isPrime = true;
: We start by assuming the number is prime. We’ll change this later if we find it’s not.int i = 2;
: We start checking from 2, the smallest prime number.
while
Loop:while (i < number) {
: The loop runs as long asi
is less than the number. This means we check every number from 2 up tonumber - 1
.
- Checking Divisibility:
if (number % i == 0) {
: This checks ifnumber
is divisible byi
without a remainder. If it is, thennumber
is not a prime number.isPrime = false;
: If we find any number that divides, we set isPrime it tofalse
.break;
: We stopped checking further since we already found a divisor.
- Increment the Counter:
i++;
: We increasei
to check the next number.
- Final Check and Output:
if (isPrime && number > 1) {
: We check ifisPrime
is still true and that the number is greater than 1 (since 1 is not considered prime).System.out.println(number + " is a prime number.");
: This prints if the number is prime.System.out.println(number + " is not a prime number.");
: This prints if the number is not prime.
Output
29 is a prime number.
Calculate Factorial Using while
Loop in Java
import java.util.Scanner;
public class FactorialCalculator {
public static void main(String[] args) {
// Create a Scanner object to get input from the user
Scanner input = new Scanner(System.in);
// Ask the user for a number
System.out.print("Enter a positive number to find its factorial: ");
int number = input.nextInt(); // Read the user input
int result = 1; // This will hold the final factorial result
int count = 1; // Counter starting at 1
// Calculate the factorial using a while loop
while (count <= number) {
result = result * count; // Multiply current count with result
count++; // Increment the counter
}
// Display the result
System.out.println("Factorial of " + number + " is: " + result);
}
}
Explanation
- Import Scanner Class:
import java.util.Scanner;
: This imports the Scanner class to take input from the user.
- Setting Up the Scanner:
Scanner input = new Scanner(System.in);
: We create aScanner
object namedinput
to read user input from the console.
- User Input:
System.out.print("Enter a positive number to find its factorial: ");
: We prompt the user to enter a positive integer.int number = input.nextInt();
: We read the integer input from the user and store it in thenumber
variable.
- Initializing Variables:
int result = 1;
: We initializeresult
to 1. This variable will hold the factorial result.int count = 1;
: We initializecount
to 1, which will be used as our loop counter.
while
Loop to Calculate Factorial:while (count <= number) {
: The loop runs as long ascount
is less than or equal tonumber
.result = result * count;
: We multiply the currentresult
bycount
and store it back inresult
.count++;
: We incrementcount
by 1.
- Displaying the Result:
System.out.println("Factorial of " + number + " is: " + result);
: We print the final factorial result to the console.
Output
Enter a positive number to find its factorial: 5
Factorial of 5 is: 120
Conclusion
In this article, we’ve covered the basics of the while
loop in Java, including its syntax, flowchart, and practical examples. The while
loop is useful for repeating actions as long as a condition is true, making it perfect for tasks like continuously reading data or checking user input. By mastering the while
loop, you can create more efficient and dynamic Java programs. Keep experimenting with different scenarios to get comfortable using the while
loop, and you’ll soon find it an indispensable part of your coding toolkit.
We’d Love to Hear From You!
Do you have questions or feedback about the while
loop in Java? We’re here to help! Whether you need further clarification, have suggestions, or simply want to share your thoughts, please leave a comment below. Your feedback is invaluable in helping us improve our content and support others in their learning journey. Don’t hesitate to reach out—we’re excited to hear from you!
Read More: Switch case in Java: Syntax, Flowchart, and Practical Examples
Additional Resource: Want to read more about it then go to the Oracle documentation.