Saturday 8 November 2014

Control statements in java


As you can guess control statements in java if and else conditions and switch and case statements.
Control statements generally decide which way way to go based on the given condition or rule. In any programming language control statements are inevitable.
Now lets start with if and else statements.
General structure of if and else statements

if(condition){
     code goes here
}
else if(condition){         /* optional*/
         code goes here
}
else if(condition){         /* optional*/
           code goes here
}
.
.
.
.
.
else{                               /* optional*/
           code goes here
}
if statements always follows a condition enclosed in a parenthesis. If inside if statement only single statement is there, there is no need to use braces.
Else if and else conditions are optional
In java if and else if conditions are are checked sequentially, if at any time any if or else if condition satisfies it's condition, the code inside that particular condition executes and after that control comes out of the entire if and else block.
If no condition satisfies, code in else i=block is executed
Class if_and_else{
           public static void main(String args[]){
                    int a=10,b=11,c=12;
                    int x;
                    if(a>b){                      
                          x=a;
                       }
                    else if(b>a){
                              x=b;
                        }
                    else{
                          x=0;
                       }
                  System.out.println(x);
              }
}
Find out the output.
Output will be 11. Understand why it is 11
If and else statements can be nested also, i.e. within any if or else if or else block we can start another if and else block.
One we need to notice here is that, else and else if condition always precedes by else if or if condition.
Let's go through an example so that it will be clear.
Class nested_if_and_else{
         public static void main(String args[]){
                   int a=10,b=11,c=12;
                   int x;
                   if(a>b){                     
                          x=a;
                     }
                  else if(b>=a){
                                  if(b==a)
                                             x=0;
                                   else
                                             x=b;
                                    }
                    System.out.println(x);
              }
}
Try finding out output now.
Output will be same as before. Understand why it is so.
Here our logic checks whether a>b since that condition does not satisfies(10>11) control goes into else if statement it gets satisfied there it enters in and again there is one more if and else code. Here if b and a equals then x is assigned to 0 else x is assigned to b.

No comments:

Post a Comment