Updates
  • Starting New Weekday Batch for Java Full Stack Developer on 24th June 2024 @ 02:00 PM to 04:00 PM
  • Starting New Weekend Batch for Java Full Stack Developer on 06th July 2024 @ 11:00 AM to 02:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 08th July 2024 @ 04:00 PM to 06:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 29th July 2024 @ 10:00 AM to 12:00 PM
Join Course

Control Statement


In a Java Program the control moves from top to bottom by default, but sometimes we need to control the flow of the codes as per our requirement. In order to control the flow of the program Control Statement has been introduced.

Types of Control Statement

Java Control Statement is of the following three types

1. Conditional Control Statement
2. Looping Control Statement
3. Unconditional Control Statement

Conditional Control Statement

In Conditional Control Statement the execution of a set of codes depends on specific conditions or the results of tests which can be either true or false.

Types of conditional control statement

1. If Statement
2. If-Else Statement
3. Nested If Statement
4. If-Else Ladder
5. Switch Statement

1. If Statement

In Java if statement, also known as if-then statement, is the simplest form of decision-making statement. If statements are used to control the flow of program based on specified conditions: for example a statement that is executed only when true condition is present, otherwise the program skips the section and moves ahead..

syntax:
if (condition) {
// block of code to be executed if the condition is true
}

            
public class If_Statement {
	public static void main(String[] args) {
		int number1 = 20;
		int number2 = 18;
		if (number1 > number2) {
			System.out.println("number1 is greater than number2");
		}

	}

}
            
        
    number1 is greater than number2
            

Here, we are declaring a class as If Statement and inside this class we are declaring int type variables number1 and number2 and initializing it. Thereafter using if statement we are checking a condition (number1 > number2). We will get true as the result since value of number1 and number2 are 20 and 18 respectively. Since the program finds a true condition, it proceeds to execute corresponding output.


2. If-else Statement

if-else statement is also known as if-then-else statement.
if-else statement also tests conditions.
It executes the if block if condition is true, otherwise else block is executed.

syntax:
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

            
public class If_Else_Statement {

public static void main(String[] args) {
    int number1 = 20;
    int number2 = 15;

    if (number1 < number2) {
        System.out.println("number1 is less than number2");
    } else {
        System.out.println("number1 is greater than number2");
    }

   }

}
            
        
    number1 is greater than number2
            


In the above example we declare a class as if-else statement and we test a condition (number1 < number2) using If-else statement. We get a false as value of number1 (20) is greater than value of number2 (15), hence the control moves to the else block and we get “number1 is greater than number2” as the output.

3. Nested-If Statement

In Java, the Nested-if statement represents an if block inside another if block. The inner if block condition is executed only when the outer if block condition is true.

syntax:
if (condition) {
// code to be
if (condition) {
//code to be executed
}
}

            
class Nested_If{
	public static void main(String arg[]){
		int a = 10,b = 20, c = 30;
		
		if(a > b){
			if(a > c){
				System.out.println("a is greatest.");
			}else{
				System.out.println("c is greatest.");
			}
		}else{
			if(b > c){
				System.out.println("b is greatest.");
			}else{
				System.out.println("c is greatest.");
			}
		}
	}
}

            
        
    c is greatest.
            


In the above program we have 3 int type of variables a, b and c and their values are 10, 20 and 30 respectively. Here we want to find the greatest number out of three given numbers using nested-if statement. The first condition a > b i.e. 10 > 20 returns a false, so the control moves to the else block of the outer if statement. Now we check the second condition b > c i.e. 20 > 30 and again the return is false. The control now moves to the corresponding else block of the current if statement and we get the output as “c is greatest”.

4. If-Else Ladder

An if statement can follow an optional else-if-else statement, which is useful for testing many conditions with a single if-else statement.

Syntax:

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}else{
//code to be executed if all the condition is false
}

            
class If_Else_Ladder{
	public static void main(String arg[]){
		int num = 10;
		
		if(num > 0){
			System.out.println(num +" is a +ve number.");
		}else if(num == 0){
			System.out.println(num+" is a zero");
		}else{
			System.out.println(num+" is a -ve number");
		}
	}
}
            
        
    10 is a +ve number.
            


In the above code we define a class as If_Else_Ladder. We want to check whether the given num is a +ve number or –ve number or zero. Here we have an int type of variable num and its value is 10 in the first if statement. We set a condition num > 0 and get a true for the current value of num, hence the control moves to the relevant if block and skips the other if block.

5. Switch Statement

Using the switch statement, we can easily address a situation where we have provided multiple options to the end user. The user can select anyone out of the given options and further processing depends on the option selected by the user.

Syntax:

switch(selected-option) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

How switch statement works:

o The switch expression is evaluated once.
o The value of the expression is compared with the values of each case. If there is a match, the associated block of code is executed.
o When no match is found then the default block gets executed.
o Duplicate case levels are not allowed.

            

