The body of a switch statement is known as a switch block. Any statement immediately contained in a switch block may be labeled with one or more case or default labels. The switch statement evaluates its expression and executes the appropriate case.
Switch Statement in Java
A switch case statement is a multiple-branching statement where, based on a condition, the control is transferred to one of the many possible points. The switch statement is useful when selecting some action from a number of alternatives. The switch statement allows for any number of possible execution paths.
The value inside the test expression is compared against the case labels that are constant expressions as in the following:
- If a match is found, the statements following the label are executed. Execution continues until a break is encountered that transfers control to the statement following the switch statement.
- If no match is found, control passes to the statements following the default label. The default label is optional, if no default label is provided, the switch statement does nothing when no match is found.
The following are the advantages of a switch case statement:
- Switch case is a faster execution.
- Easier to debug.
- Easier to understand.
- Easier to maintain.
Java Switch Example
- //code
- import java.util.Scanner;
- class demo
- {
- public static void main(String arg[])
- {
- int x= 0, y=0;
- Scanner sc=new Scanner(System.in);
- System.out.println("enter choice \n1.add \n2.sub \n3.mul \n4.div");
- int ch=sc.nextInt();
- switch(ch)
- {
- case 1:
- System.out.println("enter two number");
- x=sc.nextInt();
- y=sc.nextInt();
- x=x+y;
- System.out.println("result is="+x);
- break;
- case 2:
- System.out.println("enter two number");
- x=sc.nextInt();
- y=sc.nextInt();
- x=x-y;
- System.out.println("result is="+x);
- break;
- case 3:
- System.out.println("enter two number");
- x=sc.nextInt();
- y=sc.nextInt();
- x=x*y;
- System.out.println("result is="+x);
- break;
- case 4:
- System.out.println("enter two number");
- x=sc.nextInt();
- y=sc.nextInt();
- x=x/y;
- System.out.println("result is="+x);
- break;
- default:
- System.out.println("invalid number");
- }
- }
- }

Gowtham RajamanickamPosted May 19, 2015, 12:45 AM
keepgoing...
Gopi ChandPosted May 17, 2015, 2:21 AM
Nice article, keep it up..
Abhishek JaiswalPosted May 17, 2015, 1:47 AM
Keep going, good illustrations!! :)
Santhakumar MunuswamyPosted May 17, 2015, 1:00 AM
Thanks for sharing