Unit: 5 Control Statements

By Haitomns G

Java’ Selection Statements

There are two types of decision-making statements in Java. They are:

  1. If Statement
  2. Switch Statement

If Statement:

The if statement is one of the most powerful statements of any programming language, it is used to carry out a logical test of conditions and take one of the impossible actions depending upon the result of the test. The condition will be true or false.

Syntax:

if (condition) {

            // statement

}

Example:

public class IfExample { 

    public static void main(String[] args) { 

        int age=20; 

        if(age>18){ 

            System.out.print(“Age is greater than 18”); 

        } 

    } 

Output:

Age is greater than 18

If Else Statement:

If statement provides two-way branching. If statement can be followed by an optional else statement, which will be executed when the Boolean expression is false.

Syntax:

if (condition) {

            // statement

}

else{

            //statement

}

Example:

public class IfElseExample { 

    public static void main(String[] args) { 

        //defining a variable 

        int number=13; 

        //Check if the number is divisible by 2 or not 

        if(number%2==0){ 

            System.out.println(“even number”); 

        }else{ 

            System.out.println(“odd number”); 

        } 

    } 

Output:

odd number

If Elseif Else Statement

If statement can be followed by an optional else statement, which is very useful to test various conditions using single IF statement.

When if, else if, else statement, there are few points to keep in mind:

  • An if can have zero or one else, and it must come after if statement.
  • An if can have zero to many else, if and they must come before the else.
  • Once an else succeed none of the remaining else if or else will be tested.

Syntax:

if (condition) {

            // statement

}

else if(condition)

{

            // statement

}

else

{

            // statement

}

Example:

public class IfElseIfExample { 

    public static void main(String[] args) { 

        int marks=65; 

        if(marks<50){ 

            System.out.println(“fail”); 

        } 

        else if(marks>=50 && marks<60){ 

            System.out.println(“D grade”); 

        } 

        else if(marks>=60 && marks<70){ 

            System.out.println(“C grade”); 

        } 

        else if(marks>=70 && marks<80){ 

            System.out.println(“B grade”); 

        } 

        else if(marks>=80 && marks<90){ 

            System.out.println(“A grade”); 

        }else if(marks>=90 && marks<100){ 

            System.out.println(“A+ grade”); 

        }else{ 

            System.out.println(“Invalid!”); 

        } 

    } 

Output:

C grade

Nested If Else Statement:

It is always legal to nest if else statement, which means we can use one if or else if statement inside the if or another, if else statement.

Syntax:

if(condition){   

     // statement

          if(condition){ 

             // statement

    }   

}

Example:

public class JavaNestedIfExample {   

    public static void main(String[] args) {   

        //Creating two variables for age and weight 

        int age=20; 

        int weight=80;   

        //applying condition on age and weight 

        if(age>=18){   

            if(weight>50){ 

                System.out.println(“You are eligible to donate blood”); 

            }   

        }   

    }

}

Output:

You are eligible to donate blood

Switch Statement:

A Switch statement allows the variable to test for equality against the list of values. Each value is called case, and the variable begins switched on is checked for each value.

The switch keeps default statement is useful whenever flow of control must be directed to one of the several possible statements.

Syntax:

switch(expression)

{   

            case 1:

                        // statement

            case n:

                        // statement

default:    

                        // statement

}   

Example:

public class SwitchMonthExample {   

    public static void main(String[] args) {   

        //Specifying month number 

        int month=7;   

        String monthString=””; 

        //Switch statement 

        switch(month){   

        //case statements within the switch block 

        case 1: monthString=”1 – January”; 

        break;   

        case 2: monthString=”2 – February”; 

        break;   

        case 3: monthString=”3 – March”; 

        break;   

        case 4: monthString=”4 – April”; 

        break;   

        case 5: monthString=”5 – May”; 

        break;    

        case 6: monthString=”6 – June”; 

        break;   

        case 7: monthString=”7 – July”; 

        break;   

        case 8: monthString=”8 – August”; 

        break;   

        case 9: monthString=”9 – September”; 

        break;   

        case 10: monthString=”10 – October”; 

        break;   

        case 11: monthString=”11 – November”; 

        break;   

        case 12: monthString=”12 – December”; 

        break;   

        default:System.out.println(“Invalid Month!”);   

        }   

        //Printing month of the given number 

        System.out.println(monthString); 

    }   

}  

Output:

7 – July

Iteration Statements

Looped are required whenever set of statement must be executed a number of times. The loop structure is one, where the sequence of statements are executed repeatedly until some condition is terminated or the loop is satisfied. A loop consists of two parts: The body of the loop and the control statement.

The control statement checks given condition and then executes the set of statement in the body of the loop. Control Structure can be classified into two categories:

  • Entry Control Loop
    • Exit Control Loop

Entry Control Loop:

The loop in which the control conditions are tested before looping are known as entry control loop.

Exit Control Loop:

The loop in which the control conditions are tested at the end of the body of the loop are known as exit control loop.

Java has very flexible three mechanisms:

