- 1Java Exceptions
- 2Java Keywords
- 3Java abstract Keyword
- 4Java assert Keyword
- 5Java boolean Keyword
- 6Java break Keyword
- 7Java byte Keyword
- 8Java case Keyword
- 9Java catch Keyword
- 10Java char Keyword
- 11Java class Keyword
- 12Java const Keyword
- 13Java continue Keyword
- 14Java default Keyword
- 15Java do Keyword
- 16Java double Keyword
- 17Java else Keyword
- 18Java enum Keyword
- 19Java extends Keyword
- 20Java final Keyword
- 21Java finally Keyword
- 22Java float Keyword
- 23Java for Keyword
- 24Java goto Keyword
- 25Java if Keyword
- 26Java implements Keyword
- 27Java import Keyword
- 28Java instanceof Keyword
- 29Java int Keyword
- 30Java interface Keyword
- 31Java long Keyword
- 32Java native Keyword
- 33Java new Keyword
- 34Java null Keyword
- 35Java package Keyword
- 36Java private Keyword
- 37Java protected Keyword
- 38Java public Keyword
- 39Java return Keyword
- 40Java short Keyword
- 41Java static Keyword
- 42Java strictfp Keyword
- 43Java super Keyword
- 44Java switch Keyword
- 45Java synchronized Keyword
- 46Java this Keyword
- 47Java transient Keyword
- 48Java try Keyword
- 49Java void Keyword
- 50Java volatile Keyword
- 51Java while Keyword
- 52Java String Methods - Syntax and Description
- 53Java String
charAt()
method - 54Java String
codePointAt()
method - 55Java String
codePointBefore()
method - 56Java String
codePointCount()
method - 57Java String
compareTo()
method - 58Java String
compareToIgnoreCase()
method - 59Java String
concat()
method - 60Java String
contains()
method - 61Java String
contentEquals()
method - 62Java String
copyValueOf()
method - 63Java String
endsWith()
method - 64Java String
equals()
method - 65Java String
equalsIgnoreCase()
method - 66Java String
format()
method - 67Java String
getBytes()
method - 68Java String
getChars()
method - 69Java String
hashCode()
method - 70Java String
indexOf()
method - 71Java String
intern()
method - 72Java String
isEmpty()
method - 73Java String
join()
method - 74Java String
lastIndexOf()
method - 75Java String
length()
method - 76Java String
matches()
method - 77Java String
offsetByCodePoints()
method - 78Java String
regionMatches()
method - 79Java String
replace()
method - 80Java String
replaceAll()
method - 81Java String
replaceFirst()
method - 82Java String
split()
method - 83Java String
startsWith()
method - 84Java String
subSequence()
method - 85Java String
substring()
method - 86Java String
toCharArray()
method - 87Java String
toLowerCase()
method - 88Java String
toString()
method - 89Java String
toUpperCase()
method - 90Java String
trim()
method - 91Java String
valueOf()
method - 92Java ArrayList Methods - Complete Reference with Syntax and Description
- 93Java LinkedList Methods - Complete Reference with Syntax and Description
- 94Java HashMap Methods - Syntax and Descriptions
Java while Keyword
Usage and Examples
while
Keyword in Java
The while
keyword in Java is used to create a loop that continues executing a block of code as long as a specified condition is true
. It’s one of the fundamental looping constructs every Java programmer must master.
Syntax of while
Loop
while (condition) {
// Code to execute repeatedly
}
The loop checks the condition before executing the block. If the condition is false at the beginning, the loop body is skipped altogether.
Flow of Control
- Check the condition.
- If true, execute the loop body.
- Go back and check the condition again.
- If false, exit the loop.
Example 1: Simple Counting Loop
public class WhileExample1 {
public static void main(String[] args) {
int count = 1;
while (count <= 5) {
System.out.println("Count: " + count);
count++;
}
}
}
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Explanation: The loop runs as long as count
is less than or equal to 5. On each iteration, it prints the value and increments the count by 1.
Example 2: Summing Numbers
public class WhileExample2 {
public static void main(String[] args) {
int sum = 0, i = 1;
while (i <= 10) {
sum += i;
i++;
}
System.out.println("Sum of first 10 numbers: " + sum);
}
}
Sum of first 10 numbers: 55
This example demonstrates how we can use a while
loop to compute the sum of a sequence of numbers. The logic is simple and readable.
Example 3: Infinite Loop (Be Careful!)
public class WhileExample3 {
public static void main(String[] args) {
while (true) {
System.out.println("This loop will run forever...");
}
}
}
Warning: This loop has no exit condition. It's an infinite loop and must be manually stopped.
Use Case: Input Validation
The while
loop is especially helpful for validating user input:
import java.util.Scanner;
public class WhileInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
System.out.print("Enter a number greater than 0: ");
number = scanner.nextInt();
while (number <= 0) {
System.out.println("Invalid input. Try again.");
System.out.print("Enter a number greater than 0: ");
number = scanner.nextInt();
}
System.out.println("Thank you! You entered: " + number);
}
}
Enter a number greater than 0: -5
Invalid input. Try again.
Enter a number greater than 0: 0
Invalid input. Try again.
Enter a number greater than 0: 3
Thank you! You entered: 3
Common Mistakes with while
Loops
- Forgetting to update the loop variable, which leads to infinite loops.
- Using conditions that are never true, causing the loop to be skipped.
- Using complex or unclear conditions that are hard to debug.
When to Use while
Loops
Use a while
loop when:
- You don’t know beforehand how many times the loop should run.
- You want to keep running a block of code until a certain condition changes dynamically.