Thursday, 14 July 2011

java jump statements

After writing about loops now i am going to write about jump statements. These are used within loops for unconditional jump. Jump statements are used to unconditionally transfer the program control to another part of the program. Java has three jump statements: break, continue, and return.

Java break Keyword
In Java programming, the break statement has two uses. First it terminates a statement sequence in a switch statement. Second, it can be used to exit a loop. After the break statement the control will go to the next block after the loop

public BreakDemo {

  public static void main(String[] args) {

    for(int i = 0; i < 10; i++) {
       if(i == 5) {
         System.out.println("Terminating the loop...");
       System.out.println("Still in the loop");

Java continue Keyword
Continue statement is used within the loops. After the continue the control will go to the beginning of the loop leaving the reminder section of the loop.

public class ContinueDemo{

public static void main(String[] args) {

for(int i = 0; i < 5; i++) {

if(i <= 2) {

// this line will be executed only when
// the value of i is greater than 2. If it
// is not then it will skip this code.
System.out.println(i + " is greater than 2");
3 is greater than 2
4 is greater than 2

Java return Keyword
Return statement simply returns a value from a method. That means that the execution control is returned back to the caller of the method. It is ideally the last statement that is executed in a method. no statements would be executed written after return statement.


public ReturnDemo{

  public static void main(String args[]) {

    boolean flag = true;

    System.out.println("The value of the flag has been set as true.");

    if(flag) return;

    System.out.println("This line will never be printed on the screen");


Post a Comment