[go: up one dir, main page]

0% found this document useful (0 votes)
5 views20 pages

Session 7 - Jump Statements

Jump statements in Java, including break, continue, and return, are essential for altering the flow of control within programs. They allow for skipping code sections, exiting loops or methods, and repeating code execution based on specific conditions. Understanding and using these statements effectively enhances code flexibility, readability, and performance.

Uploaded by

pavankumarvoore3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views20 pages

Session 7 - Jump Statements

Jump statements in Java, including break, continue, and return, are essential for altering the flow of control within programs. They allow for skipping code sections, exiting loops or methods, and repeating code execution based on specific conditions. Understanding and using these statements effectively enhances code flexibility, readability, and performance.

Uploaded by

pavankumarvoore3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

OBJECT-ORIENTED PROGRAMMING

THROUGH JAVA

UNIT - I

Session 7 - Jump Statements

1. Introduction to Jump Statements

Introduction to Jump Statements

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.

Purpose of Jump Statements


Jump statements help manage the flow of execution by allowing the program to:

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.

Types of Jump Statements


In Java, jump statements include:

1. break Statement:

● Purpose: Exits the current loop or switch statement immediately. It terminates


the loop or switch block and transfers control to the statement following the loop
or switch.
● Usage: Commonly used to exit loops early or to break out of a switch statement
based on certain conditions.

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

The break Statement in Java


The break statement in Java is a control flow statement used to exit from a loop or a switch
statement prematurely. By using the break statement, you can terminate the execution of a
loop or switch case and transfer control to the statement immediately following the loop or
switch block.

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.

2. Exiting switch Statements: In switch statements, the break statement is used to


exit the switch block after executing a particular case. Without break, the program
continues executing the subsequent cases (a phenomenon known as "fall-through").

Examples
1. Breaking Out of a for Loop

public class BreakLoopExample {


public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exits the loop when i equals 5
}
System.out.println(i);
}
}
}

Output:

0
1
2
3
4

In this example, the loop terminates when i equals 5, so only numbers from 0 to 4 are printed.

2. Breaking Out of a while Loop

public class BreakWhileExample {


public static void main(String[] args) {
int i = 0;
while (i < 10) {
if (i == 3) {
break; // Exits the loop when i equals 3
}
System.out.println(i);
i++;
}
}
}

Output:

0
1
2

In this example, the loop exits when i equals 3, so only numbers from 0 to 2 are printed.

3. Using break in a switch Statement

public class BreakSwitchExample {


public static void main(String[] args) {
int number = 2;
switch (number) {
case 1:
System.out.println("One");
break; // Exits the switch block
case 2:
System.out.println("Two");
break; // Exits the switch block
case 3:
System.out.println("Three");
break; // Exits the switch block
default:
System.out.println("Default");
}
}
}

Output:

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.

Common Use Cases


1. Early Exit from Loops: Use the break statement to exit loops when a certain condition
is met, especially if continuing the loop would be redundant or unnecessary.

2. Control Flow in switch Statements: Use break to prevent fall-through in switch


statements, ensuring that only the code associated with the matched case is executed.
Best Practices
1. Use Sparingly: While break can simplify code, excessive use can make code harder to
read and maintain. Prefer using break only when necessary for clarity and control.

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.

3. Document Usage: Clearly document why a break statement is used, particularly in


complex loops or switch statements, to help other developers understand the intent
and logic.

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?

A) Exits the current iteration of the loop

B) Exits the loop and transfers control to the statement immediately following the loop

C) Continues with the next iteration of the loop

D) Repeats the current iteration of 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?

A) case 1: System.out.println("One"); break;

B) case 1: break; System.out.println("One");

C) case 1: System.out.println("One"); continue;

D) case 1: System.out.println("One"); return;

Answer: A. case 1: System.out.println("One"); break;

3. What happens if a break statement is not used in a switch case?

A) The program exits the switch block

B) The program falls through to the next case and executes its statements

C) The program repeats the current case

D) The program generates a compilation error

Answer: B. The program falls through to the next case and executes its statements
4. How does the break statement affect nested loops?

A) It breaks out of all nested loops

