Pages

Monday 30 September 2013

Control Statements in Java


Decision Making and Branching statements:


a)    If statement
b)    If-else statement
c)     Nested if-else statement
d)    If-else-if ladder statement
e)    Switch statement
f)      Nested Switch statement


These above statements are used for performing decision making and branching executions in java programs.


a)     if statement:

                      
General syntax of if statement:



          if(condition)

            {

                  Statement1;

                   ………..

                   Statement N;

            }


The condition in the if  block is any expression which can be evaluated to Boolean value, true/false. If the condition is evaluated has true then the statements in the if block is executed. If condition evaluates to be false then the if block is ignored. 



Example program implementing if statement:

/** program implementing if
 *
 *
 * @author Jaivanth
 *
 */
public class SampleIfStatement
{
   public static void main(String[] args)
   {
               int a=200;
               int b=600;
               int c=800;
               int temp=b;
              
               if(a>b)
               {
                           temp=a;
               }
              
               if(temp>c)
               {
                           System.out.println("greater is "+temp);
               }
              
               if(c>temp)
               {
                           System.out.println("greater is "+c);
               }
              
               if(a==b&&b==c&&c==a)
               {
                           System.out.println("all are equal & value is "+temp);
               }
           
   }
}




b)    If-else statement:

                             This statement is used for two way branching.

General Syntax:



                   if(condition)

                   {

                      Statement1;

                       ……………..

                      Statement N;

                    }

                 else

                 {

                     Statement1;

                      ………………

                     Statement N;

                  }

If the condition evaluates to be true then, if block statements are executed. If the condition is false, else statements are executed.


Example program implementing if-else statement: 


/** Program implementing if else
 *
 *
 * @author Jaivanth
 *
 */
public class SampleIfElseStatements
{
   public static void main(String[] args)
   {
                int a=100,b=50,c=30,temp;
               
                if(a>b) // if-else block
                {
                        temp=a;
                }
                else
                        temp=b;
               
                if(temp>c) //if-else block
                {
                        System.out.println("greater value is "+temp);
                }
                else
                        System.out.println("greater value is "+c);
               
   }
}


c)     Nested if-else statement:

                              If block inside a if block forms the nested if block statements. 

 General Syntax:

                    if (condition)

                    {

                       if (condition-inner)

                          statement;

                      else statement;

                        ……….

                       If(condition)

                     ……….

                   }

                   else

                     statement;



Example Program implementing Nested if-else statement: 


/** Program implements Nested if-else
 *
 * @author Jaivanth
 *
 */
public class NestedIfElseStatement
{
   public static void main(String[] args)
   {
              int a=10,b=40,c=30;
             
              if(a>b)
              {
                          if(a>c)
                          {
                                      System.out.println("greater is "+a);
                          }
                          else
                                      System.out.println("greater is "+c);
              }
              else
              {
                          if(c>b)
                          {
                                      System.out.println("greater is "+c);
                          }
                          else
                                      System.out.println("greater is "+b);
              }
   }
}


d)    If-else-if ladder statement:

                     
General Syntax:



                    if(condition)

                    {

                     Statement 1;

                     …………………

                     Statement N;

                    }

                    else if(comdition)

                    {

                      Statement1;

                      ………………..

                      Statement N;

                    }

                     ………………..

                     else

                     statements;

The if-else-if ladder is executed from top to bottom. If the condition of anyone of the if is found true in the ladder then the corresponding if statement is executed and remaining all the ifs are bypassed. If none of the ifs are true then the else statement at the end of the ladder is executed. If else is not present at end of the ladder, no action is performed.
 

Example Program for if-else-if statement:

 /**

 * Bonus is added to employees of a company depending on the

 * employees designation

 *

 *

 * @author Jaivanth

 *

 *

 *

 */

public class SampleIfElseIFLadder

{

    public static void main(String[] args)

    {

                String s="ASE";

                double salary=20000.00;

                double NewSalary=0;

               

                if(s=="ASE")

                {

                        NewSalary=salary+1000;

                }

                else if(s=="SE")

                {

                        NewSalary=salary+3000;

                }



                else if(s=="Manager")

                {

                        NewSalary=salary+6000;

                }

                else

                        System.out.println("No such Designation found");

               

                System.out.println(s+" new salary is "+NewSalary);

            }

}


e)    Switch statement:

                     It is executed from top to bottom. This statement is used for multi-way branching. It’s similar to if-else-if ladder, but easier than if-else-if ladder to implement. If the expression in switch statement evaluates to anyone of the case present in switch block, then that case is executed and execution follows downwards. The break statement is used to control the transfer out of the switch block.   

General Syntax:



       switch(expression)

       {

           case value1:

               Statement;

               break;



           case value2:

               Statement;

               break;

               …………

               …………

           Case valueN:

              Statement;

              break;

            default:

              //default statement;

         }


Example program for switch statement:
 

/** Simple Calculator program
 *
 *
 * @author Jaivanth
 *
 *
 */

