Jump statements in Java

Rumman Ansari   Software Engineer   2024-08-19 04:02:12   26  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

In Java, jump statements allow you to control the flow of execution in a program by jumping to different parts of the code. There are four primary jump statements in Java:

  1. break Statement
  2. continue Statement
  3. return Statement
  4. goto Statement (Note: goto is not used in Java; it's reserved but not implemented.)

Here’s a brief overview of each jump statement:


1. break

The break statement is used to exit from a loop or switch statement prematurely. It immediately terminates the innermost loop or switch block.

Example:


for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break; // Exit the loop when i is 5
    }
    System.out.println(i);
}

Output:


0
1
2
3
4


2. continue

The continue statement is used to skip the current iteration of a loop and continue with the next iteration. It is typically used inside for, while, or do-while loops.

Example:


for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue; // Skip the rest of the loop body for even numbers
    }
    System.out.println(i);
}

Output:


1
3
5
7
9


3. return

The return statement is used to exit from a method and optionally return a value. If the method has a return type other than void, it must return a value of that type.

Example:


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

public static void main(String[] args) {
    MyClass obj = new MyClass();
    int result = obj.sum(5, 10);
    System.out.println(result);
}

Output:


15


4. goto (Not Used in Java)

The goto statement is reserved in Java but is not used. In Java, control flow is managed using other constructs like loops, conditionals, and methods, making goto unnecessary.


Summary

  • break: Exits from the loop or switch statement.
  • continue: Skips the current iteration and continues with the next iteration of the loop.
  • return: Exits from the method and optionally returns a value.
  • goto: Reserved keyword but not used in Java.

These jump statements help manage control flow and make the code more readable and efficient by handling special cases and simplifying complex conditions.