A switch statement is used to test a value against a list of value. The values are checked for each of the cases. And if a match is found. Then the corresponding statement will be executed.
Some important points to be noted about switch case are given as.
1:- It can only work for equality comparison.
2:- No two case labels in a switch can have some values.
3:- It works with integral type an also with char.
4:- It is much more efficient then nested if - Else Statement.
The syntax of Switch case statement is given below.
switch (expression)
{
Case value 1 : Statement 1 ;
break ;
Case value 2 : Statement 2 ;
break ;
Case value 3 : Statement 3 ;
break ;
....................... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . And Continue
default : default Statement ;
}
Here, the value of these expression is compared with a value corresponding to the case . If a match is found , the statements corresponding to that particular cases will be executed.
The break Statement is used to break the flow of the execution of the program, and the statement following the switch will be executed.
The default keyword is used when none of the case value matches the value of the expressions. Then the statement following the default will be executed. No break statements is required in default cases.
Taking user input in Java
To take input from the user , you can use InputStreamReader class by importing its packages in the program like given below:-
import java .io.*;
Here , the import statement is used to include the specified packages in a program. This statement is included at the top of a program. To access packages, you use the import line or statement.
إرسال تعليق