[post-views]

In this lesson, you will learn
A while loop in Java is a control flow statement that allows code to be executed repeatedly based on a given boolean condition.
The loop will continue executing until the condition becomes false.
Syntax
while (condition) {
// Statements to be executed
}
Here, condition is a boolean expression that is evaluated before each iteration of the loop. If the condition is true, the statements inside the loop are executed.
This process repeats until the condition becomes false.
int counter = 0;
while (counter < 5) {
System.out.println("Counter is: " + counter);
counter++;
}
Output
Counter is: 0
Counter is: 1
Counter is: 2
Counter is: 3
Counter is: 4
This loop will print the value of counter five times (from 0 to 4) and then stop when counter reaches 5.
package ControlStatements;
public class SumOfNumbers {
public static void main(String[] args) {
int number = 1;
int sum = 0;
while (number <= 10) {
sum += number;
number++;
}
System.out.println("Sum is: " + sum);
}
}
Output
Sum is: 55
This loop calculates the sum of numbers from 1 to 10 and then prints it out.
package ControlStatements;
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = "";
while (!input.equals("exit")) {
System.out.println("Enter a string (type 'exit' to stop): ");
input = scanner.nextLine();
System.out.println("You entered: " + input);
}
scanner.close();
}
}
Output
Enter a string (type 'exit' to stop):
Learning while loop
You entered: Learning while loop
Enter a string (type 'exit' to stop):
stop
You entered: stop
Enter a string (type 'exit' to stop):
exit
You entered: exit
This loop reads strings from the user until the user types “exit”.
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.