Switch Statement And If Else Ladder

Java has a builin multiway decision statement known as switch. The switch statement test the value of a given variable(Expression against a list of case values and when a match is found, a block of statement associated with the case is executed. The journal syntax of switch is:

switch(Expression)
{
            case value1:
                        block1;
                        break;
            case value2:
                        block2;
                        break;
            -----------------------
            -----------------------
            -----------------------
            default:
                        default block;
                        break;
}

The expression is an integer expression of characters value1, value2 are constant or constant expression and are know as case labels. Each of these values should be unique with in a switch statement.

class SwitchTest
{
            public static void main(String args[])
            {
                        int x = 2;
                        switch(x)
                        {
                                    case 1:
                                                System.out.println("One");
                                                break;
                                    case 2:
                                                System.out.println("Two");
                                                break;
                                    case 3:
                                                System.out.println("Three");
                                                break;
                                    default:
                                                System.out.println("Invalid");
                                                break;
                        }
            }
}


Else If Ladder : The general syntax of else if ladder is as follow:

if(condition)
{
          statement1;
}
else if(condition)
{
          statement2;
}
else if(condition)
{
          statement3;
}
else
{
          statement4;
}

Example:

class IfElseTest
{
          public static void main(String args[])
          {
                    int i = 0;
                    if(i == 0)
                              System.out.println("Zero bit");
                    else if(i == 1)
                              System.out.println("One bit");
                    else
                              System.out.println("Invalid Bit");
          }
}

Output : 

0 Comments:

Post a Comment