• iconJava Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

While Loop

While:
'while' is a keyword in java language which is used to execute one block of statements several number of times based on the condition.
Syntax

while(condition)
{
    ...
    ...
}

In the above syntax if the condition is true the statements of while block is execute infinite times, if the condition is false while block terminated :



Key Points

Image
Display 1 to 10 Values Using While Loop


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


Output:
1
2
3
4
5
6
7
8
9
10

Display 10 to 1 Values Using While Loop


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


Output:
10
9
8
7
6
5
4
3
2
1

Nested For While In java


Nested While Loop :
One While loop within another While loop is knows as Nested While Loop Syntax

while(condition)
{
     while(condition)
    {
        ...
        ...
        
    }
...
..
}

In the above syntax :
Outer loop is Row
Inner loop is Column

***
***
***
***
***
***


class Main
{
public static void main(String args[])
{
int x=1,y;
while(x<=6)
{
y=1;
while(y<=3)
{
System.out.print("*");
y++;
}
System.out.println();
x++;
}
}
}


Output:
***
***
***
***
***
***

*
**
***
****
*****
******


class Main
{
public static void main(String args[])
{
int x=1,y;
while(x<=6)
{
y=1;
while(y<=x)
{
System.out.print("*");
y++;
}
System.out.println();
x++;
}
}
}


Output:
*
**
***
****
*****
******

******
*****
****
***
**
*


class Main
{
public static void main(String args[])
{
int x=1,y;
while(x<=6)
{
y=6;
while(y>=x)
{
System.out.print("*");
y--;
}
System.out.println();
x++;
}
}
}


Output:
******
*****
****
***
**
*