As we discussed in our Java for loop guide, loops are essential for executing repetitive tasks efficiently. Among the different types of loops available in Java, the "while" loop provides a flexible and powerful mechanism for iterating until a specified condition is met. In this article, we will delve into the details of the Java while loop, explore its syntax, discuss practical use cases, and provide examples with expected outputs.
Java While Loop:
The while loop in Java is a control flow statement that
repeatedly executes a block of code as long as a given condition remains true.
Syntax of the Java While Loop:
The syntax of the while loop consists of the keyword
"while" followed by a Boolean expression in parentheses, and a block
of code enclosed within curly braces. The loop continues to execute the code
block as long as the condition evaluates to true.
Syntax:
while(condition){
//code to be executed
}
Example: Printing first 5 numbers:
int count = 1;
while (count <= 5) {
System.out.println("Count: " + count);
count++;
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Working Principle of the Java While Loop:
1. The condition is evaluated: Before executing the
code block, the condition is evaluated. If it is true, the code block is
executed. If false, the loop is terminated, and control is passed to the next
statement after the loop.
2. Code block execution: If the condition is true,
the code block within the while loop is executed. It can include any valid Java
statements, such as variable assignments, method calls, or conditional
statements.
3. Condition update: After executing the code block,
the condition is re-evaluated. If the condition remains true, the loop repeats
step 2. If false, the loop terminates.
Practical Use Cases and Examples:
1. Counting with a While Loop:
int i = 1;
while (i <= 10) {
System.out.print(i
+ " ");
i++;
}
Output:
1 2 3 4 5 6 7 8 9 10
2. User Input Validation:
Scanner scanner = new Scanner(System.in);
int age = 0;
while (age <= 0) {
System.out.print("Enter your age: ");
age =
scanner.nextInt();
if (age <= 0) {
System.out.println("Invalid
age. Please enter a positive value.");
}
}
System.out.println("Age entered: " + age);
Output:
Enter your age: -5
Invalid age. Please enter a positive value.");
Enter your age: 0
Invalid age. Please enter a positive value.");
Enter your age: 20
Age entered: 20
3. Password Validation:
Scanner scanner = new Scanner(System.in);
String password = "";
while (!password.equals("secret")) {
System.out.print("Enter the password: ");
password =
scanner.nextLine();
if
(!password.equals("secret")) {
System.out.println("Invalid password. Try again.");
}
}
System.out.println("Access granted!");
Output:
Enter the password: pass
Invalid password. Try again.
Enter the password: mypass1
Invalid password. Try again.
Enter the password: secret
Access granted!
4. Reversing a number:
Write a program that prompts the user to input an integer
and then outputs the number with the digits reversed. For example, if the input
is 12345, the output should be 54321.
Solution:
import java.util.Scanner;
public class ReverseNumber {
public static void
main(String[] args) {
Scanner
console = new Scanner(System.in);
int number;
int reverse =
0;
System.out.print("Enter the number: ");
number =
console.nextInt();
int temp =
number;
int remainder
= 0;
while(temp>0) {
remainder = temp % 10;
reverse = reverse * 10 + remainder;
temp /=
10;
}
System.out.println("Reverse of " + number + " is " +
reverse);
}
}
When you run the program, the output will be:
Enter the number: 12345
Reverse of 12345 is 54321
Understanding Infinite Java While Loops:
An infinite while loop occurs when the test expression
within the while loop always evaluates to true. As a result, the loop continues
executing indefinitely until an external intervention interrupts the program's
execution. It is crucial to use infinite loops with caution, as they can lead
to program freezing or unresponsiveness if not handled properly.
Example 1: Counting Up Infinitely:
int i = 1;
while (true) {
System.out.print(i
+ " ");
i++;
}
Output:
This example will continuously print an increasing sequence
of numbers, starting from 1 and continuing indefinitely until manually
interrupted.
Example 2: Endless User Input Prompt:
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter a number: ");
int number =
scanner.nextInt();
System.out.println("You entered: " + number);
}
Output:
This code prompts the user to enter a number repeatedly and
prints the entered value. The loop continues indefinitely until manually
interrupted by terminating the program.
The Java while loop provides a very interesting way for
executing code again and again based on a given condition. By understanding its
syntax, working principle, and practical use cases, you can use the power of
the while loop to solve many programming challenges.