Jul 18, 2014

For Loop and Enhanced For Loop In Java

For Loop

For Loop Allows Code To Be Repeatedly Executed. A For Loop Is Classified As An Iteration Statement. A For Loop Can Be Use, When We Know How Many Times A Code Is To Be Repeated. For Loop Syntax Looks Like Below.

for(initialization; Boolean_expression; update)
{
   //Code We Want To Run Repeatedly 
}


Inside The Brackets Of The For
 Loop You Have To Define A Variable & Initialized It To A Value.Then Put A Semi Colon & Write The Boolean Condition To Run The For Loop. After That Put Another Semi Colon & Write The Update Statement For The For Condition Variable.

Following Example Shows How To Use While Loop In Java.

class EasyCodeStuff {
   public static void main(String args[]){

      for(int MyCount = 1; MyCount < 5; MyCount++){
         System.out.print("My Count Is : ");
         System.out.println(MyCount);
      }
   }


OutPut

My Count Is : 1
My Count Is : 2
My Count Is : 3
My Count Is :
 

Enhanced For Loop 

Enhanced For Loops Also Like For Loop. Enhanced For Loops Mainly Used With Arrays. Enhanced For Loop Syntax Looks Like Below.


for(declaration : expression)
{
   //Code We Want To Run Repeatedly  
}

In Enhanced For Loops Declared Variable Type Must Be Compatible With The Array That We Are Going To Use In The Enhanced For Loop.For Example If We Have A Integer Array We Have To Use The Declaration Variable As Integer Too. In The Expression You Have To Give The Array. 
Following Example Shows How To Use While Loop In Java.

class EasyCodeStuff {
   public static void main(String args[]){

               int [] MyNumbers = {1,2,3,4,5};
      for(int MyCount : MyNumbers){
         System.out.print("My Count Is : ");
         System.out.println(MyCount); 
      }
   }


OutPut

My Count Is : 1
My Count Is : 2
My Count Is : 3
My Count Is : 4  
My Count Is : 5  

No comments:

JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...