Recent Posts

Thursday, 9 June 2016

Flow Control Tutorial

     
     Flow control describes the order in which the statements will be executed at run time.
Selection Statements

1. if_else
Syntax
if(a) {
    Action if a is true
} else {
   Action if a is false 
}
* The argument to the if statement should be boolean type. If we are providing any other type we will get compile error.

* Curly braces { } are optional and without curly braces we can take any one statement and which should not be declarative statement
E.g:
if(true) 
System.out.println("Hai this is Ashok"); // Hai this is Ashok

if(true) 
int x = 10; // Compile time error

if(true) {
    int x = 10; // Fine
}

if(true); // Fine
2. Switch statement
     If several options are possible then it is never recommended to use if-else, we should go for switch statement
Syntax
switch(a) {
case 1:
         Action 1;
case 2:
         Action 2;
      .
      .
      .
default:
         default Action;
}
* Curlly braces are mandatory

* Both case and default are optional inside a switch
E.g
int x = 10;
switch(x) {
}
* With in the switch, every statement should be under some case or default. Independent statements are not valid
E.g
int x = 10;
switch(x) {
   System.out.println("Hi this is Ashok"); 
}
C.E: case, default or '}' expected 
* Until 1.4v the allowed data types for switch argument are
1. byte
2. short
3. int
4. char

* But from 1.5V on wards in addition these corresponding wrapper classes (Byte, Short, Character, Integer) and enum types are allowed and 1.7V on wards String type is allowed

* If we are passing any other type we will get compile time error.

* Every case label should be with in the range of switch argument type otherwise we will get compile time error.
E.g
byte b = 10;
switch(b) {
   case 10:
           System.out.println("10");
   case 100:
           System.out.println("100");
   case 1000:                         // C.E: Possible loss of precision found: int required : byte [byte range is – 128 to 127]
           System.out.println("1000"); 
}
byte b = 10;
switch(b + 1) { // int type
   case 10:
           System.out.println("10");
   case 100:
           System.out.println("100");
   case 1000:                         // Fine
           System.out.println("1000"); 
}
* Every case label should be valid compile time constant , if we are taking variable as case label then we will get compile time error.
E.g
int a = 10;
int b = 20;
switch(b) {
case 10:
        System.out.println("10");
case y:                         // C.E: Constant expression required
        System.out.println("20"); 
}
Note
* If we declared y as final then we won't get any compile time error

* Expressions are allowed for both switch argument and case label but case label should be constant expression.
E.g
int a = 10;
switch(a+1) {
   case 10:
           System.out.println("10");
   case 10+1:                         
           System.out.println("11"); 
}
* Duplicate case labels are not allowed
E.g
int a = 10;
switch(a) {
   case 97:
           System.out.println("97");
   case 98:                         
           System.out.println("98"); 
   case 'a':                         // C.E: Duplicate case label
           System.out.println("a"); 
}
Fall Through inside switch 
     Within the switch statement if any case is matched from that case onwards all statements will be executed until break statement or end of the switch. This is called fall-through inside switch.
switch(x) {
case 0:
         System.out.println("0");
case 1:
         System.out.println("1");
         break;
case 2:
         System.out.println("2");
default:
         System.out.println("default");
}
Output:
If x = 0 -- 0, 1
If x = 1 -- 1
If x = 2 -- 2, default
If x = 3 -- default
* Fall through inside switch is useful to define some common action for several cases.
switch(x) {
case 3:
case 4:         
case 5:
       System.out.println("Summer");
       break;
case 6:
case 7:
case 8:
case 9: 
       System.out.println("Rainy");
       break;
case 10:
case 11:
case 12: 
case 1:
case 2: 
       System.out.println("Winter");
       break;      
}
Default Case
* We can use default case to define default action

* This case will be executed iff no other case is matched

* We can take default case any where within the switch but it is convension to take as last case.
E.g
switch(a) {
default:
        System.out.println("default");
case 0:                         
        System.out.println("0"); 
        break;
case 1:                         
        System.out.println("1"); 
case 2:                         
        System.out.println("2"); 
}
Output:
If x = 0 -- 0
If x = 1 -- 1, 2
If x = 2 -- 2
If x = 3 -- default
Iterative Statements

1. while
     If we don't know the number of iterations in advance then the best suitable loop is while loop.
E.g:
while(rs.next()) { // ResultSet
............
............
}

while(itr.hasNext()) { // Iterator
............
............
}
Syntax
while(boolean_value) {
Some Action
}
* The argument to the while loop should be boolean type. If we are trying to use any other type then we will get compile time error
while(1) { // C.E: Incompatible types found:int required: boolean 
System.out.println("Hai this is while loop");
}
* Curly braces { } are optional and without curly braces we can take any one statement and which should not be declarative statement
E.g:
while(true) 
System.out.println("Hai this is Ashok"); //Fine

