JAVA

Java Jumping Statement


What is jumping statement?

  • Jumping statements are used to alter the flow of control in a program by transferring the execution to a different part of the code.
  • Java provides three main types of jumping statements

                1. break

               2. continue

               3. return 

Note: These statements change the normal execution sequence of a program.

 

1. break:  It is used to terminate the loop or switch statement.

Syntax

break;

Note:  When encountered inside a loop (such as for, while, or do-while) or a switch statement, the "break" statement exits the loop or switch, transferring the control to the statement immediately following the loop or switch.

 

Example

public class BreakStatement {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {    // Loop to print numbers from 1 to 5
            if (i == 3) {    // If i reaches 3, break the loop
                break;
            }
            System.out.println(i);
        }
    }
}

Output:

1
2

 

2.  continue: It statement is used in loops to skip the remaining code within the loop for the current iteration and move on to the next iteration of the loop.

 

Syntax

continue;

 

Example

public class BreakStatement {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {    // Loop to print numbers from 1 to 5
            if (i == 3) {    // If i is 3, skip printing and continue to the next iteration
                continue;
            }
            System.out.println(i);
        }
    }
}

 

Output:

1
2
4
5

 

3. return: It is used to explicitly exit a method and return a value (if the method has a return type other than "void"). It terminates the execution of a method and optionally passes back a value to the calling code.

 

Syntax

public int add(int a, int b) {
    return a + b; // returns the sum of a and b
}

 

Example

public class ReturnExample {
    public int add(int a, int b) {
    	return a + b; // returns the sum of a and b
	}

    // Main method - entry point of the program
    public static void main(String[] args) {
        ReturnExample obj= new ReturnExample(); // Creating an instance of ReturnExample
        int result = obj.add(5, 3); // Calling the add method with arguments 5 and 3
        System.out.println("Sum: " + result); // Printing the result of the addition
    }
}

 

Output:

Sum: 8