Control Flow Statements = Decision making - if, else, switch | Looping - for, Infinite, Enhanced for loop, while, do-while | Branching - break, Labeled break, continue, Labeled continue, return, goTo keyword in java

Control Flow Statements

The statements inside your source files which are generally executed from top to bottom, in the order that they appear.
Control flow statements enables >
  1. decision making,
  2. looping, and
  3. branching,
  4. program to conditionally execute particular blocks of code.


Different Control Flow Statements
  1. Decision making statements
    • 1.1) if
    • 1.2) if-else
    • 1.3) if if-else else
    • 1.4) switch

  1. Looping statements
    • 2.1) for,
      • Infinite for loop
      • Enhanced for loop
    • 2.2) while,
      • Infinite while loop
    • 2.3) do-while
      • Infinite do-while loop
Difference between while and do-while loop

  1. Branching statements
    • 3.1) break,
      • Labeled break statement>
    • 3.2) continue,
      • Labeled continue statement>
    • 3.3) return
    • 3.4) goTo (not used)


Now, let’s discuss different Control Flow Statements in detail

1. Decision making statements

    • 1.1) if
    • 1.2) if-else
    • 1.3) if if-else else
    • 1.4) switch


1.1) If statements

Syntax of if statement>


            if (booleanVal) {
                 // Statements will execute if the booleanVal is true
          }

If booleanVal evaluates to true then the statements inside if block are executed.
More about if statement >
  • If only one statement is used inside if then enclosing those statements in brackets is optional.

             if(booleanVal)
                   //Only a Statement..

  • Or, if we look at it another way - If statements inside if are not enclosed in bracket then only first statement is considered inside if.

             if(booleanVal)
                   //Statement1. (Will be inside if)
                   //Statement2. (Will be outside if)



Program 1.1 to demonstrate if statement
/** JavaMadeSoEasy.com */
public class StatementTest {
   public static void main(String[] args) {
          int marks = 50;
         
          if(marks>=40){
                 System.out.println(">=40 - PASS");
          }         
   }
}
/* OUTPUT
>=40 - PASS
*/

1.2) if-else

Syntax of if-else statement >


             if (booleanVal) {
                 // Statements will execute if the booleanVal is true
          } else {
                 // Statements will execute if the booleanVal is false
          }



if-else statement rules >
If booleanVal evaluates to true then the statements inside if block are executed and statement inside else are not executed.
Program 1.2 to demonstrate if-else statement
/** JavaMadeSoEasy.com */
public class StatementTest {
   public static void main(String[] args) {
          int marks = 39;
         
          if(marks>=40){
                 System.out.println(">=40 - PASS");
          }
          else{
                 System.out.println("<40 - FAIL");
          }
   }
}
/* OUTPUT
<40 - FAIL
*/


1.3) if if-else else

Syntax of if if-else else statement>


            if (booleanVal1) {
                 // Statements will execute if the booleanVal1 is true
          } else if (booleanVal2) {
                 // Statements will execute if the booleanVal is true
          } else if (booleanVal3) {
                 // Statements will execute if the booleanVal3 is true
          }
          // Also java allows us to use any number of if-else conditions.
          else {
                 // Statements will execute if all of the above booleanVal are false.
          }


if if-else else statement rules >
  • If booleanVal evaluates to true in any if or if-else then >
the remaining if-else condition are not evaluated (if any), and
else block is not executed.
  • Also java allows us to use any number of if-else conditions.

Program 1.3 to demonstrate if if-else else statement>
/** JavaMadeSoEasy.com */
public class StatementTest {
   public static void main(String[] args) {
          int marks = 61;
          if(marks>=80){
                 System.out.println(">=80 - Grade A");
          }
          else if(marks>=60){
                 System.out.println(">=60 - Grade B");
          }
          else if(marks>=40){
                 System.out.println(">=40 - Grade C");
          }
          else{
                 System.out.println("<40 - FAIL");
          }
   }
}
/* OUTPUT
>=60 - Grade B
*/