B) It breaks out of the outermost loop

C) It breaks out of only the innermost loop

D) It does not affect nested loops

Answer: C. It breaks out of only the innermost loop

5. In which of the following scenarios would you use a break statement?

A) To skip the current iteration of a loop

B) To continue executing the next iteration of a loop

C) To return a value from a method

D) To terminate a loop or switch block prematurely

Answer: D. To terminate a loop or switch block prematurely

3. Continue Statement

The continue Statement in Java


The continue statement in Java is a control flow statement used to skip the current iteration of
a loop and proceed to the next iteration. It can be used within for, while, and do-while
loops. This statement is helpful when certain conditions need to be avoided within a loop without
exiting the loop entirely.

Syntax of the continue Statement


The basic syntax of the continue statement is:
continue;

In a for loop, the continue statement will skip the remainder of the loop body and proceed to
the update statement before the next iteration. In while and do-while loops, it will skip the
remainder of the loop body and re-evaluate the condition for the next iteration.

How It Works
1. Within a for Loop:

● When the continue statement is encountered, the remaining statements in the


loop body are skipped for the current iteration.
● The control then moves to the update statement (increment or decrement) and
proceeds to the next iteration of the loop.

2. Within a while or do-while 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.

Example of continue in a for Loop


Here's an example that demonstrates the use of the continue statement in a for loop to print
all even numbers from 1 to 10:

public class ContinueForLoopExample {


public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) {
continue; // Skip odd numbers
}
System.out.println(i); // Print even numbers
}
}
}

Explanation:

- The if condition checks if the number is odd (i % 2 != 0).


- If the condition is true, the continue statement is executed, which skips the print
statement and continues with the next iteration of the loop.
- Only even numbers are printed as a result.
Example of continue in a while Loop
Here’s an example that demonstrates the use of the continue statement in a while loop to
skip negative numbers and print only positive numbers from an array:

public class ContinueWhileLoopExample {


public static void main(String[] args) {
int[] numbers = {-5, 3, -2, 7, 1, -4};

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:

● The if condition checks if the current number is negative.


● If the condition is true, the continue statement is executed, skipping the print
statement and continuing with the next iteration of the loop.
● Only positive numbers are printed.

Example of continue in a do-while Loop


Here’s an example that uses the continue statement in a do-while loop to skip certain
values:

public class ContinueDoWhileLoopExample {


public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25};

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:

● The if condition checks if the current number is a multiple of 20.


● If the condition is true, the continue statement is executed, which skips the print
statement and continues with the next iteration of the loop.
● Numbers that are not multiples of 20 are printed.

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.

Common Use Cases


1. Skipping Invalid Data: The continue statement is useful for skipping invalid or
unwanted data within a loop, such as filtering out certain values.
2. Avoiding Nested Conditions: It can reduce the need for nested if statements by
handling specific cases upfront and skipping the rest of the loop body.

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

1. What is the purpose of the continue statement in a loop?


a) To exit the loop immediately
b) To skip the current iteration and proceed to the next iteration
c) To terminate the program
d) To reset the loop counter

Answer: b) To skip the current iteration and proceed to the next iteration

2. What happens when a continue statement is executed inside a for loop?


a) The loop terminates
b) The current iteration is skipped, and the loop moves to the next iteration
c) The loop counter is reset to its initial value
d) The loop's condition is set to false

Answer: b) The current iteration is skipped, and the loop moves to the next iteration

3. Given the following code, how many numbers will be printed?


for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}

a) 5
b) 10
c) 0
d) 9

Answer: a) 5

4. In which of the following loops can the continue statement be used?


a) for loop
b) while loop
c) do-while loop
d) All of the above

Answer: d) All of the above

5. Consider the following code. What will be the output?


int[] numbers = {2, 4, 6, 8, 10};
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == 6) {
continue;
}
System.out.print(numbers[i] + " ");
}

a) 2 4 6 8 10
b) 2 4 8 10
c) 2 4 8
d) 4 8 10

Answer: b) 2 4 8 10

4. return Statement

The return Statement in Java


