while loop in java

In this post, we will read the while loop in java and java while loop example. As you can see the name of the loop is already says, the code will be executed repeatedly while the condition is true.
It is a part of Control statements. A while loop allows code to be executed repeatedly until a condition is satisfied. If the number of iterations is not fixed, it is recommended to use a while loop. It is also known as an entry control loop. In this article, we will discuss how we can use while loop java.

while(condition)
{
   // Body of while loop
}

Firstly, the condition will be evaluated:

  • If it returns true, then the body of the while loop will be executed. In the body of while loop the statements contain an update value for the variable being processed for the next iteration.
  • If it returns false, then the loop terminates which marks the end of its life cycle.

Flowchart of while loop Java

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

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

Java Infinitive while Loop: If the condition of while loop will never false. Then it’s an infinite while loop. Here, below is example of infinite while loop.
public class ExampleOfInfinitewhileLoop
 {  
	public static void main(String[] args)
	{  
	     int i = 1; 
	     while(i  > 0)
	     {
	    	System.out.println(i);
	    	i++;
	     }
	}  
}  
It is an infinite loop. Because this is because the condition is i > 0 which would always be true as we are incrementing the value of i inside while loop.
public class ExampleOfInfinitewhileLoop
 {  
	public static void main(String[] args)
	{   
	     while(true)
	     {
	    	System.out.println(i);
	     } 
	}  
}  
If we pass true in while loop condition. Then it will be an infinite loop.

1. Quiz, Read the below code and do answer.

public class ExampleOfwhileLoop
 {  
    public static void main(String[] args)
    {  
         int i = 0; 
         while(i < 5)
         {
            System.out.println(i);
            i++;
         }
    }  
}

Click on anyone to know the answer.

2. Quiz, Read the below code and do answer.

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

Click on anyone to know the answer.

3. Quiz, Read the below code and do answer.

public class ExampleOfwhileLoop
 {  
    public static void main(String[] args)
    {  
         while(true)
         {
            System.out.println("Hi");
         }
    }  
}

Click on anyone to know the answer.

Leave a Comment