while(true) 
int x = 10; // Compile time error

while(true) {
    int x = 10; // Fine
}

while(true); // Fine
E.g 2:
while(true) {
    System.out.println("Hi");
}
System.out.println("Hello"); // C.E: Unreachable code

while(false) {
    System.out.println("Hi");
}
System.out.println("Hello"); // C.E: Unreachable code
2. do-while
* If we want to execute loop body at least once then we should go for do-while loop
Syntax
do {
Some Action
}while(boolean_value); // Here ; is mandatory 
* Curly braces { } are optional and without curly braces we can take any one statement between do and while and which should not be declarative statement
E.g:
do 
System.out.println("Hai this is Ashok"); //Fine
while(true);

do; // ; is a valid java statement
while(true);

do
int x = 10; // C.E
while(true);

do{
int x = 10; 
}while(true); // Fine

do
while(true); //C.E (Compulsory one statement declare or take.)
3. For loop
* For loop is the most commonly used loop in java

* If we know the number of iterations in advance then for loop is the best choice
Syntax
for (initialization; condition; increment/decrement) {
    statement(s) //block of statements
}
* Curly braces { } are optional and without curly braces we can take any one statement and which should not be declarative statement
E.g:
for(int i=0;true;i++)
System.out.println("Hai"):

for(int i=0;true;i++);

for(int i=0;true;i++)
int x=10; // C.E
Initialization section
* This will be executed only once

* Usually we are declaring and performing initialization for the variables in this section

* Here we can declare multiple variables of the same type but different datatype variables we can't declare
E.g:
int i = 0, j = 0; // Fine
int i = 0, byte b = 0; // Error
int i = 0, int j = 0; // Error
* In the initialization section we can take any valid java statement including System.out.println() also
int i=0;
for(System.out.println("Hello");i<3;i++) {
System.out.println("Hai");
}

Output
Hello
Hi
Hi
Hi
Conditional Expression
* Here we can take any java expression but the result should be boolean type.

* It is optional and if we are not specifying then compiler will always places true.

Increment and decrement section
* We can take any valid java statement including System.out.println() also.
int i=0;
for(System.out.println("Hello");i<3;System.out.println("Ashok")) {
i++;
}

Output
Hello
Ashok
Ashok
Ashok
* All 3 parts of the for loop are independent of each other.

* All 3 parts of for loop are optional
E.g:
for( ; ; ); // Represent infinite loop
4. for-each() loop (Enhanced for loop)
* Introduced in 1.5V

* This is the most convenient loop to retrieve the elements of arrays and collections
E.g:
1. Print elements of single dimensional array by using general and enhanced for loops
int[] a = {10,20,30,40,50};
for-loop
for(int i=0;i<a.length;i++) {
System.out.println(a[i]);
}

for-each
for(int x:a) {
System.out.println(a[i]);
}
2. Print elements of 2-dimensional int array by using general and enhanced for loops
int[][] a = {{10,20,30},{40,50}};
for-loop
for(int i=0;i<a.length;i++) {
for(int j=0;j<a[i].length;j++) {
System.out.println(a[i][j]);
}
}

for-each
for(int[] x:a) {
for(int y:x) {
System.out.println(y);
}
}
* Even though for-each loop is more convenient to use, but it has the following limitations.
1. It is not a general purpose loop
2. It is applicable only for arrays and collection
3. By using for-each loop we should retrieve all values of arrays and collection and can't be used to retrieved a particular set of values

Transfer statements

1. break
* We can use break statement in the following cases
1. Within the switch to stop fall through
2. Inside loops to break the loop execution based on some condition
3. Inside labelled blocks to break that block execution based on some condition

* If we are break statement other than above cases then we will get compile time error
for(int i = 0;i<=10; i++) {
    if(i==5) 
         break;
    System.out.println(i);
}
2. continue 
We can use continue statement to skip current iteration and continue for the next iteration inside loops
for(int i = 0;i<=10; i++) {
    if(i%2==0) 
         continue;
    System.out.println(i);
}
* If we are using continue outside of any loops we will get compile time error.
Labelled break and continue statements
     In the case of nested loops to break and continue a particular loop we should go for labeled breka and continue statements
E.g
l1:
for(int i=0;i<3;i++) { 
   for(int j=0;j<=3;j++) {
      if(i == j)
         break;
      System.out.println(i+"  "+j);
   }
}

Output

break
1  0
2  0
2  1

break l1<
No output

continue
0  1
0  2
1  0
1  2
2  0
2  1

continue l1
1  0
2  0
2  1
Note 
     Compiler will check for unreachable statements only in the case of loops but not in if-else

Next Tutorial  Declarations & Access Modifiers

Previous Tutorial  Operators and Assignments

1 comment: