Site icon TestingDocs.com

Learn Java Loops

Overview

In this post, we will discuss loops in Java Programs. We will also look at some simple Java programs demonstrating the different loops in java.  Sample programs make learning easy.

Different Types of loops:

For Loop

This Loop is the most common of all types of loops. It is structured around a finite set of repetitions of code. So if you have a particular block of code that you would want to have run over and over again a specific number of times then we should use the For Loop. A common use of this loop is when you have a list of items that you need to iterate and process the items.

Code listing

package com.testingdocs.sample.programs;

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

}

 

Output of the program:

i value =0
i value =1
i value =2
i value =3
i value =4

 

While Loop

The While Loop is appropriate when we don’t know the specific number of times we want to loop beforehand, rather, we want to keep looping through your code until a certain condition is met. A while loop is a control structure that allows you to repeat a task a certain number of times.

syntax:
while(Boolean_expression)
{
//statements
}

package com.testingdocs.sample.programs;

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

}

 

Output of the program:

x value =1
x value =2
x value =3
x value =4
x value =5
x value =6
x value =7
x value =8
x value =9

 

do.. while Code Example

Do..while Loop will always execute the code in the block at least once. It is the difference between the normal while loop. The most common case of this loop is to display a menu to the user to choose and based on the user input, we may want to loop or exit the loop.

package com.testingdocs.sample.programs;

public class JavaDoWhileExample 
{
  public static void main(String[] args)
   {
    
    int y = 1 ;
          do
          { 
           System.out.println("y value = "+ y );
               y++;
          }
          
          while(y< 10) ; 
             
   }

}

 

Output of the program:

y value = 1
y value = 2
y value = 3
y value = 4
y value = 5
y value = 6
y value = 7
y value = 8
y value = 9

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version