Loops in Java and Types of loops in Java

Loops in Java:

In Java, loops are used to execute a set of statements repeatedly until the given condition is satisfied.




In loops sequence of statements to be executed inside the curly braces (“{}”) is known as the loop body. Every execution of the loop body condition is checked and if the condition is true loop body executes again. When condition checked to be False then loop body will not to be executed and come out of the loop and execute the remaining part of the program.

Types of the Loops in Java language: 

There are three types of loops in Java language. They are:
1) while loop.
2) do-while loop.
3) for loop.

Read: Java For loop

While loop: While is a conditional control statement and it repeats a statement (or) block while its controlling is True. 

Syntax of While loop:


While Loop syntax:
while(condition)
{
  //body of the loop (statements)//

}

Explanation of the above diagram: In the while loop, the first condition is checked. If the condition is True, the code inside the body (means inside the parenthesis) will be executed. Again the loop executes until the condition becomes False when the condition becomes false exists from while loop.

Example of while program:

Java While loop program:
class WhileExample
{
 public static void main(String[] args)
 { 
  int i = 1;
    while( i < 5)
    {
     System.out.println("i = " + i);
     i++;
    }
 }

}
Output:
i = 1
i = 2
i = 3

i = 4
Explanation:
1) The first variable of type integer is declared and initialized to “1”.
2) While loop condition is checked ( 1 < 5) condition is true. So the value of “i” is printed.
3) Then the value is incremented (i++) it becomes i = 2. If we did not use any increment (or) decrement operator then while loop will be executed continuously with value i = 1. So we used the increment operator to satisfy the condition. 
4) The cycle continues until “i” becomes “5”. When “i” becomes “5” condition becomes fails. Control jumps out of the while loop.

Do-while: The do-while loop first executes the body of the loop and then the condition statement executes. If the expression is true, the loop repeat or else the loop terminates. There is a semicolon at the end of while() in do.

 Syntax of Do - while loop:

Java Do- While loop Syntax:
do
{
  //body of the loop//
}

while(condition);
Example of Do-while program:

Java Do- While loop program:
class DoWhileExample
{
 public static void main(String[] args)
 { 
  int i = 1;
    do
    {
     System.out.println("i = " + i);
     i++;
    }
   while( i < 5);
 }
}
Output:
i = 1
i = 2
i = 3

i = 4
Share:

Our Services

Search This Blog

  • ()
Powered by Blogger.

TikTok Sign Up and Account Registration in detail

TikTok Sign Up and Account Registration  The steps to create an account on Tik Tok application for Android and ios. Download and introd...

Blog Archive