Jul 18, 2014

While and Do While Loop In Java

While Loop

While Loop Is A Control Flow Statement That Allows Code To Be Executed Repeatedly Based On A Given Boolean Condition. The While Loop Can Be Thought Of As A Repeating If Statement.While Loop Syntax Looks Like Below.
 
while ( condition ) {
     //Codes You Want To Execute After Condition Is True

}

We Have To Write "while" In Lowercase.The Condition We Want To Write Goes Inside The Round Brackets. We Can Write The Code That We Want To Execute Inside The Curly Brackets.Make Sure You Have Change The Condition Varible Value In Side The Curly Brackets.Otherwise You Will End Up With A Infinite Loop.

Following Example Shows How To Use While Loop In Java.

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

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


OutPut

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


Do While Loop

Do While Loop Is Related To While Loop.The Main Difference Between While Loop and Do While Is, In Do While Loop, Loop Will Run At Least Once, Even Without Condition Is False.In Do While Loop, While Is In Bottom and Do Is At The Top.We Have To Write The Codes That We Want To Execute Inside The Curly Brackets That Are With The Do Loop.Do While Loop Syntax Looks Like Below.


do{
     //Codes You Want To Execute After Condition Is True

}
 while ( condition ); 


Following Example Shows How To Use Do While Loop In Java.

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

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


OutPut

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


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...