PREV NEXT
Java Control statements :
- The Java control statements inside a program are usually executed sequentially. Sometimes a programmer wants to break the normal flow and jump to another statement or execute a set of statements repeatedly.
- Control statements in java which breaks the normal sequential flow of the program are called control statements.
- Control statements in java enables decision making, looping and branching.
Decision making statements:
These statements decides the flow of the execution based on some conditions.
- If then
- If then else
- switch
Loops Control statement:
- Loop control statements change execution from its normal sequence.
- When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
Statements inside a loop are executed repeatedly provided with some condition which terminates the loop.
- for – For loop executes a set of statements repeatedly until a specified condition evaluates to false.
- while & do while – Do while loop is similar to that of the while loop except that the condition is evaluated at the end of the loop in do-while whereas in while loop, it is evaluated before entering into the loop.
Branching statements:
Branching statements are used to jump from the current executing loop.
- break – Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
Example For Break statement :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class breakTest { public static void main(String args[]) { for (int j = 0; j < 5; j++) { // come out of loop when i is 4. if (j == 4) break; System.out.println(j); } System.out.println("After loop"); } } |
1 2 3 4 5 6 |
0 1 2 3 4 After loop |
- continue – Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
Example for Continue statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class continueTest { public static void main(String args[]) { for (int j = 0; j < 10; j++) { // If the number is odd then bypass and continue with next value if (j%2 != 0) continue; // only even numbers will be printed System.out.print(j + " "); } } } |
1 |
0 2 4 6 8 |