Java While Loop

πŸ” Java While Loop

A while loop in Java is used to repeatedly execute a block of code as long as a condition is true.


βœ… Syntax

while (condition) {
// code to execute
}

πŸ“Œ The loop runs only if the condition is true.


πŸ“˜ Example 1: Basic While Loop

public class Main {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
}
}

πŸ“Œ Output:

1
2
3
4
5

πŸ” How It Works

Step Action
1 Check condition i <= 5
2 If true β†’ execute code
3 Increase i++
4 Repeat until condition becomes false

πŸ“˜ Example 2: Countdown

public class Main {
public static void main(String[] args) {
int n = 5;
while (n > 0) {
System.out.println(“Countdown: “ + n);
n–;
}
System.out.println(“Go!”);
}
}

πŸ“Œ Output:

Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Go!

⚠️ Infinite Loop Example (Don’t do this unless intended)

while (true) {
System.out.println("Running...");
}

πŸ“Œ This never stops.


πŸ“˜ Example 3: Summation Loop

public class Main {
public static void main(String[] args) {
int sum = 0;
int i = 1;
while (i <= 5) {
sum += i; // sum = sum + i
i++;
}

System.out.println(“Total: “ + sum);
}
}

πŸ“Œ Output:

Total: 15

🧠 When to Use a while Loop?

Use while when:

βœ”οΈ You don’t know how many times the loop will run
βœ”οΈ Condition controls the loop execution

CodeCapsule

Sanjit Sinha β€” Web Developer | PHP β€’ Laravel β€’ CodeIgniter β€’ MySQL β€’ Bootstrap Founder, CodeCapsule β€” Student projects & practical coding guides. Email: info@codecapsule.in β€’ Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *