Java For Loop


For loop is an entry-controlled loop which consists of initialization, condition and increment/decrement.

The execution of the for loop statement is 3 parts:

  • Initialization
  • Test-condition
  • Increment or Decrement

1. Initialization:

Control variable is initialize one time at first. To declare and initialize any loop control variables.


2. Test-condition:

If the test condition is true, the body of the loop is executed otherwise the loop is terminated.


3. Increment or Decrement:

When the body of the loop is executed, the control is transferred back to the increment statement.


Syntax:-

for ( initialization ; test-condition ;increment)
{
    Body of the loop
} 

Example:-

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

Java For-each Loop

It is used to traverse array or collection in java. you don't need to use increment value in Java for-each Loop.

Syntax:-

for(Type var:array){   
   // Body of the loop
} 

Example:-

public class Foreach 
{  
	public static void main(String[] args) {  
        int arr[]={1,2,3,4,5};  
        //Printing array using for-each loop  
        for(int i:arr){  
            System.out.println(i);  
        }  
	}  
} 

Java Nested Loop

We can use Nested For loop as For loop inside another For loop. The inner loop is executed completely when the outer loop is executed one time. If the outer loop executed 3 times then the inner loop also executed 3 times.


Java Infinite Loop

In this, we can use double semicolons and it will be executed infinite times.




Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.