While-Loop in Java

by Jasleen Chhabra | Updated on 24 August 2024

Table of Contents (Click any Topic to view first)

  1.  Syntax of the While Loop:
  2. Example 1: Simple While Loop
  3. Example 2: Using While Loop for User Input
  4. Example 3: While Loop with Conditional Exit

Understanding the While-Loop in Java

In Java programming, the while loop provides a mechanism to execute a block of code repeatedly as long as a specified condition remains true. It's particularly useful when the number of iterations is unknown beforehand. Let's dive into the while loop in Java with detailed explanations and examples.

Syntax of the While Loop:

while (condition) {

    // Code to be executed

}

The while loop starts by evaluating the condition. If the condition is true, the loop body is executed. After each iteration, the condition is re-evaluated. The loop continues until the condition becomes false.

Example 1: Simple While Loop

public class SimpleWhileLoop {

    public static void main(String[] args) {

        int i = 1;

        while (i <= 5) {

            System.out.println("Iteration " + i);

            i++;

        }

    }

}

In this example, the while loop executes the block of code inside it as long as the value of i is less than or equal to 5. The loop iterates from 1 to 5, printing each iteration number.

Example 2: Using While Loop for User Input

 

import java.util.Scanner;

public class WhileLoopUserInput {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        String userInput;

        while (true) {

            System.out.print("Enter 'exit' to quit: ");

            userInput = scanner.nextLine();

            if (userInput.equals("exit")) {

                break; // Exit the loop if user inputs 'exit'

            }

            System.out.println("You entered: " + userInput);

        }

        scanner.close();

    }

}

This example demonstrates the use of a while loop for continuous user input. The loop prompts the user to enter text until they input "exit," at which point the loop terminates using a break statement.

Example 3: While Loop with Conditional Exit

public class ConditionalExitWhileLoop {

    public static void main(String[] args) {

        int i = 1;

        while (i <= 10) {

            System.out.println("Iteration " + i);

            if (i == 5) {

                break; // Exit the loop when i reaches 5

            }

            i++;

        }

    }

}

In this example, the loop iterates from 1 to 10, but it exits prematurely when the value of i becomes 5. This demonstrates how to use a conditional statement inside a while loop to control the loop's behavior.

Conclusion:

The while loop is a fundamental looping construct in Java that allows for iterative execution based on a condition. Whether iterating through a range of values, processing user input, or implementing conditional exits, the while loop provides flexibility and efficiency in program flow control.

 

 

 


 


FAQ

Any Questions?
Look Here.

Related Articles

Abstraction in Java

Binding in Java

Break Statement in Java

Classes & Objects in Java

Collections Framework in Java

Comments in Java

Continue Statement in Java

Control Statements in Java

Data Types in Java

Do While-Loop in Java

Encapsulation in Java

Exception Handling in Java

For-Loop In Java

Hello World Program in Java

If-else Statement in Java

Inheritance in Java

Introduction to Java

Java Database Connectivity (JDBC)

Java Development Tools and Frameworks

Java GUI (Graphical User Interface) Programming

Java I/O

Java Vs. C++

Methods and Constructors in Java

Multithreading in Java

Object Oriented Programming in Java

Operators in Java

Polymorphism in Java

Scanner Class in Java

Setting Up Java Environment

Static Keyword in Java

Super Keyword in Java

Switch Statement in Java

This Keyword in Java

Variables in Java