1.4) switch

Syntax of switch statement>


             switch (expression) {
                 case value:
                       // Statements..
                       break; // optional
  
                 case value:
                       // Statements..
                       break; // optional
  
                 // Java allows us to use any number of case statements.
  
                 default: // Optional default statements will execute when none of the
                                     // above case value matches
                       // Statements..
                
          }

switch statement rules >
  1. Before java 7 > byte, short, int, or char can only be used as expression in switch statement (i.e. all those data types which could be implicitly casted into int - read Implicit casting/promotion of primitive Data type).
  2. Java 7 allows to use String as expression in switch statement

  1. Java allows us to use any number of case.

  1. The data type of value of case must have same data type as of expression.

  1. Case is executed - when expression is equal to value in case.

  1. Optional break statement >
    • If break statement is not used (bad practice) >
      • all the statements in below cases will be executed,
      • including statements in default.
    • If break statement is used >
      • switch terminates and
      • flow of control reaches right to the next line of switch.

  1. Optional default >
    • Optional default statements will execute when none of the above case value matches
    • Using break in default doesn’t matter, as it is last case in switch.

Program 1.4.1 to demonstrate switch statement
/** JavaMadeSoEasy.com */
public class StatementTest {
   public static void main(String[] args) {
          char grade = 'B';
          switch (grade) {
                 case 'A':
                       System.out.println("Grade A - marks >=80");
                       break;
  
                 case 'B':
                       System.out.println("Grade B - marks >=60");
                       break;
                 case 'C':
                       System.out.println("Grade C - marks >=40");
                       break;
                      
                 case 'F':
                       System.out.println("Grade F - marks <40 FAIL");
                       break;
                      
                 default : //optional
                       System.out.println("Invalid Grade");
                       break; //optional
          }
   }
}
/*OUTPUT
Grade B - marks >=60
*/


Program 1.4.2 -  Java 7 allows to use String as expression in switch statement
/** JavaMadeSoEasy.com */
public class StatementTest {
   public static void main(String[] args) {
          String marks="marks >=60";
          switch (marks) {
                 case "marks >=80":
                       System.out.println("Grade A");
                       break;
  
                 case "marks >=60":
                       System.out.println("Grade B");
                       break;
                 case "marks >=40":
                       System.out.println("Grade C");
                       break;
                      
                 case "marks <40 FAIL":
                       System.out.println("Grade F");
                       break;
                      
                 default : //optional
                       System.out.println("Invalid marks");
                       break; //optional
          }
   }
}
/*OUTPUT
Grade B
*/



Java allows us to use nested Decision making statements
    • nested if
    • nested if-else
    • nested if if-else else
    • nested switch



2. Looping statements
    • 2.1) for,
      • Infinite for loop
      • Enhanced for loop
    • 2.2) while,
      • Infinite while loop
    • 2.3) do-while
      • Infinite do-while loop


2.1) for loop
Loop allows us to use perform certain task repeatedly.

Syntax of for loop>

             for(initialization; termination_booleanVal; increment/Decrement){
                   //Statements..
          }


How for loop works internally >
    • initialization - declare and initialize variables.
Only done once (i.e. at start of for loop.)
  • You may declare variables of only same data types
for (int i = 0, j=0; i < 3; i++){}

We have declare variable of int type in for loop, so we cannot declare variables of any other data type.
  • If you haven’t declare any data type, you may initialize variable of different data types.
int i; long l;
for (i = 0, l=0; i < 3; i++){}

We have declare variable of int and long type before loop, so we can initialize both.
or initialize any number of variables separated by comma (,)
    • termination_booleanVal - for loop is executed only when termination_booleanVal evaluates to true.
evaluation is done every time when for loop is called.
    • increment/Decrement - increment/Decrement is done at end of for loop.
Not done in first execution, but is done in all subsequent executions.


Let’s understand How for loop works  internally by program >

          for (int i = 0; i < 3; i++) {
                 System.out.println("i= " + i);
          }

