Execution Control in Java Simplified

Execution Control in Java
Execution Control in Java

Execution Control in Java Simplified:

When a program breaks the sequential flow and jumps to another part of the code, the technique is called branching. If branching takes place on a condition, it is called conditional branching. If the branching takes place without a decision, it is called unconditional branching.Java coding complexity is determined by control structures.There are mainly two control structures in java:

  1. branches
  2. loops

There are several six sub control structure of these two types. They are as follows:
  1. Block
  2. do while
  3. while
  4. for and for each
  5. if
  6. Switch




Java supports the following execution controls:

  • if
  • if else
  • While
  • do while
  • for
  • switch

Java does not support goto statement for the jump from one statement to another. It supports a finer approach for this goto.

Block:

The block is used to group a set of statements into a single statement. The statements are enclosed between a pair of braces.{}

{
statements
}
 
There could be a block with no statement. They are called empty block.It is just pair of two braces{}.The block of code is usually used to group several statement into logical boundary like a function.We can declare and define variables inside a block but they are local to block.Hence they are not visible or accessible outside of the block.Java allocates memory to the variables declared and defined inside a block.When the block is over,the memory is discarded by JVM to make room for other variables. Block statements do not affect the flow of control in a program.

True False:


All conditional statements use the truth or falsehood of a conditional expression to determine the execution path. However, Java does not support number as a boolean.

if statement:

It is the basic branching or decision technique in java.If is a two-way decision-making statement and it in conjunction with an expression."if statement" checks the true path and executes the statements if the expression is evaluated as true.

if(expression){
statement
}
 

if(testcondition)
statements
 
In this case, if the expression is evaluated as true then the statement block inside the if block will be executed. Otherwise, it will skip the statement inside if and continue execution.

if else statement:

"if else statement" checks the true path and executes the statements if the expression is evaluated as true. if the expression is evaluated as false, it will follow the else part and execute the statements present in the else part;

if(expression){
statement1
}
else
{
statement2
}

 
In this case, if the expression is evaluated as true then the statement1 block inside the if block will be executed. Otherwise, it will go to else part and execute the statement2 part.

if(testcondition)
statements-1
else
statements-2
 

it can also have nested if-else


if(testcondition1)
  if(testCondition2)
     statements-1
  else
   statements-2     
else
statements-3
 

we can also have else if ladder


if(testcondition1)
statement1
else if(testcondition2)
statement2
else if(testcondition3)
statement 3
else if
...
...
...
 

A statement block can be a single statement or a group of statements including method call.


if(flag){
int age=30;
calculatePF();
}
 

If can have more than one condition to evaluate.


if((x>y)&&(z>a))
 

Example of the nested if:


if (x>15)
   if(y>20)
     if(z>30)
       ....

 

An example of if else:



public class oddEvenTest{

     public static void main(String []args){
         int number[]={50,65,56,71,81};
         int even=0;
         int odd=0;
         for(int i=0;i<number.length;i++)
         {
             if((number[i]%2)==0)
             even++;
             else
             odd++;
         }
         
        System.out.println("No of odd-"+odd);
        System.out.println("No of even-"+even);
     }
}
 

Iterations/Loops:

The process of repeatedly executing a block of statements is known as looping.The statement is the block may be executed any number of times from 0 to infinite number. 
A loop consists of three stages:
  1. Starter
  2. body or block of code to be repeated
  3. Control statement
The control statement tests certain conditions and checks if the loop needs to be continued or terminated.
Depending on the position of a control statement a loop structure can be classified as :
  1. Entry controlled structure-conditions are tested before the start of the loop execution if the condition is not satisfied,the loop body will not be executed. like while and for
  2. Exit controlled structure-conditions are tested at the end of the body of the loop hence the body executed unconditionally for the first time.like do while

A looping process consists of the below steps:

The steps are:
  1. Setting and initialization of a counter
  2. Execution of the statement of the loop
  3. Test for a condition for execution of the loop.
  4. Increment/decrement the counter

Few words to remember :

  • If the loop goes on and on and never ends,it is called infinite loop.
  • A different value used in a loop to demark the real input value or to create a break condition of the loop is called Sentinel value.
  • Setting up different things so that the test in a while loop executed is called priming the loop.
  • A variable used to evaluate the true or false hood is called loop control variable.

While:

A while loop is an entry controlled loop statement.A while loop is used to execute a statement multiple times.The boolean expression is evaluated once at the beginning of the loop and again before each further iteration of the statement. The statements can be compound and mix of different expressions. But eventually, they will boil down to true or false.If it is true the body of the loop gets evaluated.Then it comes to evaluate the boolean expression.If it is true again the loop continues.It continues until the loop breaking condition arises. If it is false, the body is skipped.Java continues to execute the remaining statements.


initialization
while(Boolean-Expression)
{
statement
//or
statements
}
 
Example:

public class whileTest{

     public static void main(String []args){
        int number=1;
        //initailize the i
        while(number<10)//loop breaking condition
        {
        System.out.println("Hello World "+number);
        number++;
        }
     }
}
 
Output of the code:
$javac whileTest.java
$java -Xmx128M -Xms16M whileTest
Hello World 1
Hello World 2
Hello World 3
Hello World 4
Hello World 5
Hello World 6
Hello World 7
Hello World 8
Hello World 9

do While:

Sometimes,it is convenient to test a condition for continuation at the end of the loop,allowing some set of statements to be executed at the beginning instead of checking at the beginning.In those case,we need to use do while  loop.In this case the body of the loop executed first instead of checking the boolean expression.This is little different from the while loop. The difference between while and do while is that statement or statements in doing while will execute at least once.


initialization 
do
{
statement/statemenst
}
while(Boolean-expression);//note semicolon is the part of statement
 
When control reaches to do statement,the program proceed to execute the body of the loop first.At the end of the loop,the test condition in the while statement is evaluated.If the expression evaluates as true the control goes back at the beginning of the loop and repeat the process.If the condition expression is evaluated as false the loop gets terminated and control goes out of the loop.As the test condition is evaluated at the end of the loop , it is considered as exit controlled loop.

