TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: While Loop in Java
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Java Flow ControlJava Tutorials

While Loop in Java

Last updated: Sep 04, 2023 9:56 pm
By Meenakshi Agarwal
Share
4 Min Read
Java While Loop Tutorial
Java While Loop with Examples
SHARE

This tutorial will guide you on how to use while loop in Java programs, perform repetitive tasks, and iterate through the elements of a collection or array.

Contents
SyntaxExampleFlowchartGenerate first N whole numbersCount backward from a given numberIterate through an array/collection

The while loop is a core Java programming construct used to perform repetitive tasks. We’ll now see how seamlessly you can use it in programs.

Java While Loop Tutorial

The tutorial has the following sections to help you learn quickly.

Basics of while loop in Java

A while loop is an entry-controlled loop statement that allows the code to execute if and only if it passes through the entry condition. You can assume it as a chain of repeating if expression.

Syntax

The while loop places the condition at the entry gate.

while (boolean expression)
{
    statement(s);
}
  • The while loop in Java begins executing the code block only after the conditional expression returns true. That is why we call it a pre-condition loop.
  • If the pre-condition evaluates to true, then the inside block gets executed. Usually, the conditional statement uses a dynamic counter which gets updated in every iteration.
  • Whenever the test condition turns false, the loop ends the cycle which indicates the closing of its life cycle.

Also Read: Do-While Loop in Java

Example

Check this simple example of the while loop.

public class SimpleWhile {

   public static void main(String args[]){
        int iter = 0;
        while (iter <= 10)
        {
            System.out.print(iter + " ");
            iter++;
        }
   }
}

The above loop will run 11 times printing numbers from 0 – 10.

Flowchart

The Java while loop flow chart will help you visualize it:

Java while loop flowchart

While loop examples

You can use a while loop in Java programs for many purposes. Below are some samples to demonstrate it.

Generate first N whole numbers

public class WhileLoop {
    public static void main(String args[]) {
        int n = 0;
        int N = 5;
        while ( n <= N )
        {
            System.out.print(n + " ");
            n++; // Incrementing n by 1 in each iteration
        }
    }
}

Instead of writing the print statement for N times, we made the while loop in this Java program resolve it. Here ‘n’ is the loop control variable and N has a fixed value.

The output is as follows:

0 1 2 3 4 5

Count backward from a given number

public class WhileLoop {
    public static void main(String args[]) {
        int N = 5;
        while ( N >= 0 )
        {
            System.out.print(N + " ");
            N--; // Decrementing N by 1 in each iteration
        }
    }
}

The result is as follows:

5 4 3 2 1 0

You can see that the while loop is letting us manipulate the test condition and update the counter to produce different outputs.

Iterate through an array/collection

public class WhileLoop 
{ 
    public static void main(String args[]) {
         char char_arr[] = {'a', 'b', 'c', 'd'};
         // array index begins with 0
         int iter = 0;
         while( iter < char_arr.length ){
              System.out.print(char_arr[iter] + " ");
              iter++;
         }
    }
}

Test run:

a b c d

Please note that if you replace the array type in the above example from integer to char, then while loop will print the ASCII values of each char.

97 98 99 100

Must Read – Java For Loop Statement

You Might Also Like

A Simple Guide to Exception Handling in Java

Difference Between Spring and Spring Boot

How to Use Java String Format with Examples

Java IRC Bot with Sample Code

Generate Random Number in Java – 10 Ways

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Java Switch Case with Examples Switch-Case in Java
Next Article Java Do While Loop Tutorial Do…While Loop in Java

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x