Switch Statements.pptx

EnricoValdez3 23 views 9 slides Oct 24, 2022
Slide 1
Slide 1 of 9
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9

About This Presentation

A slide show presentation about switch statements in java


Slide Content

Switch Statements By Enrico Valdez Credit: Jin Castor

W hat is a switch statement? The switch statement provides another way to decide which statement to execute next, which is similar to an if statement. However if statements are two way statements while switch statements are multiway statements meaning it can check more then true or false . The switch statement evaluates an expression, then attempts to match the result to one of several possible cases. Match must be an exact match to execute the code within the within the switch statement.

Syntax of a switch statement A Switch statement contains an expression, cases, breaks, and a default. The expression is a variable for which the cases check if they have the same value. Case statements are written with the word case and the value that you want to compare with the expression written next to it. A break statement jumps to the end of the switch statement so that the code does not have to run all of the cases, if it is already true for one. Defaults are the else statements of switch statements they are executed if none of the cases are correct.

to Switch or not to Switch the value of a case cannot be a variable, boolean, float, or a double The case values can also not repeat Break statements and Defaults are not necessary when writing switch statements.

Syntax of a switch statement cont.

Flow of Control The flow of control transfers to the statement associated with the first case value that matches. If a break statement is not used, the flow of control will continue into the next case until it reaches a break statement.

Tracing #1 This will go through every case and only print the default as none of the cases match the expression.

Tracing #2 This will only check the first two case statements because the break statement ends the switch statement. The third case and the default statement will not be checked. *case statements do not have to be in numerical order

Tracing #3 Even though the first case was true the second statement will still print because there was not a break statement in the first case .