ConditionSWITCH CASE What we are going to study can be seen as an alternative to writing fromkondisi logika IF ELSE IF on the previous Java tutorial. However, not all IF ELSE IF conditions can be converted into SWITCH CASE form, which we will discuss in more detail.
Understanding SWITCH CASE Java Language
ConditionSWITCH CASE is a branch of program code where we compare the contents of a variable with several values. If the comparison process results intrue, then the program code block will be processed.
ConditionSWITCH CASE consist of 2 part, i.e. commandSWITCH where there is the name of the variable to be checked, as well as 1 or more ordersCASE for each value to be checked.
The following is the basic format for writing conditionsSWITCH CASE in Java:
At the beginning of the program code, there is an orderSWITCH to input the variable to be checked. Then there are some CASE commands followed by a value.
If the contents ofvariable_name equal to one of these values, then the program code block will be executed. If it turns out that none of the CASE conditions are met, blokdefault in the bottom row is what will be run.
In each block case, ends with an order break; order structure CASE immediately stop once the conditions are met. Let's see a practical example.
Java Language SWITCH CASE Program Code Example
In the previous tutorial, there is a program code to display values with structureIF ELSE IF. We will try to convert it to formSWITCH CASE.
Previously, the following code displays the value with the structureIF ELSE IF:
The same program can be converted into the formSWITCH CASE the following:
Program code results:
In line 10 there is a command to ask the user to input one of the letters between ‘A’ - ‘E’. The value of this letter is then stored into a variablescore which has been set with a data typechar.
ConditionSWITCH CASE starting on line 12. Here is the orderswitch (score) which means we want to check the contents of the variablescore. The entire SWITCH block is in parentheses starting with a row 12 until 30.
In line 13 there is an ordercase ‘A’: This means that if the variablescore contains the character 'A‘, then run the contents of the CASE block, i.e. commandSystem.out.println(“Keep!”). Then there is the orderbreak in line 15 so that other CASE structures do not need to be processed again.
In line 16 there is an orderCASE second, that iscase ‘B’:. Same as before, this block will be executed if the variablescore contains the letters ‘B‘. So on until‘E’ case : in line 25.
If it turns out that there is no suitable value, so block default in line 28 which will be executed.
1,013 total views, 4 views today