Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Working with While Loop in Java

[post-views]

 

 

 

In this lesson, you will learn

  • The while loop
  • Examples

 

The while loop

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.

 

Example 1: Basic Counter

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.

 

Example 2: Sum of Numbers

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.

Example 3: Reading User Input

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”.

 


End of the lesson….enjoy learning

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review