A while loop helps repeat a task as long as a condition is true. It saves time and avoids writing the same code again and again.
0
0
Why while loop is needed in Java
Introduction
When you want to keep asking a user for input until they give a valid answer.
When you want to keep checking if a game is still running.
When you want to repeat an action until a certain condition changes.
When you don't know in advance how many times you need to repeat something.
When you want to process items until a list or queue is empty.
Syntax
Java
while (condition) { // code to repeat }
The condition is checked before each repetition.
If the condition is false at the start, the code inside the loop may never run.
Examples
This prints numbers 0 to 4 by repeating the loop while
count is less than 5.Java
int count = 0; while (count < 5) { System.out.println(count); count++; }
This loop runs once because
running becomes false inside the loop.Java
boolean running = true; while (running) { // do something running = false; // stop after one run }
Sample Program
This program keeps asking the user to enter a positive number. It repeats the question until the user enters a number greater than zero.
Java
import java.util.Scanner; public class WhileLoopExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number = 0; while (number <= 0) { System.out.print("Enter a positive number: "); number = scanner.nextInt(); if (number <= 0) { System.out.println("That's not positive. Try again."); } } System.out.println("You entered: " + number); scanner.close(); } }
OutputSuccess
Important Notes
Be careful to change something inside the loop that eventually makes the condition false, or the loop will run forever.
Use while when you don't know how many times the loop should run before starting.
Summary
While loops repeat code as long as a condition is true.
They are useful when the number of repetitions is not known in advance.
Always make sure the loop condition will become false to stop the loop.