The Switch Statement
by
, January 29th, 2012 at 04:46 PM (1197 Views)
It's to my understanding that the Switch Statement is used as a means of saving time. If you want to test multiple conditions, but are looking for a more efficient way of doing things than using the If or Else If Statements, the Switch Statement is the way to go. I have trouble remembering what the switch statement means because I fail to make its connection to the 'case' keyword. The 'case' is the most important part of the switch statement. I know I'll be able to remember to use the switch statement more frequently if I can realise its relationship with the 'case' structure. Basically, think of switch; think of case.
Switch Statement
Note: The 'break;' isn't always going to be present. You only use break if you want to exit the Switch Statement if the current condition proves true. In some situations, it will pay to go through several conditions of the Switch Statement regardless of whether the current one is true or not. However, in most cases, the 'break;' will be necessary.switch(variable){ case firstcondition: instructions if firstcondition is true... instructions if firstcondition is true... instructions if firstcondition is true... break; case secondcondition: instructions if secondcondition is true... instructions if secondcondition is true... instructions if secondcondition is true... break; case thirdcondition: instructions if thirdcondition is true... instructions if thirdcondition is true... instructions if thirdcondition is true... break; default: instructions if all above conditions are false... instructions if all above conditions are false... instructions if all above conditions are false... break; }
Java Example