This is the last control statements that i’m writing about. This statements let’s the program to jump to other parts of the program. The are three jum statements in java:

  • break
  • continue
  • return

break

break can be used to terminate a switch statement. Every time a case match the condition of the switch statement, the break terminate the switch and let the program procede ton the next part of the code.

Break can be used also to exit from a loop. let’s take an example:

for(x = 0; x < 20; x++)

{

if(x == 10) break;

System.out.println(x);

}

 

In this example while the loop goes an if statement check if the x is equal to 10 and in that case there is the break that let the program exit from the loop, so the result of this program will print onli the number from 0 to 9.

The break can be used in any loops. In the nested loopsthe break wil exit only from the innermost loops.

 

There is another way to use break, with the labels. Let’s say we have multiple nested loops and at one point we want to break not to the innermost loop but to anoter. Well, you can do it using labels:

first for(x = 0; x < 10; x++)
{
   second for(y = 0; y < 10; y++)
   {
      second for(y = 0; y < 10; y++)
      {
         break first;
      }
   }
}

 

In this case the break will stop the first loop instead of the tird.

 

Continue

The continue skip one or more iteration in a loop:

for(x = 0; x < 10; x++)
{
   if(x == 5) continue;
   System.out.println(x);
}

In this example when x is equal to 5 the control jump to the next iteration without print the number 5.

 

return

Return is used to pass the control to the caller of method.

Categories: Java

Leave a Reply

%d bloggers like this: