While-loop: Used to execute a block of instructions repeatedly as long as the given condition is valid.
Syntax:
while (condition)
{
Logic….
}
Flow-Chart:
The code executes infinite times as condition always true:
class Test
{
public static void main(String[] args)
{
while(true)
{
System.out.println("Never stops");
}
}
}
Compiler raises error when we try define unreachable statements:
class Test
{
public static void main(String[] args)
{
while(true)
{
System.out.println("Never stops");
}
System.out.println("Unable to reach"); // Error :
}
}
Another example: Directly we cannot specify the boolean type to execute loops
class Test
{
public static void main(String[] args)
{
while(false)
{ // Error :
System.out.println("Unable to reach");
}
}
}
We can specify the condition (boolean value) indirectly with variables to avoid compiler checking:
class Test
{
public static void main(String[] args)
{
boolean val = false ;
while(val)
{
System.out.println("Unable to reach");
}
System.out.println("Ends here");
}
}
Print 1 to 10 using while loop:
class Test
{
public static void main(String[] args)
{
int i=1 ;
while(i<=10)
{
System.out.println("i value : " + i);
++i ;
}
}
}
Print 10 to 1 using while loop:
class Loops
{
public static void main(String[] args)
{
int i=10;
while(i>=1)
{
System.out.println("i val : " + i);
--i;
}
}
}
Even numbers from 1 to 10:
class Test
{
public static void main(String[] args)
{
int i=1 ;
while(i <= 10)
{
if(i%2==0){
System.out.println("Val : " + i);
}
++i;
}
}
}