Session 7 - Jump Statements
Session 7 - Jump Statements
THROUGH JAVA
UNIT - I
Overview
Jump statements in Java provide a way to alter the flow of control within a program. They are
used to "jump" to different parts of the code based on specific conditions or program logic.
These statements are crucial for managing the flow of execution, making decisions, and
handling exceptional cases. By understanding jump statements, programmers can write more
flexible and responsive code.
1. Skip Sections of Code: Jump statements can skip over certain parts of code, enabling
conditional execution and reducing redundancy.
2. Exit Loops or Methods: They can terminate loops or methods prematurely, based on
specific conditions, which is useful for optimizing performance and handling exceptions.
3. Repeat Sections of Code: Jump statements can facilitate repeated execution of certain
code blocks, particularly within loops and control structures.
Key Concepts
1. Control Flow: Jump statements modify the default sequential flow of control in a
program. They can direct the program to move forward, backward, or to specific
locations based on conditions.
2. Conditional Execution: By using jump statements, programmers can control the
execution path of a program, deciding which sections of code to execute based on
runtime conditions.
3. Code Optimization: Jump statements help in optimizing code by reducing unnecessary
computations and improving readability by handling exceptions or terminating loops
early.
1. break Statement:
2. continue Statement:
● Purpose: Skips the current iteration of the loop and proceeds with the next
iteration. It transfers control to the loop’s update statement.
● Usage: Used to skip the rest of the code inside the current loop iteration and
proceed with the next iteration, typically based on certain conditions.
3. return Statement:
● Purpose: Exits from the current method and optionally returns a value. It
transfers control back to the calling method or context.
● Usage: Used to terminate a method execution and return a value (for non-void
methods) or simply exit the method (for void methods).
goto Statement:
● Purpose: Java does not support the goto statement as it is considered to make
code difficult to understand and maintain. The goto statement was part of early
versions of Java but is reserved and not used in modern Java programming.
● Usage: It is included here for completeness, but its use is discouraged and not
applicable in current Java practices.
Usage Scenarios
1. Loop Control: Jump statements are often used within loops to control iteration, exit
loops early, or skip certain iterations. They help manage loop execution and improve
efficiency.
2. Exception Handling: They can be used to handle exceptional cases by jumping to error
handling code or terminating a method when an error occurs.
3. Program Termination: Jump statements can terminate methods or exit from blocks of
code based on specific conditions, allowing for more flexible and dynamic control flow.
Best Practices
1. Avoid Overuse: While jump statements are powerful, overusing them can make code
harder to understand and maintain. Use them judiciously to avoid creating complex and
confusing control flow.
2. Use in Context: Apply jump statements in appropriate scenarios, such as error
handling, loop control, or conditional execution, to enhance code clarity and functionality.
3. Consider Alternatives: In some cases, structured control statements like loops and
conditionals may provide a clearer and more maintainable approach than jump
statements. Evaluate the best approach based on the specific requirements of the code.
Jump statements are essential tools in Java for managing the flow of execution within a
program. They allow for conditional and unconditional jumps to different parts of code,
facilitating flexible control flow and efficient code execution. Understanding when and how to
use jump statements effectively is crucial for writing robust and maintainable Java programs.
2. Break Statement
Syntax
The syntax for the break statement is straightforward:
break;
When encountered, the break statement immediately exits the nearest enclosing loop or
switch block, bypassing any remaining iterations or cases.
Usage
1. Breaking Out of Loops: The break statement is commonly used to terminate loops
(for, while, do-while) based on a specific condition. This is useful when you want to
exit the loop early before the loop condition becomes false.
Examples
1. Breaking Out of a for Loop
0
1
2
3
4
In this example, the loop terminates when i equals 5, so only numbers from 0 to 4 are printed.
0
1
2
In this example, the loop exits when i equals 3, so only numbers from 0 to 2 are printed.
Two
Here, the break statement ensures that only the code for case 2 is executed, and control
exits the switch statement afterward.
Key Characteristics
1. Control Flow: The break statement provides a way to control the flow of execution by
exiting a loop or switch block early, based on a condition.
2. Termination of Nested Loops: When used inside nested loops, the break statement
only terminates the innermost loop containing it. To break out of multiple nested loops,
you would need additional logic, such as using a labeled break statement (though this
is less common).
3. Scope of Influence: The break statement affects only the loop or switch block in
which it is contained. It does not exit from outer blocks or methods.
2. Avoid Deep Nesting: If break statements are used extensively within deeply nested
loops or switch statements, consider refactoring the code to simplify the logic and
enhance readability.
Conclusion
The break statement is a fundamental control flow tool in Java that allows for early termination
of loops and switch statements. By using break, you can manage the flow of your program
more effectively, making it easier to handle specific conditions and enhance code readability.
Understanding when and how to use break appropriately is essential for writing clear and
efficient Java code.
Do It Yourself
1. Create a program that prompts the user to enter numbers repeatedly until they input a
number greater than 100. Use break to exit the loop when the condition is met.
2. Write a program that counts and prints numbers from 1 to 50 but stops and exits the loop
if the count reaches 20 using break.
3. Write a program with a switch statement that displays a menu with options to "Add a
Book", "Remove a Book", "List All Books", and "Exit". Ensure that each menu option is
handled correctly and use break to prevent fall-through. Print a message for each
selected option and exit the program when "Exit" is chosen.
Quiz
1. What does the break statement do in a for loop?
B) Exits the loop and transfers control to the statement immediately following the loop
Answer: B. Exits the loop and transfers control to the statement immediately following
the loop
2. Which of the following correctly uses the break statement in a switch case?
B) The program falls through to the next case and executes its statements
Answer: B. The program falls through to the next case and executes its statements
4. How does the break statement affect nested loops?
3. Continue Statement
How It Works
1. Within a for Loop:
● The remaining statements in the loop body are skipped when the continue
statement is encountered.
● The control then re-evaluates the loop condition for the next iteration.
int i = 0;
while (i < numbers.length) {
if (numbers[i] < 0) {
i++;
continue; // Skip negative numbers
}
System.out.println(numbers[i]); // Print positive numbers
i++;
}
}
}
Explanation:
int i = 0;
do {
if (numbers[i] % 20 == 0) {
i++;
continue; // Skip numbers that are multiples of 20
}
System.out.println(numbers[i]); // Print other numbers
i++;
} while (i < numbers.length);
}
}
Explanation:
Key Characteristics
1. Control Flow: The continue statement alters the flow of control within a loop, allowing
specific iterations to be skipped based on a condition.
2. Loop Specific: It affects only the loop in which it is present. If used within nested loops,
it only impacts the innermost loop.
3. No Exit: Unlike the break statement, which exits the loop entirely, the continue
statement only skips the current iteration and continues looping.
Best Practices
1. Clarity: Use the continue statement judiciously to enhance code readability and
clarity. Overusing it can make the code harder to follow.
2. Avoid Infinite Loops: Ensure that the continue statement does not inadvertently
cause an infinite loop by skipping necessary operations that affect the loop’s termination.
The continue statement is a valuable tool for controlling the flow of loops in Java. By allowing
the program to skip specific iterations and proceed with the next one, it helps manage loop
behavior effectively. Understanding its application and impact on loop execution enables
programmers to write cleaner and more efficient code.
Do It Yourself
1. Write a program to print all even numbers between 1 and 100 using a continue
statement.
2. Write a Java program that prints all numbers from 1 to 50, but skips any number that is a
multiple of 5. Use the continue statement to achieve this.
3. Write a Java program that prints even numbers from 1 to 30, but skips numbers that are
divisible by both 2 and 3. Use the continue statement to skip these numbers.
Quiz
Answer: b) To skip the current iteration and proceed to the next iteration
Answer: b) The current iteration is skipped, and the loop moves to the next iteration
Answer: a) 5
Answer: b) 2 4 8 10
4. return Statement
Example:
Example:
Example:
2. Incompatible Return Types: Ensure the return value's type matches the method's
declared return type. For example, a method declared to return int must not return a
String.
3. Unreachable Code: Avoid placing code after a return statement in a method, as it will
be unreachable and may cause warnings or errors.
4. Using return for Control Flow: Use return judiciously to control method flow.
Overuse of return statements, especially in deeply nested conditional statements, can
make code harder to read and maintain.
Do It Yourself
Quiz
Answer: b
2. Which of the following method signatures would be correct for a method that uses
return a + b;?
- a) public static void add(int a, int b)
- b) public static int add(int a, int b)
- c) public static boolean add(int a, int b)
- d) public static String add(int a, int b)
Answer: b
3. What will be the output if a method with the following signature public static
int getValue() contains only a return; statement?
- a) Compilation error
- b) 0
- c) null
- d) No output, the program runs successfully
Answer: a
Answer: b
5. Which of the following statements about the return keyword is NOT true?
Answer: a
References
Break and continue in Java - #3.5 Java Tutorial | Break and Continue
End of Session - 7