Switch... Case statement usage
public class Test7
{
public static void main(String[] args)
{
int i=5;
switch(i)
{
case 1:
System.out.println("one");
case 10:
System.out.println("ten");
case 5:
System.out.println("five");
case 3:
System.out.println("three");
default:
System.out.println("other");
}
}
}
The result is:
Five
Three
Other
Switch (expression)
{
Case constant expression 1: Statement 1;
....
Case constant expression 2: Statement 2;
Default: statement;
}
The switch is used to determine whether the expression after the case matches the expression after the switch. Once the case matches, the code after the switch is executed sequentially, regardless of whether the subsequent case matches, until the break is met.
In the code given above, because I is equal to 5 and does not match the previous two cases, there is no one or ten in the result. In the third case, 5 matches the I value in the switch, so five is printed. Since break is not encountered, the code is executed in sequence, print three and other
The switch-case statement in Process Control has always been a weakness of mine.
Every time I take an exam or take a test in an interview, the second monk is confused. I think this should be the reason why my foundation is too poor!
To completely solve this heart disease, you have to spend some time!
First, we will discuss the problem from the principle:
Switch (expression)
{Case constant expression 1: Statement 1;
....
Case constant expression 2: Statement 2;
Default: statement;
}
1. Default is executed if there is no matching case. Default is not required.
2. The statement after case does not need braces. The constant expression constant expressions must be followed by case. The error format is case X.
3. The conditions for the switch statement can be int, byte, Char, short, or enum.
4. Once the case matches, the subsequent program code will be executed sequentially, regardless of whether or not the subsequent case matches until the break is met. This feature allows several cases to execute unified statements.
Here are some examples of obfuscation.
1. Standard Type (break statements are available after case)
int i=3;
switch(i)
{
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
default:
System.out.println("default");
break;
}
Output result:
3