public class SampleSwitchStatement
{
  public static void main(String[] args)
  {
             char ch='+';
             double a=15.68,b=12.56;
             double result=0;
             
             switch(ch)
             {
             case '+':
                         result=a+b;
                         break;
           
             case '-':
                         result=a-b;
                         break;
                         
             case '*':
                         result=a*b;
                         break;
                         
             case '/':
                         if(b!=0)
                         result=a/b;
                         if(b==0)
                         System.out.println("denominator is zero, division will be invalid");
                         break;
             default:
                         System.out.println("operator not valid");
                    
             }
             if(b==0&&ch!='/')
             System.out.println("Result of "+a+ch+b+"= "+result);
             else
                         System.out.println("Result of "+a+ch+b+"= "+result);
           
  }
}



f)      Nested Switch statement:
 
                            
          The switch statement inside a switch statement form nested switch statement.

Code fragments showing nested switch statement.

switch (a+b)

{

case 1:

        switch (sum+a+b)

          {

            Case 1:

               system.out.println(“execute”);

               break;

               …………..

               default:



               system.out.println(“execute this”);

           }

case 2:

………..

case N:

default:

          system.out.println(“it’s the end”);

}



    
Decision making and Looping Statements or Iteration Statements:

a)    While statements
b)   Do-while statements
c)    For statements

The above statements are capable of making decision whether or not to perform iteration.

a)    While statements: 

                            This statement repeats its block until the control expression or condition governing the loop evaluates to false.

General Syntax:



      while(condition)

      {

         //Body of loop

                   }

     The while loop repeats itself until the condition is true.


Example Program for While statement: 


/**Program to find give number is prime or not
 * and implementing while
 *
 *
 * @author Jaivanth
 *
 *
 *
 */
public class SampleWhileStatement
{
   public static void main(String[] args)
   {
              int n1=87,i=2;
              int mid=0,result=0;
             
              mid=n1/2;
             
              while(i<mid)
              {
                        result=n1%i; 
                        if(result==0)
                        {
                                    System.out.println(n1+" is not prime");
                                    break;
                        }
                        i++;
              }
              if(result!=0)
                          System.out.println(n1+" is prime");
             
              }
}


b)   Do-while statements:

                                     Sometimes there will be requirement where you have to allow the loop to execute at least once its body before checking the control condition of the loop. In this context do-while is used. 

           General Syntax:

                   do {

                  //body of loop

                     }while(condition)

                        
                                 As you can see in the syntax at least once the body of do-while is allowed to execute before checking the while condition. 


c)    For statements:

  There are two forms of for statements or loops in Java.

  •        Regular for loop
  •        For each for loop

               The regular for loop is common for loop which you may have used in many other programming languages like C/C++. 

       General Syntax of normal for loop:

                      for (initialization; condition; iteration)

                       {

                          //body of loop

                        }

Let us take a closer look at how this for loop will work. 

a)    First the for loop variable is initialized.

b)    Secondly the for loop condition is checked. If the condition satisfies or the condition returns Boolean value true then the for executes the body for the first time. If condition is false then the for loop is ignored. 

c)     Thirdly when the end of the for is reached the variable value is incremented or decremented. Again the control is transferred to beginning of the loop. The condition is checked again, if satisfied or true then loop is repeated for next iteration. The iteration takes place until the condition fails or Boolean false is returned. 



Example Program of the for loop:
 

/** program implementing for
 *
 *
 *
 * @author Jaivanth
 *
 *
 *
 */
public class SampleForStatement
{
            public static void main(String[] args)
            {
           

    int a[]=new int[20];
    int k=0;
   
      for(int i=0;i<20;i++)
      {
            a[i]=k;
            k++;
      }
     
      for(int i=0;i<20;i++)
      {
              System.out.println("Array elements are "+a[i]);
      }
     
            }
}



The For Each Loop:

                        The for each loop is introduced to java from the beginning of JDK 5.

                     General Syntax:



                        for(type variable:collection)

                         {

                         //body of loop

                     }                      


               This kind of for loop is very useful in iterating values of collections like arrays or collections from collection frameworks.


Example Program for For-Each loop: 

/** Program for For Each
 *
 *
 *
 * @author Jaivanth
 *
 *
 *
 */
public class SampleForEachStatement
{
   public static void main(String[] args)
   {
              int a[]={7,3,4,5,6,8};
             
              int key=8;
              boolean x=false;
             
              for(int y:a)
              {
                         if(y==key)
                         {
                                     x=true;
                                     break;
                         }
                         
              }
              if(x)
                          System.out.println("value is present in array!! hurray!!");
              else
                          System.out.println("not found");
             
   }
}


Jump Statements:

Break: This is mainly used to control transfer out of the loop or branch.
            // code fragments
           if(x==0)
           {
             //I am happy
           break;  
         }

Continue:  This is used to skip the iteration value of loop and continue with the next iteration value. 

Return: This statement is used explicitly to return the control to the calling method from the called method.