Switch Statement in Java


The switch statement is Java's multi-way branch statement. It is used to take the place of long if-else chains, and make them more readable. However, unlike if statements, one may not use inequalities; each value must be concretely defined.

There are three critical components to the switch statement:

  • Case: This is the value that is evaluated for equivalence with the argument to the switch statement.
  • Default:This is an optional, catch-all expression, should none of the case statements evaluate to true.
  • Abrupt completion of the case statement; usually break: This is required to prevent the undesired evaluation of further case statements

Syntax:
     switch ( expression )
    {
    case 1 :
         // Block of Statement
         break;
    case 2 :
         // Block of Statement
         break;
    case 3 :
         // Block of Statement
         break;
    case 4 :
         // Block of Statement
         break;
     .
     .
     default :
         // Block of Statement
         break;
    }

Source Code

import java.util.Scanner;
 
//Switch Case Statement in Java
public class switch_demo {
    public static void main(String args[]) {
        int a,b,c,ch;
        System.out.println("1.Addition");
        System.out.println("2.Subtraction");
        System.out.println("3.Multiplication");
        System.out.println("4.Division");
        System.out.println("Enter Your Choice : ");
        Scanner in =new Scanner(System.in);
        ch=in.nextInt();
        System.out.println("Enter 2 Nos : ");
        a=in.nextInt();
        b=in.nextInt();
        switch (ch)
        {
            case 1:
                c=a+b;
                System.out.println("Addition : " +c);
                break;
            case 2:
                c=a-b;
                System.out.println("Subtraction : "+c);
                break;
            case 3:
                c=a*b;
                System.out.println("Multiplication : "+c);
                break;
            case 4:
                c=a/b;
                System.out.println("Division : "+c);
                break;
            default:
                System.out.println("Invalid Selection");
                break;
        }
    }
}
 

Output

1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter Your Choice :
3
Enter 2 Nos :
12
8
Multiplication : 96
To download raw file Click Here
`

Basic Programs