Break and Continue in Java : Tutorial 6


04 Oct  

We have seen that we can have different types of loops in java using for, while , do etc.

You can also make use of labelling  of loops in Java for efficient and easy handling. You can name your loops in the following way:

loopname:

{ LOOP }

 

And then you can use ‘continue’ to switch back to that loop by calling its name.

You can use break if you want to stop an iteration process in a loop –say , you might have set the condition as i<100; but you can instruct the compiler to stop after i=10.

 

You will also see that the continue option is quite handy! Here is a code that makes use of it:

 

   1: public class NewClass{

   2:     public static void main (String arg []) {

   3:         loop1:

   4:             for (int i=1;i<10;i++)

   5:         {

   6:             System.out.println("  ");

   7:             for (int j=1; j<10; j++)

   8:             {

   9:                 System.out.println("J");

  10:  

  11:                  if (j == i)

  12:                     continue loop1;

  13:             }

  14:  

  15:         }

  16:  

  17:     }

  18: }

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

Tags: ,


TechBlog on Facebook

Leave a Reply