Jul 18, 2014

Break and Continue Keyword In Java

Break Keyword

"Break" Key Word Is Used For Stop The Entire Loop. The Break Keyword Must Be Used Inside A Loop Or In A Switch Statement.The Break Keyword Will Stop The Execution Of The Innermost Loop & It Will Move Outside The Loop To Execute The Rest Of The Codes.   

Syntax Is Simply "break;" Inside The Loop.

Following Example Shows How To Use Break Keyword Inside A Loop.

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

      int [] MyNumbers = {5,3,8,2,6,1,11};

      for(int MyCount : MyNumbers){
         if(MyCount == 6){
            break;
         }
         System.out.print("My Count Is : ");
         System.out.println(MyCount); 
      }
   }


OutPut

My Count Is : 5
My Count Is : 3
My Count Is : 8
My Count Is : 2  
  
In The Above Example Inside The For Loop We Have If Condition To Check "MyCount" Variable Value. If "MyCount" Variable Value Is 6, It Will Exit The Loop.



Continue Keyword

The "Continue" Keyword Can Be Used In Any Of The Loop Control Structures. It Causes The Loop To Immediately Jump To The Next Iteration Of The Loop.The Continue Statement Is Used To Jump To The Next Iteration Of A For Or While Loop, By Skipping The Rest Of The Code Lines In The Current Iteration.

The Different Between Continue and Break Statement Is If We Use Break Inside A For Loop It Will Exit From The For Loop.But If We Used A Continue Statement Inside For Loop It Will Go To The Update Statement Of The For Loop. 

If We Used  "continue;" Keyword Inside A While Loop Or Do While Loop It Move To The Boolean Expression Of The Loop.

Syntax Is Simply "continue;" Inside The Loop.
Following Example Shows How To Use Continue Keyword Inside A Loop.

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

      int [] MyNumbers = {5,3,8,2,6,1,11};

      for(int MyCount : MyNumbers){
         if(MyCount == 6){
            continue;
         }
         System.out.print("My Count Is : ");
         System.out.println(MyCount); 
      }
   }


OutPut

My Count Is : 5
My Count Is : 3
My Count Is : 8
My Count Is : 2My Count Is : 1
My Count Is : 11



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