First loop,
    • initialization - declare and initialize i.  Only done once  (i.e. at start of for loop)
    • termination_booleanVal -  i < 3 (i.e. 0<3) evaluates to true.
Program will enter for loop, print i= 0
second loop,
    • increment/Decrement - i++ is called, i becomes 1
    • termination_booleanVal -  i < 3 (i.e. 1<3) evaluates to true.

Program will enter for loop, print i= 1
Third loop,
    • increment/Decrement - i++ is called, i becomes 2
    • termination_booleanVal -  i < 3 (i.e. 2<3) evaluates to true.

Program will enter for loop, print i= 2
Then (Attempt for fourth loop),
    • increment/Decrement - i++ is called, i becomes 3
    • termination_booleanVal -  i < 3 (i.e. 3<3) evaluates to false.

Program will not enter for loop, and exit for loop.

Note : If termination_booleanVal evaluates to true in first loop/evaluation, then for loop statements will not be executed even once.
Program 2.1.1 to demonstrate for loop
/** JavaMadeSoEasy.com */
public class LoopTest {
   public static void main(String[] args) {
          for (int i = 0; i < 3; i++) {
                 System.out.println("i= " + i);
          }
   }
}
/* OUTPUT
i= 0
i= 1
i= 2
*/


Infinite for loop
As initialization; termination_booleanVal; increment/Decrement) are optional, we may leave all of them

             // infinite loop
          for ( ; ; ) {
          // Statements..
          }


Enhanced for loop
Enhanced for loop can be used used for iterating over >
  • Array or
  • Collection .
Program 2.1.2 to demonstrate enhanced for loop for iterating over Array elements >
/** JavaMadeSoEasy.com */
public class LoopTest {
   public static void main(String[] args){
     int[] ar =  {1,2,3};
     for (int n : ar) {
         System.out.println(n);
     }
   }
}
/* OUTPUT
1
2
3
*/

Program 2.1.3 to demonstrate enhanced for loop for iterating over Collection elements >
import java.util.ArrayList;
/** JavaMadeSoEasy.com */
public class LoopTest {
   public static void main(String[] args){
     ArrayList<Integer> l =  new ArrayList<Integer>();
     l.add(1);
     l.add(2);
     l.add(3);
    
     for (int n : l) {
         System.out.println(n);
     }
   }
}
/* OUTPUT
1
2
3
*/



2.2) while loop

Syntax of while loop>

            while(booleanVal){
                   //Statements..
          }

If booleanVal evaluates to true then the statements inside while loop are executed.
while loop will continue to execute until booleanVal evaluates to true.


Note : If booleanVal evaluates to false in first loop/evaluation, then while loop statements will not be executed even once.

Program 2.2 to demonstrate while loop
/** JavaMadeSoEasy.com */
public class LoopTest {
   public static void main(String[] args) {
          int i = 0;
          while(i < 3){
                 System.out.println("i= " + i);
                 i++;
          }
   }
}
/* OUTPUT
i= 0
i= 1
i= 2
*/


Infinite while loop

            while(true){
                   //Statements..
          }





2.3) do-while loop

Syntax of do-while loop>

             do {
          //Statements..
          } while (booleanVal);


First statements inside do block are executed, then booleanVal is evaluated.
do-while loop continue to execute until booleanVal evaluates to true.

Program 2.3 to demonstrate do-while loop
/** JavaMadeSoEasy.com */
public class LoopTest {
   public static void main(String[] args) {
          int i = 0;
          do{
                 System.out.println("i= " + i);
                 i++;
          }while(i < 3);
  
   }
}
/* OUTPUT
i= 0
i= 1
i= 2
*/


Infinite do-while loop
            do{
          // Statements..
          }
          while ( true );



Difference between while and do-while loop

while loop
do-while loop
in while loop statements may not be executed even once.

booleanVal is evaluated at top in while loop.
So, Statements inside while loop are executed when booleanVal is true.

