The switch / case:
The switch is useful when you need to manage a lot of if / else if / else. It has a shorter syntax and is more appropriate for this type of case.
Operation:
Code:
switch (variable)
(
case 'value1':
action1;
break;
case 'value2':
action2;
break;
case 'value3': 'value4':
action 3;
break;
default:
Action 4;
break;
)
Here in our example of how this instruction, we note the case 'value3': 'valeur4':. This line means that if the variable variable is either 'value3' or 'valeur4', then execute "Action 4". You can save as many values as you want. If no value matches, or the instructions contained in the default run block (s)
Here is our previous example (based on else if) translated with the switch / case:
Code:
public class Test
(
public int variable = 15;
public Test ()
(
switch (variable)
(
case 20:
System.out.println ( "The variable 'variable' is equal to 20");
break;
case 15:
System.out.println ( "The variable 'variable' is not equal to 20 and is equal to 15");
break;
case 10:
System.out.println ( "The variable 'variable' is not equal to 20 or 15 and is 10");
break;
default:
System.out.println ( "The variable 'variable' is not equal to 20 or 15 or 10");
break;
)
)
)
Negation:
The denial is used when one wishes, for example, say "if this variable is not equal to". You can use the operator! = (Which means "different") but you can also simply use the exclamation point, which means "no". Beware, the exclamation point applies to a Boolean variable (true or false), so you should put some brackets.
Example:
Code:
public class Test
(
public int variable = 15;
public Test ()
(
if (! (variable = 20))
(
System.out.println ( "The variable 'variable' is not equal to 20");
)
)
)
Bookmarks