Java Control Statement

Category: Java   Tags: Java, Java Basic, Java Control Statement

A control statement is used to proceed further based on some condition. For example, print "Even" if a number is even else print "Odd". A control statement can be categorised as:

  • Selection Statements
  • Iteration Statements
  • Jump Statements

Selection Statements

Java support two type of selection statements: if and switch

if

A Java if conditional statement has following syntax:

                            if (condition)
                                statement1;
                            else
                                statement2;
                        

Here, condition is any expression that returns a boolean value. statement1 and statement2 can be a single or multiple statements.

If condition is true then statement1 will be executed else statement2 will be executed. Here is a simple example:

BasicIfExample.java

                            public class BasicIfExample {

                                public static void main(String s[]) {
                                    int a = 500;
                                    int b = 200;

                                    if(a > b) {
                                        System.out.println("a is greater than b");
                                    } else {
                                        System.out.println("b is greater than a");
                                    }

                                    int c = 100;
                                    int d = 100;

                                    if(c == d) {
                                        System.out.println("c is equal to d");
                                    } else {
                                        System.out.println("c is not equal to d");
                                    }

                                    String s1 = "Hello";
                                    String s2 = "Hello";

                                    if(s1.equals(s2)) {
                                        System.out.println("s1 is same as s2");
                                    } else {
                                        System.out.println("s1 and s2 is differetnt");
                                    }
                                }
                            }
                        

Output of this Java program is:

                            a is greater than b
                            c is equal to d
                            s1 is same as s2
                          

if condition can have a method also:

BasicIfExample2.java

                            public class BasicIfExample2 {

                                public BasicIfExample2() {
                                    if(isEven(100)) {
                                        System.out.println("Even number");
                                    } else {
                                        System.out.println("Odd number");
                                    }
                                }

                                public static void main(String s[]) {
                                    new BasicIfExample2();
                                }

                                private boolean isEven(int n) {
                                    return n%2 == 0;
                                }
                            }
                        

Output of this Java program is:

                            Even number
                          

Nested ifs

Nested if consist another if statements:

NestedIf.java

                            public class NestedIf {

                                public static void main(String s[]) {
                                    int a = 100;
                                    int b = 200;
                                    int c = 300;

                                    if(a == 100) {
                                        if(b == 200) {
                                            if(c == 300) {
                                                System.out.println("I was inside nested if");
                                            }
                                        }
                                    }
                                }
                            }
                        

Output:

                            I was inside nested if
                          

if-else-if

It is a sequence of nested ifs. As soon as one of the if condition is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. It looks like this:

                            if (condition1)
                                statement1;
                            else if (condition2)
                                statement2;
                            else if (condition3)
                                statement3;
                            else
                                default statement
                        

default statement will be executed if none of the if condition is true.

NestedIf.java

                            public class NestedIf {

                                public static void main(String s[]) {
                                    int a = 200;

                                    if(a == 100) {
                                        System.out.println("a is 100");
                                    } else if(a == 200) {
                                        System.out.println("a is 200");
                                    } else if(a == 300) {
                                        System.out.println("a is 300");
                                    } else {
                                        System.out.println("a is unknown");
                                    }
                                }
                            }
                        

Output:

                            a is 200
                          

switch

A switch statement provides an easy way to dispatch execution to different parts of code based on the value of an expression. It is better alternative than using a large number of if-else-if statements. A Java switch statement syntax is as below:

                            switch (expression) {
                                case value1:
                                    statements;
                                    break;
                                case value2:
                                    statements;
                                    break;
                                ...
                                ...
                                case valueN:
                                    statements;
                                    break;
                                default:
                                    default statements;
                            }
                        

Here value of expression is compared with each of the value specified in the case statement. default statement is executed when none of the case statement is matched.

When break; statement is encountered, execution jump out to the first line of code that follow switch statement.

Prior to JDK 7, expression must be of type short, int, byte, char or an enumeration. Beginning with JDK 7, expression can be of type String. Here is an example:

SwitchDemo.java

                            public class SwitchDemo {

                                public static void main(String s[]) {
                                    int a = 10;
                                    switch(a) {
                                        case 5:
                                            System.out.println("a is 5");
                                            break;
                                        case 10:
                                            System.out.println("a is 10");
                                            break;
                                        case 15:
                                            System.out.println("a is 15");
                                            break;
                                        default:
                                            System.out.println("this is default");

                                    }
                                }
                            }
                        

Here a is 10 therefore case 10 will be executed.

Output:

                            a is 10
                          

The break statement is optional. If there is no break statement, execution will continue to next case. Here is an Java code example:

SwitchDemo1.java

                            public class SwitchDemo1 {

                                public static void main(String s[]) {
                                    int a = 3;
                                    switch(a) {
                                        case 1:
                                        case 2:
                                        case 3:
                                        case 4:
                                        case 5:
                                            System.out.println("a is between 1 to 5");
                                            break;
                                        case 10:
                                            System.out.println("a is 10");
                                            break;
                                        case 15:
                                            System.out.println("a is 15");
                                            break;
                                        default:
                                            System.out.println("this is default");

                                    }
                                }
                            }
                        

Output:

                                a is between 1 to 5
                              

Here, from case 1 to case 5 there is no break statement so execution flow till it find break in case 5.

Iteration Statements

This type of statement execute set of code repeatedly. Java support three type of iteration statements: for, while, and do-while.

for

A for statement has below syntax:

                            for(initialization; condition; increment) {
                                statement(s)
                            }
                        

  • initialization expression start the loop and is executed just once as loop start.
  • condition expression is used to terminate the loop as soon as it return false.
  • increment is called after each iteration.
Here is a simple Java example of for loop:

ForExample.java

                            public class ForExample {

                                public static void main(String s[]) {
                                    for(int i=0; i<=5; i++) {
                                        System.out.println("i = " + i);
                                    }
                                }
                            }
                        

Here, i is initialized to 0. In each iteration it is checked whether it is less than or equal to 5 using i<=5, if any of these condition is true loop will be terminated.

i++ is used increment value of i in each iteration.

So here is the output of previous program:

                                i = 0
                                i = 1
                                i = 2
                                i = 3
                                i = 4
                                i = 5
                              

while

A while loop has below syntax:

                            while(expression) {
                                statement(s)
                            }
                        

The while statement continually executes a block of statements while expression return true, once it is false, loop will be terminated. Here is an example:

WhileExample.java

                            public class WhileExample {

                                public static void main(String s[]) {
                                    int i = 0;
                                    while(i<=5) {
                                        System.out.println("i = " + i);
                                        i++;
                                    }
                                }
                            }
                        

Output:

                                i = 0
                                i = 1
                                i = 2
                                i = 3
                                i = 4
                                i = 5
                              

For-Each Loop

Beginning with JDK 5, another form of for loop was introduced called for-each loop. It iterate through a collection of objects, such as an array. It has below syntax:

                            for(type variable-name : collection) {
                                statement(s)
                            }
                        

With each iteration of the loop, the next element in the collection is retrieved and stored in variable-name. The loop repeats until all elements in the collection have been obtained.

ForEachExample.java

                            public class ForEachExample {

                                public static void main(String s[]) {
                                    int numbers[] = { 1, 2, 3, 4, 5};
                                    int sum = 0;
                                    for(int n: numbers) {
                                        System.out.println("n is: " + n);
                                        sum += n;
                                    }
                                    System.out.println("Total Sum: " + sum);
                                }
                            }
                        

Output:

                                n is: 1
                                n is: 2
                                n is: 3
                                n is: 4
                                n is: 5
                                Total Sum: 15
                              

do-while

The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. It has below syntax:

                            do {
                                statement(s)
                            } while(expression);
                        

In each iteration do-while loop first execute the loop body then evaluate the expression. If expression is true loop will continue else it will be terminated. A simple Java example:

DoWhileExample.java

                            public class DoWhileExample {

                                public static void main(String s[]) {
                                    int i = 0;
                                    do {
                                        System.out.println("i = " + i);
                                        i++;
                                    } while(i<=5);
                                }
                            }
                        

Output:

                            i = 0
                            i = 1
                            i = 2
                            i = 3
                            i = 4
                            i = 5
                        

Jump Statements

A jump statement stop the current execution and tranfer the control to another part of your program. Java has three type of jump statements: return, break and continue

return

The return statement is used to explicitly return from a method. It causes program control to transfer back to the caller of the method. It has this syntax:

                            return value-to-return;
                        

Here is a simple Java program:

ReturnExample.java

                            public class ReturnExample {

                                public static void main(String s[]) {
                                    String name = getMyName();
                                    System.out.println("Name is: " + name);
                                }

                                private static String getMyName() {
                                    return "Jack";
                                }
                            }
                        

Output:

                            Name is: Jack
                        

break

A break statement has multiple purpose:

  • Used to exit a loop
  • Used to terminate a sequence in switch statement as shown earlier.

A Java example to show how use break to exit a loop:

BreakExample.java

                            public class BreakExample {

                                public static void main(String s[]) {
                                    for(int i=1; i<=20; i++) {
                                        System.out.println("i is: " + i);
                                        if(i == 10) {
                                            System.out.println("Exiting the loop..");
                                            break;
                                        }
                                    }
                                    System.out.println("Out of loop.");
                                }
                            }
                        

Output:

                            i is: 1
                            i is: 2
                            i is: 3
                            i is: 4
                            i is: 5
                            i is: 6
                            i is: 7
                            i is: 8
                            i is: 9
                            i is: 10
                            Exiting the loop..
                            Out of loop.
                        

As you can see once the value of i is 10, loop is terminated and the immediate line following for is executed.

continue

The continue statement skips the current iteration of a for, while or do-while loop.

ContinueExample.java

                            public class ContinueExample {

                                public static void main(String s[]) {
                                    for(int i=1; i<=5; i++) {
                                        if(i == 3) continue;
                                        System.out.println("i is: " + i);
                                    }
                                }
                            }
                        

Output:

                            i is: 1
                            i is: 2
                            i is: 4
                        

If you see the output carefully, you will find that i is: 3 is not printed because of if(i == 3) continue;. Here once i is 3, next all statements are skipped.