If booleanVal evaluates to false in first loop/evaluation, then while loop statements will not be executed even once.

in do-while loop statements are at least executed once.

First statements inside do block are executed, then booleanVal is evaluated.
Program - When while loop statements are not executed even once.


/** JavaMadeSoEasy.com */
public class LoopTest {
   public static void main(String[] args) {
          int i = 3;
          while(i < 3){
                 System.out.println("i= " + i);
                 i++;
          }
   }
}
/* OUTPUT
*/
Program - Even with same while condition used in do-while, do-while loop statements are at least executed once (as compared to while loop program).

/** JavaMadeSoEasy.com */
public class LoopTest {
   public static void main(String[] args) {
          int i = 3;
          do{
                 System.out.println("i= " + i);
                 i++;
          }while(i < 3);
  
   }
}
/* OUTPUT
i= 3
*/





Java allows us to use nested Looping statements
    • nested for,
      • nested Enhanced for loop
    • nested while,
    • nested do-while


3. Branching statements  
    • 3.1) break,
      • Labeled break statement>
    • 3.2) continue,
      • Labeled continue statement>
    • 3.3) return
    • 3.4) goTo (not used)

3.1) break
  • break statement
  • break is keyword in java.
  • break statement can be used inside >
  • loop (for, while, do-while) or
  • switch statement.
  • break statement can’t be used inside method.
  • break statement is used to stop the loop, flow of control reaches right to the next line where loop ends.
  • If break statement is used inside nested loops, than innermost loop will be stopped,  flow of control reaches right to the next line where innermost loop ends.

break;



Program 3.1.1 to demonstrate break statement>
/** JavaMadeSoEasy.com */
public class StatementTest {
   public static void main(String[] args) {
          for (int i = 0; i < 3; i++) {
                 if(i>1){
                       break;
                 }
                 System.out.println("i= " + i);
          }
         
   }
}
/* OUTPUT
i= 0
i= 1
*/

Program 3.1.2 to show - If break statement is used inside nested loops, than innermost loop will be stopped,  flow of control reaches right to the next line where innermost loop ends >
/** JavaMadeSoEasy.com */
public class StatementTest {
   public static void main(String[] args) {
          for (int i = 0; i < 3; i++) { //outer loop
                
                 System.out.println("outer i= " + i);
         
                 for (int j = 0; j < 3; j++) { //inner loop
                       if(j>0){
                              break;
                       }
                       System.out.println("inner i= " + i+", j= " + j);   
                 }//end inner loop
          }//end outer loop
         
   }
}
/* OUTPUT
outer i= 0
inner i= 0, j= 0
outer i= 1
inner i= 1, j= 0
outer i= 2
inner i= 2, j= 0
*/




Labeled break statement>
So far we have used unlabeled break statements, but now we will learn how to use labeled break statements via program.
Program 3.1.3 to demonstrate labeled break statement>
/** JavaMadeSoEasy.com */
public class StatementTest {
   public static void main(String[] args) {
          outerForLoop: // Labeled outer loop
                 for (int i = 0; i < 3; i++) {
                       System.out.println("outer i= " + i);
         
                       innerForLoop: // Labeled  inner loop
                              for (int j = 0; j < 3; j++) {
                                     if (j > 0) {
                                            break outerForLoop;
                                     }
                                     System.out.println("inner i= " + i + ", j= " + j);
                              }// end inner loop
                 }// end outer loop
  
   }
}
/* OUTPUT
outer i= 0
inner i= 0, j= 0
*/



3.2) continue statement

continue statement
  • continue is keyword in java.
  • continue statement can be used inside >
  • loop (for, while, do-while)
  • continue statement can’t be used inside
    • method or
    • switch.
  • continue statement is used to skip the current iteration of loop, flow of control reaches right to start of loop.
  • If continue statement is used inside nested loops, than current iteration of innermost loop will be stopped,  flow of control reaches right to the start of innermost loop.