class Switch{
	public static void main(String arg[]){
		System.out.println("******* WELCOME TO THE JTC ARITHMETIC CALCULATOR *******");
		System.out.println("_________________________________________________________");
		System.out.println("_____________________MAIN OPTION LIST____________________");
		System.out.println("Addition :- Press A");
		System.out.println("Subtraction :- Press S");
		System.out.println("Multiplication :- Press M");
		System.out.println("Division :- Press D");
		System.out.println("Modulus :- Press Mod");
		System.out.println("Waiting for your input....!");
		
		Scanner s1 = new Scanner(System.in);
		String input = s1.nextLine();
		int a,b;
		switch(input){
			case "A":
				System.out.println("Waiting for first operend :- ");
				a = s1.nextInt();
				System.out.println("Waiting for second operend :- ");
				b = s1.nextInt();
				System.out.println(a+" + "+b+" = "+(a+b));
				break;
			case "S":
				System.out.println("Waiting for first operend :- ");
				a = s1.nextInt();
				System.out.println("Waiting for second operend :- ");
				b = s1.nextInt();
				System.out.println(a+" - "+b+" = "+(a-b));
				break;
			case "M":
				case "Add":
				System.out.println("Waiting for first operend :- ");
				a = s1.nextInt();
				System.out.println("Waiting for second operend :- ");
				b = s1.nextInt();
				System.out.println(a+" x "+b+" = "+(a*b));
				break;
			case "D":
				System.out.println("Waiting for first operend :- ");
				a = s1.nextInt();
				System.out.println("Waiting for second operend :- ");
				b = s1.nextInt();
				System.out.println(a+" / "+b+" = "+(a/b));
				break;
			case "Mod":
				System.out.println("Waiting for first operend :- ");
				a = s1.nextInt();
				System.out.println("Waiting for second operend :- ");
				b = s1.nextInt();
				
				break;
			default:
				System.out.println("\n\n**************************************************");
				System.out.println("----You have selected an invalid option ----\u0002----");
				System.out.println("_____________________MAIN OPTION LIST____________________");
				System.out.println("Addition :- Press A");
				System.out.println("Subtraction :- Press S");
				System.out.println("Multiplication :- Press M");
				System.out.println("Division :- Press D");
				System.out.println("Modulus :- Press Mod");
				System.out.println("Waiting for your input....!");
		}
		
	}
}
            
        
                
            


In the above code we have a switch statement and we use it to perform arithmetic operations on the basis of selected options.¬ In this program we want to get input from keyboard using class- java.util.scanner , and on the basis of selected option we perform an arithmetic operation.

Looping Control Statement

Looping control Statement is used to continuously execute a set of codes till a certain period of time.

Types of Looping Control Statements

1. For loop
2. While loop
3. Do while loop

1. For loop

Syntax:

for (initialization; condition;updation) {
statement;
}

Initialization: When control moves inside the for-loop then first the initialization codes get executed.

Condition: here we check specified condition or conditions, if the specified condition returns as true then only the control moves inside the loop.

Updation: After processing the statements finally, the control moves to the updation section and thereafter the control moves to the condition section to re- check . In this manner the control moves between the condition section, statement and updation section until a false result from the condition section is obtained.

            
class JTC{
	public static void main(String arg[]){
		int sum = 0;
		for(int i = 1; i <= 100; i++){
			if(i%7 == 0){
				sum += i;
			}
		}
		System.out.println("sum of all numbers which is div by 7:- "+sum);
	}
}

            
        
    sum of all numbers which is div by 7:- 735
            


In the above program we have a class JTC where we are trying to find the sum of all the numbers from 1 to 100 which are divisible by 7.

2. While loop

In while loop, condition is evaluated first and if it returns true then only the statements are processed inside the while loop.

When condition returns false, then the control comes out of the loop and jumps to the next statement after the while loop.

Syntax:
while (condition) {
statement.
}

            
public class JTC {

public static void main(String[] args) {
    int i = 1;
    while(i <= 10){
        System.out.println("2 x "+i+" = "+(2*i));
        i++;
      }
    }
}
            
        
    2 x 1 = 2
    2 x 2 = 4
    2 x 3 = 6
    2 x 4 = 8
    2 x 5 = 10
    2 x 6 = 12
    2 x 7 = 14
    2 x 8 = 16
    2 x 9 = 18
    2 x 10 = 20
            


Here, in JTC class we are trying to print the Table of 2 from 1 to 10 using while loop, we can see we have an int type of variable i and their initial value is 1 and in while loop we have a condition i <= 10, so in the first test we will get a true and the control moves inside the while loop (like as we have discussed) and we will get an output “2 x 1 = 2”, then we have i++ statement which increases the value of i by 1 and this process executes until the we get a false condition.

3. Do-while loop

Java do-while loop is used to execute a block of statements continuously until the given condition is true.

The do-while loop in Java is similar to while loop except that the condition is checked after the statements are executed, so do-while loop guarantees the loop execution at least once.

Syntax:
do {
statement(s)
} while (condition);

The statement(s) inside the block are executed, and the condition is evaluated. As long as the condition is true, the statement(s) inside the block are executed in a loop, or else if the condition is false, the execution of do-while is completed.

            
public class JTC {

public static void main(String[] args) {
    int count = 1;
    do {
        System.out.println("Count is: " + count);
        count++;
    } while (count < 11);
}

}

            
        
    Count is: 1
    Count is: 2
    Count is: 3
    Count is: 4
    Count is: 5
    Count is: 6
    Count is: 7
    Count is: 8
    Count is: 9
    Count is: 10
            


In the above program we are increasing the value of int type variable count = 1 by 1using post-increment operator and the iteration is executed 10 times using do while loop.

            
public class JTC {

public static void main(String[] args) {

    // for(;false;){} :- error : unreachable statement

    //  while(false){} :- error : unreachable statement

    do{ 
        }while(false);
    System.out.println("No Error");
    

    }
}

            
            
    No Error
            


This program shows the difference between do-while loop and other loops (for loop and while loop), in the first section of the program while we are passing false value directly in for loop and while loop we are getting an error at compile time which is “unreachable statement”. Unreachable Statement error occurs when we have a code which never executes, but in the case of do-while loop we do not get any error at compile time because in do-while loop the condition is evaluated after the statements, that is the loop executes once in the case of a false condition also.

Unconditional Control Statement

In Unconditional Control Statement there is no need to satisfy any condition. The control moves from one section of the code to another section.

1. Break Statement (Labeled break statement | Unlabeled break statement)
2. Continue Statement (Labeled continue statement | Unlabeled continue statement)

1.Break Statement

• In Java break is a keyword which is basically used to terminate a loop or switch statement.
• We can’t use a break statement outside the switch statement or loop, otherwise we get an error at compile time (break outside switch or loop).
• Break must be the last statement inside the block, otherwise we get error (unreachable statement at compile-time).

There are two type of break statements –
1. Unlabeled break statement.
2. Labeled break statement.

            
class JTC {

public static void main(String[] args) {
System.out.println("------Unlabeled Break Statement-------");
for(int i = 0; i <= 10; i++){
   if(i == 5){
System.out.println("\nLoop terminated due to break statement...!");
   break;
//System.out.println("break statement must be the last statement inside their block...!");
       }
       System.out.print("i -> "+i);
   }
}

}

            
        
    ------Unlabeled Break Statement-------
    i -> 0i -> 1i -> 2i -> 3i -> 4
    Loop terminated due to break statement...!
            

In the above program we have a loop which stared from 1 and moves towards 10. In every iteration we are printing the value of i which is an int type of variable. Inside the for-loop we have an if statement which is having a condition i == 5, and on the basis of specified condition we are terminating the for-loop using unlabeled break statement.

            
public class JTC {

public static void main(String[] args) {
    System.out.println("\n------Nested-loop with Unlabeled Break Statement-------");
    for(int i = 1; i <= 5; i++){
        for(int j = 1; j<=3; j++){
            if(j == 3){
                System.out.println("Inner-Loop terminated due to break statement...!");
                break;
            }
            System.out.println("i -> "+i+" | j -> "+j);
        }
    }
}

}
            
        
    ------Nested-loop with Unlabeled Break Statement-------
    i -> 1 | j -> 1
    i -> 1 | j -> 2
    Inner-Loop terminated due to break statement...!
    i -> 2 | j -> 1
    i -> 2 | j -> 2
    Inner-Loop terminated due to break statement...!
    i -> 3 | j -> 1
    i -> 3 | j -> 2
    Inner-Loop terminated due to break statement...!
    i -> 4 | j -> 1
    i -> 4 | j -> 2
    Inner-Loop terminated due to break statement...!
    i -> 5 | j -> 1
    i -> 5 | j -> 2
    Inner-Loop terminated due to break statement...!
            


In the program we have an implementation of nested loop and using unlabeled break statement we are terminating inner loop on the basis of specified condition of if statement which is i==3.

            
public class JTC {

public static void main(String[] args) {
System.out.println("\n------Nested-loop with Labeled Break Statement-------");
    jtc: // lebel declr...
    for(int i = 1; i <= 5; i++){
        for(int j = 1; j<=3; j++){
            if(j == 3){
                System.out.println("Outer-Loop terminated due to break statement...!");
                break jtc;
            }
            System.out.println("i -> "+i+" | j -> "+j);
        }
    }
}

}

            
        
    ------Nested-loop with Labeled Break Statement-------
    i -> 1 | j -> 1
    i -> 1 | j -> 2
    Outer-Loop terminated due to break statement...!
            


In the above program we have a for-loop which executes from 1 to 5 and we have another for-loop which executes from 1 to 3 for every iteration of outer loop. In inner loop we have labeled break statement with jtc level and we can see that we have declared jtc level at outer loop, it defines that when break jtc executes then directly for-loop terminates.

2.Continue Statement

• Continue is also a keyword in java like break.
• We can use continue statement inside the loop only.
• It is basically used to skip the current iteration of a loop.
• It must be the last statement inside the block, otherwise we get unreachable error at compile-time.

We have two different types of continue statements
1. Unlabeled Continue Statement.
2. Labeled Continue Statement.

            
class JTC {

public static void main(String[] args) {
		System.out.println("-------Unlabeled Continue Statement-------");
		for(int i = 1; i<= 10;i++){
			if(i == 5){
				System.out.println("Using Unlabeled Continue Statement Skiping the current iteration");
				continue;
			}
			System.out.print("i -> "+i);
		}
	}

}

            
        
    -------Unlabeled Continue Statement-------
    i -> 1i -> 2i -> 3i -> 4Using Unlabeled Continue Statement Skiping the current iteration
    i -> 6i -> 7i -> 8i -> 9i -> 10            
            


In the above program we have a class as JTC where have a for-loop which starts from1 and executes until 10. In every iteration, we are increasing the value of i by 1 using post-increment operator. Inside the for-loop we skipped the iteration at i = 5 using the unlabeled continue statement.

            
public class JTC{

public static void main(String[] args) {
    System.out.println("\n-------Unlabeled Continue Statement with Nested-Loop-------");
    for(int j = 1; j <= 5; j++){
        for(int k = 1; k <= 5; k++){
            if(k == 3){
                System.out.println("Using Unlabeled Continue Statement Skiping the current iteration of Inner-Loop");
                continue;
            }
        System.out.println("j -> "+j+" k -> "+k);
        }
    }
}

}


            
        
    -------Unlabeled Continue Statement with Nested-Loop-------
    j -> 1 k -> 1
    j -> 1 k -> 2
    Using Unlabeled Continue Statement Skiping the current iteration of Inner-Loop
    j -> 1 k -> 4
    j -> 1 k -> 5
    j -> 2 k -> 1
    j -> 2 k -> 2
    Using Unlabeled Continue Statement Skiping the current iteration of Inner-Loop
    j -> 2 k -> 4
    j -> 2 k -> 5
    j -> 3 k -> 1
    j -> 3 k -> 2
    Using Unlabeled Continue Statement Skiping the current iteration of Inner-Loop
    j -> 3 k -> 4
    j -> 3 k -> 5
    j -> 4 k -> 1
    j -> 4 k -> 2
    Using Unlabeled Continue Statement Skiping the current iteration of Inner-Loop
    j -> 4 k -> 4
    j -> 4 k -> 5
    j -> 5 k -> 1
    j -> 5 k -> 2
    Using Unlabeled Continue Statement Skiping the current iteration of Inner-Loop
    j -> 5 k -> 4
    j -> 5 k -> 5
            


In the above example we have a class JTC where we have a loop which executes from 1 to 5 and for every iteration of outer loop, the inner loop also executes from 1 to 5. Inside the inner loop we skip the control of inner loop at k=3 using unlabeled continue statement.

            
public class JTC{

public static void main(String[] args) {
    System.out.println("\n-------Labeled Continue Statement with Nested-Loop-------");
    jtc: // Lebel Declr
    for(int j = 1; j <= 5; j++){
        for(int k = 1; k <= 5; k++){
            if(k == 3){
                System.out.println("Using Labeled Continue Statement Skiping the current iteration of Inner-Loop");
                continue jtc;
            }
        System.out.println("j -> "+j+" k -> "+k);
        }
    }	}

}

            
        
    -------Labeled Continue Statement with Nested-Loop-------
    j -> 1 k -> 1
    j -> 1 k -> 2
    Using Labeled Continue Statement Skiping the current iteration of Inner-Loop
    j -> 2 k -> 1
    j -> 2 k -> 2
    Using Labeled Continue Statement Skiping the current iteration of Inner-Loop
    j -> 3 k -> 1
    j -> 3 k -> 2
    Using Labeled Continue Statement Skiping the current iteration of Inner-Loop
    j -> 4 k -> 1
    j -> 4 k -> 2
    Using Labeled Continue Statement Skiping the current iteration of Inner-Loop
    j -> 5 k -> 1
    j -> 5 k -> 2
    Using Labeled Continue Statement Skiping the current iteration of Inner-Loop
            


In the above code again, we have implemented the same code as in the previous example except here we have labeled a continue statement which is “continue jtc” which is skipping the iteration of outer for-loop because we have declared the same level at the top of outer loop.