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 or default labels. The switch statement evaluates its expression and executs the appropriate case.
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 the are the advantages of a switch case statement:
- Switch case is a faster execution.
- Easier to debug.
- Easier to understand.
- Easier to maintain.
Example
-
-
- 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");
- }
- }
- }
Step 1Name it "add.java"and save the file in any location. I saved it at "c:/kiran/program".
Step 2
Set the paath. Without the path setting our Java file is not compiled.
Step 3
Set the path (path set means where you save your Java file).
Step 4
Now write the following code for checking whether or not the Java file is compiling.
javac add.javaMy Java program compiled successfully.
Step 5
Write the following code in a command prompt. Press Enter and see the output.
Java demo// demo is a class name which is written in my "add.java" file.
Output
Step 6
Continue in output and see the full output.
I hope you like this file.
Happy coding.