Translate

Friday 15 August 2014

Conditional Statements (if else switch)

If else statements:-

If, else, switch statements are formed using boolean expression and they are used to alter the sequence.

e.g
if( a>=90 && a<=100 )
   System.out.println("A grade");
else if( a>=80 && a<90)
   System.out.println("B grade");
else
   System.out.println("Fail");

Here if variable a lies in 90-100 (including both than it will print A grade).
Here && stand for logical AND which means both conditions a>=90 AND a<=100 should be true for if condition.

Instead of && we can also use || which is logical OR.
if( a<0 || a>0 ) means either a should be less than zero OR a should be greater than zero.

! stands for logical NOT

== is used for equality check and single = is used as assignment so always use  == (double equal to) for equality check.

else if condition is checked if, if condition above it is false.
else condition is checked if, if or else if condition above it is false.


Switch statements:-

If else is used for a condition check on set of values. Switch case is used for a specified value check.
e.g
switch(a)     //here a can be integer or character type only.
{
     case 1:  ..........
                 break;
     case 2:  ..........
                 break;
     default:  ..........
                 break;
}

Here if a is 1 then compiler goes to statements written in case 1 and starts executing. It runs till it finds break.


default is executed when above all cases are not true.
switch(a)
{
     case 1:  ..........
               
     case 2:  ..........
                 break;
     default:  ..........
                 break;
}
Here for case 1 statements in case 1 and 2 both will be executed as there is no break in case 1.

No comments:

Post a Comment

Total Pageviews