Sunday 3 March 2013

Loop Statements in Java

In last post we saw selection statements like if,if-else and switch. Now lets take a look at Loop statements also known as iteration statements.
So this category consist of  while, do while and for statements.Lets see each of them in detail.
  •  while loop - 

    Syntax for while statement is as follows -
    while(condition)
    {
        //Execute some code
    }
     Now lets see what above piece of code actually does.Code which is in the curly braces will keep on executing as long as condition is true.So there mush be some point in execution that the condition must go false only then the context comes out of the loop and proceeds with normal execution.If condition remains true forever the corresponding code will keep on executing unless you give a break statement.We will look into this break statement in detail in Transfer statements. We call this situation as infinite loop condition.Note  condition expression must evaluate to a boolean.

    Note : If you don't provide any curly braces first statement is taken as the code to be executed in while loop by default.If condition is false at the start of the loop, corresponding code will not be executed even once.
  •  do-while loop 

    Syntax for do while loop is as follows - 
    do{
    //Execute some code
    }while(condition)

    Above code will do the same thing as what while loop  does.It will keep on execution some code as long as  condition is evaluated to be true.

    So what is the difference between while and do-while loop?
    Answer is simple. If you observe in while loop we specify condition before the corresponding code whereas in do-while loop we specify it after the code.So if the condition is evaluated to be false while loop will not be executed whereas even if condition is evaluated to be false at the start of execution do-while loop will b executed once.So no matter what do-while loop will be executed at least once.
      
  •  For loop

    Syntax for for loop  is as follows - 
    for (<initialization>; <loop condition>; <increment expression>)
    {
         //Code to execute
    }
    Example
    for(int i=0;i<10;i++)
    {
        System.out.println(i + "\n");
    }
    Above code prints numbers from 0 to 9.Let us analyze it now.
    Inside you for loop first expression in initialization i.e you initialize some variables.Next expression is your looping condition i.e code in curly braces will be executed only when the looping condition is satisfied.Final expression is your increment expression where you increment or decrement variable so as at some point in execution of loop looping condition will not be satisfied and the loop will be terminated.In above code variable i of type integer.i=0 assigns value 0 to variable i.Then for each value of i ranging from 0 to 9 it just prints the value on standard output.When i becomes 10 it checks if i i.e 10 is greater that 10.No i.e loop condition is not satisfies.Terminate the loop and come out.

    Note: initialization is done only once at the start of the for loop.Loop condition is checked every time before entering the loop to execute corresponding code and increment/decrement expression is executed every time after a loop code is executed.

    Another way to use for loop is as follows
    String[] vehicle={'Car','bike','truck'};
    for(String x : vehicle)
    {
        System.out.println(x);
    }

    Above code iterates over all values in array vehicle and prints them to standard output.x here is a local variable to the loop and you can name it anything you want of-course sticking to naming conventions and taking care of scope.Above code will print Car bike and truck to standard output.

    One more thing if you write the following

    for(;;)
    {
       //Code to execute
    }

    it is completely legal.This is nothing but an infinite loop.This is same as doing

    while(true)
    {
       //execute some code
    }

    Note: if you are a C user you might try something like 
    while(1)
    {
       //do something
    }
    but as i mentioned earlier condition must evaluate to be of type boolean.So above code will throw an compile time error.So you need to use true instead of 1 to achieve infinite loop.

    In next post we will see transfer statements like break,continue etc.
     

     

Control flow statements in Java

To actually dictate how your program will run and which part of code should be executed when it is important to know control flow statements.Some of these are same as what we use in C or C++. So lets look into these statements.

There are 3 main categories of control flow statements -
  • Selection statements - if, if-else and switch.
  • Loop statements - while, do-while and for.
  • Transfer statements -  break, continue, return, try-catch-finally and assert.
Now lets look control flow statements in each category in a bit more detailed manner.

Selection statements

  • if statement -  Syntax for if statement is as follows -
    if(condition)
    {
         //code to be executed if condition is true
    }

    Lets analyze above code. We have if keyword followed by condition in brackets.This condition must evaluate to be true or false.If the condition evaluates to be true the code in the curly braces following the if statement is executed.If condition evaluates to be false this code is skipped.
  • if-else statement - Syntax for if-else statement is as follows -
    if(condition)
    {
         //code to be executed if condition is evaluated to be true
    }
    else
    {
         //code to be executed if condition is evaluated to be false
    }
    Very much same as if statement if we neglect the else part. If condition is evaluated to be true code in if part is executed and if condition is evaluated to be false code in else part is executed.
    You can have as many if else statements as you need. Moreover you can even cascade them as below -
    if(condition1)
    {
         if(condition2)
           {
                //condition to be executed when both condition1 and condition2 are true
           }
    }
    You may say above code is same as writing
    if(condition1 && condition2)
    {
         //execute some code
    }

    yes it will implement same logic as above but let sat you want to execute some code when condition1 is true and condition2 is false in order.In this case you have to use cascading method.
    Note - If order is not important you can do something like
    if(condition1 && !condition2){//Do something}
    ! is negation operator
    Also please keep in mind that whenever you write any code please stick to proper "indentation". It not only helps readability but will also help you read your own code better.
  • switch statement - switch statement is used when we know that a variable can take some n values and we need to execute some code corresponding to each value that the variable takes.
    Yes it same as using multiple if-else statements but switch statement gives more clarity and readability to the code.
    Syntax for switch statement is as follows
    switch(vehicle)
    {
       case 'bike' : System.out.println("I am on a bike");
                         break;
      case 'car' : System.out.println("I am in a car");
                         break;
      default : System.out.println("I prefer walking.");
    }

    Lets understand this code line by line.
    First we have switch keyword follower by a variable called vehicle which is of type String.If the vehicle has value bike then program will print I am on a bike on the standard output else if  vehicle has value car then program will print I am in a car on the standard output. If value of vehicle is neither bike nor car then it will go ahead and pick up default case and print I prefer walking.

    Note : I have used String in above case to help you understand how switch works but support for string is added only in Java SE 7 . So if you are using any JDK version before this String will not work. You can only have primitive data types like int, char etc.

    What is the break statement we keep writing in each case?

         break statement simply says if a case is selected and code corresponding to that is executed there is no need to check and cases after that. So just break out of switch statement and carry on with the execution.I have seen many beginners do this mistake. So just note this point.

    What if i miss this break statement?

    To explain this question lets go again to our example code.Lets say vehicle has value bike. So it prints
    I am on a bike .Now if you have not provided with break statement it will go ahead till end of switch statement or till it finds a break statement and execute code corresponding to all values except default of course.

    Important point to be noted in case of switch statement

    •  A switch works with the  byte, short, char, and int primitive data types. It also works with enumerated data types(will be discussed later).
    • default case is executed only when no other cases match. Also since it is the last one to be executed there is no need of break statement. Also position of default case in switch statement is irrelevant.
    • Also note that if variable used in switch statement is of integer type you don't have to put  single quotes like we did in vehicle case as it was of type String.Ex - case 1 : //execute something.
    • It is important to put a break statement in each case.

    We will look into Loop statements and  Transfer statements in next post.



t> UA-39527780-1 back to top