continue;


Program 3.2.1 to demonstrate continue statement>
/** JavaMadeSoEasy.com */
public class StatementTest {
   public static void main(String[] args) {
          for (int i = 0; i < 3; i++) {
                 System.out.println("before continue > i= " + i);
                 if(i>1){
                       continue;
                 }
                 System.out.println("after continue > i= " + i);
          }
         
   }
}
/* OUTPUT
before continue > i= 0
after continue > i= 0
before continue > i= 1
after continue > i= 1
before continue > i= 2
*/

Program 3.2.2 - If continue statement is used inside nested loops, than current iteration of innermost loop will be stopped,  flow of control reaches right to the start of innermost loop >
/** JavaMadeSoEasy.com */
public class StatementTest {
   public static void main(String[] args) {
          for (int i = 0; i < 3; i++) { //outer loop
                
                 System.out.println("outer i= " + i);
         
                 for (int j = 0; j < 3; j++) { //inner loop
                       if(j>0){
                              continue;
                       }
                       if (i > 0) {
                              continue;
                       }
                       System.out.println("inner i= " + i+", j= " + j);   
                 }//end inner loop
          }//end outer loop
         
   }
}
/* OUTPUT
outer i= 0
inner i= 0, j= 0
outer i= 1
outer i= 2
*/


Labeled continue statement>
So far we have used unlabeled continue statements, but now we will learn how to use labeled continue statements.
Program 3.2.3 to demonstrate labeled continue statement>
/** JavaMadeSoEasy.com */
public class StatementTest {
   public static void main(String[] args) {
          outerForLoop: // Labeled outer loop
                 for (int i = 0; i < 3; i++) {
                       System.out.println("outer i= " + i);
                      
                       innerForLoop: // Labeled inner loop
                              for (int j = 0; j < 3; j++) {
                                     if (j > 0) {
                                            continue innerForLoop;
                                     }
                                     if (i > 0) {
                                            continue outerForLoop;
                                     }
                                     System.out.println("inner i= " + i + ", j= " + j);
                              }// end inner loop
                 }// end outer loop
   }
}
/* OUTPUT
outer i= 0
inner i= 0, j= 0
outer i= 1
outer i= 2
*/




3.3) return statement

The return statement exits from the current method and control flow returns to where the method was invoked.

There are 2 types of return statement >

return statement that doesn’t returns value >  in this case return type of method must be void.

  • return statement that returns value > in this case data type of the returned value must match with the data type of the method's declared return value.

Program 3.3.1 to demonstrate return statement that doesn’t returns value>
/** JavaMadeSoEasy.com */
public class StatementTest {
   public static void main(String[] args) {
          m();
   }
  
   static void m(){ //return type of method is void.
          System.out.println("in m()");
          return; //return nothing
   }
}
/* OUTPUT
in m()
*/


Program 3.3.2 to demonstrate return statement that returns value>
Method returns int
/** JavaMadeSoEasy.com */
public class StatementTest {
   public static void main(String[] args) {
          System.out.println("m() has returned > "+m());
   }
  
   static int m(){ //data type of the method's declared return value is int.
          System.out.println("in m()");
          return 1; //data type of the returned value is int
   }
}
/* OUTPUT
in m()
m() has returned > 1
*/




3.4) goTo statement (not used)

goTo is a keyword in java, but not used.

It was added java 1.0 to be used in a later version of Java, but wasn’t implemented in java.

As goTo is not implemented, any attempt to use goTo will cause compilation error,

We can use labeled break (programs 3.1.3 ) or labeled continue (As used in above programs 3.2.3 ).


RELATED LINKS>

Primitive, Custom/reference Data Types, Integer, Floating-Point, Character and String literal, Escape sequence in java, decimal to hexaDecimal and binary conversion program


Arithmetic, Unary, Equality, Relational, Conditional, Bitwise, Bit Shift, Assignment, instanceof operators in detail with programs.


No comments:

Post a Comment