Control Statements in Java

Control Statements in Java Definition -

Control Statements in java control the order of the execution of program based on data value and its types.

Java contain three types of statements -

  1. Selection Statements
  2. Repetition Statements
  3. Branching Statements 

1.  Selection Statements - 

Selection statements can be divided into the following categories:

  • The if and if-else statements
  • The if-else statements
  • The if-else-if statements
  • The switch statements

Java if statement -

Java if statement is used to check the condition it will be executed only if condition is true.

control statements in java
Flow Diagram if statement

Syntax -

 if(conditional_expression){
  <statements>;
  ...;
  ...;
}

Example -

class IfExample
{
    public static void main(String args[])
    {
        int i = 10;
 
        if (i > 15)
            System.out.println("10 is less than 15");
 
        // This statement will be executed
        // as if considers one statement by default
        System.out.println("I am Not in if");
    }
}

Output -

I am Not in if

Java if-else statement -

Java if-else statement is extension of if statement in this if statement false then else block will be executed.

control statements in java
Flow Diagram if-else

Syntax -

 if(conditional_expression){
  <statements>;
  ...;
  ...;
  }
   else{
  <statements>;
  ....;
  ....;
   }

Example -

class IfElseExample
{
    public static void main(String args[])
    {
        int i = 10;
 
        if (i < 15)
            System.out.println("i is smaller than 15");
        else
            System.out.println("i is greater than 15");
    }
}

Output:

i is smaller than 15

If-else Ladder Statement -

The if-else-if nested statement executes one condition from multiple statements.

control statements in java
Flow Diagram if else ladder

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 conditions are false  
}

Example -

public class ControlFlowExample
{
    public static void main(String[] args)
    {
        char ch = 'o';
 
        if (ch == 'a' || ch == 'A')
            System.out.println(ch + " is Vowel");
        else if (ch == 'e' || ch == 'E')
            System.out.println(ch + " is Vowel.");
        else if (ch == 'i' || ch == 'I')
            System.out.println(ch + " is Vowel.");
        else if (ch == 'o' || ch == 'O')
            System.out.println(ch + " is Vowel.");
        else if (ch == 'u' || ch == 'U')
            System.out.println(ch + " is Vowel.");
        else
            System.out.println(ch + " is a not Vovel it is Consonant.");
	}
}

Switch Statement -

Switch statement is menu kind of item. it is a selection statement that define multiple path of execution of program.

Syntax -

  switch (<non-long integral expression>) {
     case 1: <statement1>
     case 2: <statement2>
        …
     case n: <statementn>
     default: <statement>
    } // end switch

Example -

public class SwitchExample  
{  
    public static void main( String[] args )  
    {  
        int age;  
        Scanner scn= new Scanner( System.in );  
        System.out.print( "Please enter your Age: " );  
        age = scn.nextInt();  
        switch ( age )  
        {  
            case 18:  
                System.out.println( "age 18" );  
                break;  
            case 19:  
                System.out.println( "age 19" );  
                break;  
            default:  
                System.out.println( "not matching in our system" );  
                break;  
        }  
    }  
}

The following rules apply to a switch statement −

  • The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums.
  • You can use any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
  • The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.
  • When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
  • When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
  • Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
  • A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

2. Repetition Statement

Repetition Statement is divided into three categories.

  1. while
  2. do while
  3. for

while loop -

While loop are executed as long as condition return true, to end this loop iteration condition should be false, This is achieved through counters, Counters are variable and it is incremented on each iteration (every time body of loop is executed).

control statements in java
while loop flow diagra

Following are the syntax for while loop

while ( condition ) {
    // code
}

Example -

public class WhileTest {  
public static void main(String[] args) {  
    int i=1;  
    while(i<=5){  
        System.out.println(i);  
    i++;  
    }  
}  
}

Output:

1
2
3
4
5

do while statement in java -

It is an extension of while loop, Java Do while loop as compared to while loop will execute any statement inside do while loop at least one time. Means do while loop evaluates condition after do while loop’s code is executed once.

control statement in java
do-while flow diagram

Syntax -

do { 
   // body of loop 
} while

Example -

//Java program to print JavaTechWorld 10 times using do while loop
 
public class PrintJavaTechWorld
{
    public static void main(String args[]){
         
        int loop; //loop counter declaration
        final String name="JavaTechWorld"; //name as constant
         
        loop=1; //initialization of loop counter
        do{
            System.out.println(name);
            loop++; //increment
        }while(loop<=10);
         
    }

java for loop -

If the number of iteration is fixed then you have to use for loop. Let's suppose you want to print a number 50 times. Instead of using 50 System.out.println( ) statements, we can simply loop over a single System.out.println( ) statement 10 times.

Let's see the for loop syntax in Java.

Syntax -

for ( initiallization; condition; increment / decrement ) { 
      statement 1;
      statement 2;
              .
              .
      statement n;
}

Example -

public class ForExample {  
public static void main(String[] args) {  
    for(int i=1;i<=50;i++){  
        System.out.println(i);  
    }  
}  
}  

3. Branching Statements -

Branding Statements are

  1. break statement
  2. continue statement
  3. return statement

break statement - 

break in branching statement is used to break the flow of your loop (do-while, while, for or switch statement) In case of switch statement we use break at the end of each case statement.

Syntax -

loop (...){
condition{
break;
}
//statements......
}

Example -

public class BreakStatementExample {

	public static void main(String[] args) {
		System.out.println("Numbers 1 - 10");
		for (int i = 1;; ++i) {
			if (i == 11)
				break;
			// Rest of loop body skipped when i is even
			System.out.println(i + "\t");
		}
	}
}jump-statement; 
continue; 

continue statement in java -

continue statement in java is used to continue current flow of program and left the remaining code at specified condition. You can use continue statement when you do not want to execute remaining statement in the loop but you do not want to exit the loop. 

continue statement stop the flow of for, while , or do-while loop.

Syntax -

jump-statement;    
continue; 

Example -

class ContinueStatementExample {

	public static void main(String[] args) {
		System.out.println("Odd Numbers");
		for (int i = 1; i <= 10; ++i) {
			if (i % 2 == 0)
				continue;
			// Rest of loop body skipped when i is even
			System.out.println(i + "\t");
		}
	}
}

return statement in java -

The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method. As such, it is categorized as a jump statement. 

At any time in a method the return statement can be used to cause execution to branch back to the caller of the method. Thus, the return statement immediately terminates the method in which it is executed. The following example illustrates this point. Here, return causes execution to return to the Java run-time system, since it is the run-time system that calls main( ).

Syntax -

return expression;
return;

Example -

class Return { 
public static void main(String args[]) { 
boolean t = true; 
System.out.println("Before the return."); 
if(t) return; // return to caller 
System.out.println("This won't execute."); 
} 
}

 

Leave a Comment

%d bloggers like this: