Execution Control in Java Simplified

Class Class 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 structures of these two types. They are as follows:

Ads code goes here
  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 a goto statement for the jump from one statement to another. It supports a finer approach for this goto.

Jump Statements in Java:-

Jump statements allow our code to work in a non-Linear-manner. The jump statements available in java are as follows:-

  • Break
  • Labelled break
  • Continue
  • Labelled Continue
  • Return

The objective of labeled block statement is used to terminate the block for which the label is specified in the break statement.

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 blocks. It is just a pair of two braces{}. The block of code is usually used to group several statements into logical boundaries 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. It 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.

When we use a Boolean expression in an if-else statement, the Boolean expression must be enclosed with a parameter.

if(expression){
statement
} 
if(testcondition)
statements 
if-else in java
if-else in java

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 

if-else styles

There are two styles of if-else. They are as follows:

  • Allman style
  • Kernighan and Ritchie style
READ  Abstract Interface Observer in Java
Allman Style:

This type of style is called the Allman style. They are easy to read and decode. It is named after Eric Allman.

if(myScore>yourScore)
{
System.out.println("I win");
}
else
{
System.out.println("you win");
}
Kernighan and Ritchie style

The second style is called Kernighan and Ritchie style(K&R style) after Demis Ritchie and Brian Kernighan. They are tough to read and need programming practice to decode.

if(myScore>yourScore){
System.out.println("I win");
}else{
System.out.println("you win");
}

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 a 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 a 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 an 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 truth or falsehood is called the loop control variable.

While:

while loop in java
while loop in java

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;
//initialize the i
while(number<10)//loop breaking condition
{
System.out.println("Hello World "+number);
number++;
}
}
}

The 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.

do while loop in java
do-while loop in java

In those cases, we need to use a do-while loop. In this case, the body of the loop executed first instead of checking the boolean expression. This is a 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 proceeds 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 repeats the process.

READ  How Memory Allocation Happens in Java?

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 an exit controlled loop.


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

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.

for loop in java
for loop in java

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 the 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 the assignment operator. They are known as loop control variables.

Condition:

Condition is to control the loop using a 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 them for a statement after the execution of the last statement in the loop. Now the control variable is increased or decreased using an assignment statement. The new value is again tested to check if it satisfies the loop condition.

If it does the body of the loop executed. This process continues until 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 the initialization section.

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

Additional features of a for loop:

    1. More than one variable can be initialized at a time in the for the statement. For the 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 a comma.
    3. The test condition may have compound relation and testing need not be on the loop control variable.

int sum=0;
for(int i=1;i<20&&sum<100;++i)
{
//sum is evaluated here
}
    1. One or more sections can be omitted.

int m=5;
for(;m!=100;){}
 

initialization, increment or decrement has to be present otherwise it will become an infinite loop.

we can set up 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 an 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 than 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

READ  Switch Case Simplified in Java

$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 a loop. This technique is called nesting of for loop. The loops should be properly indented to enable the reader to easily determine the loop logic.

Break and Continue:

While the loops wait for termination conditions to appear, 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.An if can not contain a break and continue but all the loop can have these keywords.

Plain break and continue:

They are used in the 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 the 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 the 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 lot of jumps in the flow. Even though in some situations goto is the best solution but ordering goto creates a lot of confusion 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 truly not jump statements but an effective and efficient way to go out of an iteration statement.

Share and Enjoy !

Leave a Comment

Your email address will not be published. Required fields are marked *