There are two methods in Java that are often used for conditional judgment, one is if{}else{} and the other is switch (). In general, because switch can meet the conditions directly to one, the condition is not fulfilled, so the efficiency of switch will be higher than if{}else{}, and the two methods can be non-threshold interchange.
Use of switch:
- The types that can be used for switch judgments are: Byte, short, int, char (JDK1.6), and enumeration type, but after JDK1.7, the string type is added.
- The case statement writes less break, the compilation does not error, but it is executed all the time after the statement in the case condition is no longer judged until the default statement
- If you do not have a qualifying case to execute the code block under Default, default is not required, or you may not write
Switch(Mark) { Case 0: System. out. println (Mark); Break; Case Ten: System. out. println (Mark); Break; Case -: System. out. println (Mark); Break; }
Here the mark value is the judging condition, the case corresponds to the specific value, if mark=0 or mark=10 or mark=20, the corresponding conditions will be executed in the program
Here is a misconception that is prone to error, see the following code:
Switch(Mark) { Case 0: System. out. println (Mark); Mark = 10; Break; Case Ten: System. out. println (Mark); Mark = 20; Break; Case -: System. out. println (Mark); Mark = 30; Break; }
This code will be re-assigned to mark in each case compared to the above code, so that the re-assigned value corresponds to the next case.
false thinking: If Mark's initial value is 0, the switch program executes three times and the order of execution is 0,10,20.
Because we re-assigned mark in each step of the case, it's easy to think that the switch will be executed from the top down and all the steps that satisfy the condition will be executed. In fact, this switch is only executed once, because each case is followed by a break, the function of this break is to jump out of the current loop, that is, to jump out of the current switch, so this switch will only execute the mark initial value corresponding to the case, The subsequent steps do not continue. If you want to perform the three steps in turn, you need to add a while loop outside of the switch, and repeatedly execute the switch in a certain condition: the following plus while
while(mark<= -) { Switch(Mark) { Case 0: System. out. println (Mark); Mark=Ten; Break; Case Ten: System. out. println (Mark); Mark= -; Break; Case -: System. out. println (Mark); Mark= -; Break; } }
Summary: Each time you enter switch, if each case is followed by a break out of the current loop, then no matter how the mark's value changes, only one is executed
Use of switch in Java and thinking carding