  1. While Loop
  2. Do While Loop
  3. For Loop

While Loop

While look is the control statement that allows to repeat a loop certain number of times.

The condition is checked if the condition is found to be true. The statement in a domain are executed and controlled transfer back to the test expression.

When the condition is false control is transferred back to the next statement outside the loop.

Syntax:

while(condition)

{

// statement

}

Example:

public class WhileExample { 

    public static void main(String[] args) { 

        int i=1; 

        while(i<=10){ 

            System.out.println(i); 

        i++; 

        } 

    } 

Output

1

2

3

4

5

6

7

8

9

10

Do While Loop;

Do wide loop is similar to while loop, that is do while loop is guaranteed to execute at least one time.

In do while loop the body of loop is executed first.

The test condition is checked. If condition is true, control is transferred back to the beginning of the loop.

When the condition is false, control is transferred to the next statement outside the loop.

Syntax:

do {

    // statement

} while(condition);

Example:

public class DoWhileExample {   

    public static void main(String[] args) {   

        int i=1;   

        do{   

            System.out.println(i);   

        i++;   

        }while(i<=10);   

    }   

}   

Output:

1

2

3

4

5

6

7

8

9

10

For Loop;

A for loop is a reputation control that allows the efficiently write a loop that needs to be execute a specific number of times.

Here is the flow of control in for loop:

  • The initialization step executed 1st and only one this step allows to declare an initialize any loop control variable.
  • Next, the Boolean expression is evaluated if it is true the body of loop is executed if it is for the body of the loop, doesn’t execute and flow of control jumps to the next statement in the loop.
  • After the body of the loop executes, the flow of the control jump back to the update statement. This statement allows to update any loop control variables
  • The Boolean expression is now evaluated again if it is true. The loop executes and the process repeats itself after the Boolean expression is false the for loop terminates.

Syntax:

for(initialization; condition; increment/decrement)

{   

//statement

}   

Example:

public class ForExample { 

    public static void main(String[] args) { 

        //Code of Java for loop 

        for(int i=1;i<=10;i++){ 

            System.out.println(i); 

        } 

    } 

Output:

1

2

3

4

5

6

7

8

9

10

Java Nested for Loop

If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely whenever outer loop executes.

Syntax:

for ( initialization; condition; increment ) {

   for ( initialization; condition; increment ) {

      // statement of inside loop

   }

   // statement of outer loop

}

Example:

public class NestedForExample {

    public static void main(String[] args) {

        for (int i = 1; i <= 3; i++) {

            for (int j = 1; j <= 3; j++) {

                System.out.println(i + ” ” + j);

            }

        }

    }

}

Output:

1 1

1 2

1 3

2 1

2 2

2 3

3 1

3 2

3 3

Java for-each Loop

The for-each loop is used to traverse array or collection in Java. It is easier to use than simple for loop because we don’t need to increment value and use subscript notation.

It works on the basis of elements and not the index. It returns element one by one in the defined variable.

Syntax:

for(data_type variable : array_name)

{   

//code to be executed   

}   

Example:

public class ForEachExample { 

    public static void main(String[] args) { 

        //Declaring an array 

        int arr[]={12,23,44,56,78}; 

        //Printing array using for-each loop 

        for(int i:arr){ 

            System.out.println(i); 

        } 

    } 

}

Output:

12

23

44

56

78

Jump Statement:

Jumping statements are control statements that transfer execution control from one point to another point in the program. There are two Jump statements that are provided in the Java programming language:

  1. Break statement.
  2. Continue statement.

Break Statement:

The break keyword is used to stop the entire loop. The break keyword must be used inside any loop of Which statement it will stop the execution of the inner loop and start executing the next line of the code after the block.

Syntax:

break;

Example:

public class BreakExample { 

    public static void main(String[] args) { 

        //using for loop 

        for(int i=1;i<=10;i++){ 

            if(i==5){ 

                //breaking the loop 

                break; 

            } 

            System.out.println(i); 

        } 

    } 

Output:

1

2

3

4

Continue Statement:

To continue keyword can be used in any of the loop control structure. It causes the loop to immediately jump to the next iteration of the loop.

Syntax:

continue;

Example:

public class ContinueExample { 

    public static void main(String[] args) { 

        //for loop 

        for(int i=1;i<=10;i++){ 

            if(i==5){ 

                //using continue statement 

                continue;//it will skip the rest statement 

            } 

            System.out.println(i); 

        } 

    } 

Output:

1

2

3

4

6

7

8

9

10

Also, Read

  1. Unit-1 Introduction to Mobile Application
  2. Unit-1 Java’s Lineage
  3. Unit-3 Data types, Variables, and Array
  4. Unit-4 Operator

Haitomns G. is a desktop, android, and web developer based in Nepal. He has worked on building several websites, apps, and softwares for clients and independent projects. He is experienced in C, C++, C#, Java, Python, SQL, HTML, CSS, PHP, and JavaScript.

1 thought on “Unit: 5 Control Statements”

Leave a Comment

Slide to prove you're not a bot/spammer *