Switch Statement

Switch Statement
JAVA has a built-in multiple-branch selection statement called switch, which successively tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constant are executed. The general form of the switch statement is:
switch (expression)
{
case constant1
:statement sequence
break;
case constant2
:statement sequence
break;
case constant3
:statement sequence
break;
.
.
.
default
statement sequence
}



SAMPLE PROGRAM:-
public class SwitchExample{
  public static void main(String[] argsthrows Exception{
    int x, y;

x = 2 ;
y = 4 ;
      System.out.println("1. Add");
      System.out.println("2. Subtract");
      System.out.println("3. Multiply");
      System.out.println("4. Divide");
      System.out.println("enter your choice:");
      int a= 3;
      switch (a){      
        case 1:
           System.out.println("Enter the number one=" (x+y));
           break;
        case 2:
          System.out.println("Enter the number two=" (x-y));
          break;
        case 3:               \\ This code will be executed bcoz a = 3
          System.out.println("Enetr the number three="(x*y));
          break;
        case 4:
          System.out.println("Enter the number four="(x/y));
          break;
        default:
          System.out.println("Invalid Entry!");
      }
    }

Comments

Popular posts from this blog

NICOSIA