The return statement is a fundamental component in Java used to exit from a method and
optionally return a value to the method caller. It is essential for controlling the flow of execution
in methods and functions. Understanding how to use the return statement effectively is crucial
for writing clear and maintainable Java programs.

Purpose of the return Statement


The return statement serves two main purposes:

1. Terminate Method Execution: It immediately terminates the execution of the method in


which it is present.
2. Return a Value: If a method is declared to return a value (non-void methods), the
return statement is used to pass a value back to the caller.

Syntax of the return Statement


The basic syntax of the return statement in Java is:

return; // Used in methods with 'void' return type.



return expression; // Used in methods with non-void return types.

● return;: This form is used in methods that do not return a value (i.e., methods with the
void return type). It simply exits the method.
● return expression;: This form is used in methods that return a value. The
expression must match the return type specified in the method's declaration.

Using return in void Methods


In methods with a void return type, the return statement is optional and is primarily used to
exit the method early before reaching the end.

Example:

public class ReturnExample {


public static void main(String[] args) {
printMessage(5);
printMessage(-1);
}

public static void printMessage(int n) {


if (n < 0) {
System.out.println("Invalid number. Exiting method.");
return; // Early exit if n is negative
}
System.out.println("The number is: " + n);
}
}

In this example, if the input n is negative, the method exits early using return, and the rest of
the code is not executed.

Using return in Non-void Methods


In methods that are expected to return a value (non-void methods), the return statement
must be followed by an expression that matches the return type declared in the method
signature.

Example:

public class SumExample {


public static void main(String[] args) {
int result = sum(5, 10);
System.out.println("The sum is: " + result);
}

public static int sum(int a, int b) {


return a + b; // Returns the sum of a and b
}
}

In this example, the method sum(int a, int b) is declared to return an int. The
expression a + b evaluates to an integer value, which is then returned to the caller using the
return statement.

Multiple Return Statements


A method can have multiple return statements, but only one of them will execute during a
method call. This is often used in conditional structures to return different values based on
certain conditions.

Example:

public class MaxExample {


public static void main(String[] args) {
int max = findMax(8, 12);
System.out.println("The maximum value is: " + max);
}

public static int findMax(int a, int b) {


if (a > b) {
return a; // Returns a if a is greater than b
} else {
return b; // Returns b otherwise
}
}
}

return Statement in Recursive Methods


The return statement is commonly used in recursive methods to return the result of a
recursive computation back to the caller.

Example: Factorial Calculation Using Recursion

public class FactorialExample {


public static void main(String[] args) {
int result = factorial(5);
System.out.println("Factorial of 5 is: " + result);
}

public static int factorial(int n) {


if (n == 0) {
return 1; // Base case: factorial of 0 is 1
} else {
return n * factorial(n - 1); // Recursive call
}
}
}

In this example, the method factorial(int n) uses the return statement to return the
base case value or the result of a recursive computation.

Return Type and Method Signature


The type of the value returned by a method must match the return type specified in the
method's signature. If the types do not match, the compiler will generate an error.

Example of Incorrect Return Type:

public static int getNumber() {


return "Hello"; // Compilation error: incompatible types
}

The above code will not compile because the method getNumber() is declared to return an
int, but the return statement is trying to return a String.

Common Mistakes and Best Practices


1. Missing Return Statement: In non-void methods, ensure all code paths return a value.
If the compiler detects a path that does not return a value, it will generate an error.

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

1. What is the purpose of the return statement in a Java method?

- a) To print the method's output to the console


- b) To exit the method and optionally return a value to the caller
- c) To pause the method execution
- d) To start the method execution

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

4. In a recursive method, why is the return statement important?

- a) It pauses the method temporarily


- b) It ensures the recursive method stops calling itself
- c) It starts the recursion
- d) It is optional and has no significant use

Answer: b

5. Which of the following statements about the return keyword is NOT true?

- a) It can only be used in methods with a void return type.


- b) It can exit a method early.
- c) It can return a value to the method caller.
- d) It is essential for methods that are required to return a value.

Answer: a

References
Break and continue in Java - #3.5 Java Tutorial | Break and Continue

End of Session - 7

You might also like