Execution Control in Java Simplified

0
56
Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

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.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share