int i=0;
int sum=0;
do
{
sum=sum+1;
i=i+2;
}
while(sum<40 code="" i="">

For Loop:

For loop is entry controlled loop providing a more concise loop control structure. A for loop is equivalent to while loop but for certain type of problems,for is easier to apply and solve the issue.Any of the components may be empty in for loop. The expression is tested before each iteration and as soon as it evaluates false, the execution will continue at the line following the statement.At the end of each loop, the step executes.These make for loop very powerful.


for(initialization;Boolean-Expression;step info)
{
Statements
}
 
The for loop syntax is given below:

for(<initialization>;<condition>;<increment or decrement>){
statements
}
 

The components of for loop:

Initialization:

Initialization is used to initialize the set of variables first,using assignment operator.They are known as loop control variables.

Condition:

Condition is to control the loop using relational operator, check true or false.It determines when to exit from the loop.If the condition is evaluated to true the body of the loop is executed,otherwise the loop is terminated and execution control goes outside of the loop.

increment/decrement:

When the body of the loop is executed,the control is transferred back to the for statement after the execution of the last statement in th eloop.Now the control variable is increased or decreased using an assignment statement.The new value is again tested to check if it is satisfies the loop condition.If it does the body of the loop executed.This process continues till the value of the control variable fails to satisfy the test condition. So increment/decrement to evaluate after each iteration of the loop.This section is used to modify the variable used in in the initialization section.

If the condition is empty,it is treated as true.So the loop continues for ever until it is ended with some other keyword like break.
in this sense,while(true) is equivalent to for(;;)

Additional features of a for loop:

  1. More than one variables can be initialized at a time in the for statement.For initialization section all variables are separated by a comma.
  2. Like the initialization, the increment /decrement  section may also have more than one part separated by comma.
  3. The test condition may have compound relation and testing need not be on the loop control variable.
  4. 
    int sum=0;
    for(int i=1;i<20&&sum<100;++i)
    {
    //sum is evaluated here
    }
    
     
  5. One or more sections can be omitted.
  6. 
    int m=5;
    for(;m!=100;){}
     
    initialization,increment or decrement has to be present otherwise it will become an infinite loop.
we can setup time delay using two for loops

for(int i=0;i<10000;i++);
//or
for(int i=0;i<10000;i++)
{
;
}
 
The body only contains semicolon known as empty statement

Traditional Approach


String[] myData={"a","b","c"};
for(int i=0;i<myData.length;i++)
{
System.out.println(myData[i])
}
 

Upgraded for loop-for each loop:

The enhanced for loop also called for each loop helps us to retrieve the array of elements efficiently rather using array indexes.We can also eliminate the iterators in a for loop and retrieve the elements from a collection.
generic syntax:

for(type identifier:expression)
{
statements
}
 
where type is the data type or object used,identifier refers to the name of a variable and expression is an instance of the java.lang.Iterable interface or an array.


import java.util.*;
public class ForEachTest{

     public static void main(String []args){
        int[] numArray=new int[]{56,48,79};
        //for loop output
          System.out.println("The selected values using for loop");
        for(int i=0;i<3;i++)
        {
            if(numArray[i]>50&&numArray[i]<100)
            System.out.println("The selected value "+numArray[i]);
        }
        //this is equivalent to
        System.out.println("The selected values using for each loop");
        for(int k:numArray)
        if(k>50&&k<100)
            System.out.println("The selected value "+k);
        Stack myStack=new Stack();
        myStack.push(new Integer(56));
        myStack.push(new Integer(48));
        myStack.push(new Integer(79));
        System.out.println("The selected values using for each loop for container");
        for(Object obj:myStack)
        System.out.println("The selected value "+obj);
        //arralist
        ArrayList<String> myCities=new ArrayList<String>();
        myCities.add("Delhi");
        myCities.add("Kolkata");
        myCities.add("Hyderabad");
        for(int j=0;j<myCities.size();j++)
        System.out.println("The selected value "+myCities.get(j));
        //equivalent to
        for(String city:myCities)
        System.out.println("The selected value "+city);
        
     }
}

 
The output of the code above

$javac ForEachTest.java
Note: ForEachTest.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
$java -Xmx128M -Xms16M ForEachTest
The selected values using for loop
The selected value 56
The selected value 79
The selected values using for each loop
The selected value 56
The selected value 79
The selected values using for each loop for container
The selected value 56
The selected value 48
The selected value 79
The selected value Delhi
The selected value Kolkata
The selected value Hyderabad
The selected value Delhi
The selected value Kolkata
The selected value Hyderabad

Nesting of for loops:


for(int i=0;i<10000;i++)
{//outer loop
......
......
        for(int j=0;j<10000;j++)
        {//inner loop
        ............
        ............
         }
}
 

One for loop can go inside another for loop. This technique is called nesting of  for loop.The loops should be properly indented so as to enable the reader to easily determine the loop logic.


Break and Continue:

While the loops wait for termination conditions to be appeared,java allows us to terminate the loop by two keywords,break and continue.A break breaks out of a loop. While a continue tells a compiler to skip the rest of the code of the current iteration and continue with next iteration.A if can not contain a break and continue but all the loop can have these keywords.

Plain break and continue:

They are used in mainly loop.break quits the loop without executing the rest of the statements in the loop. continue stops the execution of the current iteration and goes back to the beginning of the loop to begin a new iteration by increasing the counter by one.

for(int i=0;i<100;i++)
{
if(i==75) break; //out of the loop
if(i%9!=0) continue;//next iteration
} 
 

Labeled break and continue:

A label is an identifier followed by a colon like LabelName:.It is an upgraded version of break.
The only place a Label is useful in java is right before an iteration statement. However, it does not do much good for the coder. We can not insert any other statement here. The reason to put a label before an iteration is, if we are going to nest another iteration or a switch inside it.break and continue keywords will normally interrupt only the current loop, but when used with a label, they will interrupt the loops up to where the label exists.

label:
outerIteration{
   InnerIteration{
         .....
         break;//breaks the inner iteration and control comes back to outer Iteration
         ...
         continue;//continue iteration two
         ....
         ....
         continue label://continue label breaks out of the inner iteration but starting
                         // at the outer iteration all the way back to label. Then it starts 
                         //execution from there
         .....
         .....
         break label: //break label also breaks all the way out label but does not re enter 
                      //the iteration.It actually breaks out both the iteration
}
It starts the next iteration in a loop. Mainly applied to a jump statement to control the loop to go to the top of the loop again. Any statement(s) after continue statement is ignored or skipped.

loop myLoop
{
if(condition)
statement-1;
statement-2
 if (anotherCondition)
continue;// control goes to to myLoop and next section is ignored if anotherCondition is true
  else{
      statement-3
      statement-4
      }
else
statements;
}
 

Goto statement: Unconditional Jump:


goto is an unconditional jump as a result it creates a lots of jumps in the flow. Even though in some situation goto is the best solution but ordering goto creates a lot of confusions and issues.Java reserved the goto keyword but does not use it or in other words  java has no goto.Java treats break and continue as a replacement of goto. They are truely not jump statements but an effective and efficient way to go out of an iteration statement.

Execution Control in Java Simplified Execution Control in Java Simplified Reviewed by Animesh Chatterjee on December 27, 2018 Rating: 5

No comments:

Powered by Blogger.