BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

While loop in Java with examples

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

In this tutorial, you will learn while loop in java with the help of examples. Similar to for loop, the while loop is used to execute a set of statements repeatedly until the specified condition returns false.

Syntax of while loop

while(condition)
{
   statement(s); //block of code
}

The block of code inside the body (content inside curly braces) of while loop executes repeatedly until the condition returns false.

Java while loop flowchart

In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute. When condition returns false, the control comes out of loop and jumps to the next statement after while loop.

Note: This block of code, generally contains increment or decrement statements to modify the variable used in the condition. This is why after each iteration of while loop, condition is checked again. If the condition returns true, the block of code executes again else the loop ends. This way we can end the execution of while loop otherwise the loop would execute indefinitely.

while loop java

Simple while loop example

This is a simple java program to demonstrate the use of while loop. In this program, we are printing the integer number in reverse order starting from 10 (as i is initialized as 10). Inside the body of while loop, we are decrementing the value of i using i--. So on every next iteration of while loop, the value of i is less by 1, the loop checks whether the value of i >1, if yes it executes the codes else the loop ends. At the very last iteration of while loop, the value of i is 1, loop checks the condition and it returns false as i<1 so the print didn’t execute for i=1 and the loop ended.

class WhileLoopExample {
    public static void main(String args[]){
         int i=10;
         while(i>1){
              System.out.println(i);
              i--;
         }
    }
}

Output:

10
9
8
7
6
5
4
3
2

Infinite while loop

In this example, we are demonstrating the infinite while loop. A loop is called infinite loop, if it never ends which means the condition specified by the loop never returns false.

In the following example, the condition is i>1, which never returns false as the initial value of i is 10 and at every iteration of loop, the value of i is increased using i++.

class WhileLoopExample2 {
    public static void main(String args[]){
         int i=10;
         while(i>1)
         {
             System.out.println(i);
              i++;
         }
    }
}

Here is another example of infinite while loop. In the following code, the true boolean value is provided in place of the condition, this will make the loop to run indefinitely.

class JavaExample {
  public static void main(String args[]){
    int i=10;
    while(true)
    {
      System.out.println(i);
      i++;
    }
  }
}

Example: Iterating an array using while loop

In the following example, we are iterating an array and printing the elements of the given array using while loop.

class WhileLoopExample3 {
    public static void main(String args[]){
         int arr[]={2,11,45,9};
         //i starts with 0 as array index starts with 0 too
         int i=0;
         while(i<4){
              System.out.println(arr[i]);
              i++;
         }
    }
}

Output:

2
11
45
9

Explanation:
First iteration of loop: value of i is 0, so the value of arr[0] is printed, arr[0] represents the first element of the array arr.
Second iteration: value of i is 1, second element of the array represented by arr[1] is printed.
Third iteration: value of i is 2, third element of the array represented by arr[2] is printed.
Fourth iteration: value of i is 3, fourth element of the array represented by arr[3] is printed.
After fourth iteration: value of i is 4, the condition i<4 returns false so the loop ends and the code inside body of while loop doesn’t execute.

Practice the following java programs related to while loop:

    • Java Program to display Fibonacci Series using while loop
    • Java Program to find factorial using while loop
    • Java Program to print hollow square star pattern using while loop
    • Java Program to print spy number using while loop
❮ PreviousNext ❯

Top Related Articles:

  1. How to Compile and Run your First Java Program
  2. Java Scanner class with examples
  3. Java Integer byteValue() Method
  4. Constructor Overloading in Java with examples
  5. Daemon thread in Java with example

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Anas says

    October 2, 2015 at 11:21 AM

    Hi, is it possible to these tutorials in pdf format?

    Reply
  2. titash says

    February 25, 2016 at 5:38 PM

    Hey,
    the notes were really helpful but i couldn’t understand the last example .Can anyone help me please?

    Reply
    • Dhiraj says

      April 1, 2016 at 1:22 PM

      please mention the point which you can’t understand

      Reply
    • PrashanthChinta says

      November 4, 2016 at 1:27 PM

      First of all…..
      The initialization done with i=0
      Then goto while loop and check the condition i<4(i=0)
      It is true goto the loop body execute the looping statement i.e., args[0]
      Then increment the i value by 1
      After incrementing again check the while loop condition …….
      ……
      Until the condition is false.
      It prints given o/p
      ….thats all

      Reply
  3. kumar says

    July 4, 2016 at 1:14 AM

    i would like to print all the tables with while loop
    for example i want the output as :
    1*1=1
    1*2=2
    ………….
    2*1=2
    2*2=4
    …………..
    3*1=3
    3*2=6
    …..
    up untill 10th table

    Can someone help me to write the code for this.
    Thank you

    Reply
    • imraan says

      August 11, 2016 at 1:30 PM

      public class Tables2 {
      public static void main(String[] args) {
      int num=3;
      int i=1;
      while(i<=10){
      System.out.println("Tables 2: " +num*i);
      i++;
      }
      }

      }

      Reply
  4. pandi says

    August 7, 2016 at 2:31 PM

    hi , I have small doudt when use for loop and when use while loop
    and what is the different between for loop and while loop

    Reply
    • Iysvariya S says

      September 7, 2016 at 2:22 PM

      In for loop if the condition is true, block of statement executes first
      ——————
      means change reflects after the completion of first iteration

      In while loop if the condition is true and if it finds the increment/decrement statement in first line inside the block then it process the increment/decrement operation first and prints the output accordingly
      ——————
      means changes reflects in first iteration itself else if the increment/decrement statement is not in first line then it is same as ‘for’ loop.
      Please find the example below,
      Example for loop:
      class Forlooparrayexample {
      public static void main(String args[]){
      int a[]={1,2,3,4};
      for(int i=0;i<4;++i)
      {
      System.out.println(a[i]);
      }
      }
      }
      output:
      1
      2
      3
      4

      Example while loop:
      class Whilelooparray{
      public static void main(String[] args)
      {
      int a=0;
      int []i=new int []{1,2,3,4};
      while(a<3)
      {
      ++a;
      System.out.println(i[a]);
      }
      }
      }
      output:
      2
      3
      4

      Reply
  5. marwan says

    February 6, 2017 at 5:48 AM

    Write a method with a while loop to prints 1 through
    n in square brackets. For example, if n = 6 print
    ! ![1] [2] [3] [4] [5] [6]!

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap