Java Switch Statement
The Java switch statement executes one statement from multiple conditions. A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.
The following rules observe a transfer statement:
- The variable used in a transfer assertion can best be a byte, brief, int, or char.
- you may have any range of case statements inside a switch. every case is accompanied by means of the value to be compared to and a colon.
- The fee for a case needs to be the same records type because the variable in the switch and it should be consistent or a literal.
- when the variable being switched on is equal to a case, the statements following that case will execute until a wreck assertion is reached.
- when a destroy assertion is reached, the transfer terminates, and the float of manage jumps to the following line following the switch declaration.
- now not each case wishes to include a spoil. If no destroy seems, the float of control will fall thru to subsequent instances until a smash is reached.
- A switch assertion will have an optional default case, which ought to seem at the top of the transfer. The default case may be used for appearing in an undertaking when not one of the instances is proper. No spoil is needed in the default case.
Java Switch Statement Example
switch (variable/expression)
{
case value1:
// statements
break;
case value2:
// statements
break;
.. .. ...
.. .. ...
default:
// statements
}
}
class my
{
{
public static void main(String[] args)
{
int D = 2;
int D = 2;
String day;
switch (D)
{
case 1:
day = "Sunday";
break;
case 2:
day = "Monday";
break;
case 3:
day = "Tuesday";
break;
case 4:
day = "Wednesday";
break;
case 5:
day = "Thursday";
break;
case 6:
day = "Friday";
break;
case 7:
day = "Saturday";
break;
default:
day = "Invalid day";
break;
}
System.out.println(day);
}
}
}
Output: Monday
No comments:
Post a Comment