Day 16: Jump Statements
Jump Statements
These statements alter the normal flow of control by transferring execution.
1.break Statement
We saw this break already in switch statements. Actually it terminates the loop or switch statement immediately.
To exit out of any control statements we do it let's see 2 examples of sing it in switch and for loop.
Example of break in Switch:
break in Loops:
Used to exit a loop before its condition fails.
Output:
i = 1
i = 2
It gets terminated from the Loop when i=3
2. continue Statement
The continue statement is used to skip the current iteration of a loop and move to the next iteration. Just the current code with continue statement be skipped.
As discussed encountering continue the iteration will be skipped when i=3
Output:
i = 1
i = 2
i = 4
i = 5
3. return Statement
The return statement is used to exit from a method and optionally return a value to the caller of the method.
Example 1 (Void Method):
after return statement the code in the method becomes unreachable will not be executed.
This makes just Hello be printed in the output.
Did you notice object is not created to call the method. what makes it happen, It's all the Magic of the word Static. Let's explore it detailly tomorrow.
Control statement are a basic and simple topic. Understanding and using these statements effectively can improve the flow control and readability of Java programs. Let's Explore Static tomorrow.