Switch
Anonymous contributor
Anonymous contributor3071 total contributions
Anonymous contributor
Published Aug 4, 2021Updated Nov 5, 2022
Contribute to Docs
A switch
statement provides a means of checking an expression against various case
statements. If there is a match, the code within starts to execute. The break
keyword can be used to terminate a case.
There’s also an optional default
statement marking code that executes if none of the case
statements are true.
Syntax
A switch
statement looks like:
switch (expression) {
case x:
// Code block
break;
case y:
// Code block
break;
default:
// Code block
}
- The
switch
keyword initiates the statement and is followed by()
, which contains the value that each case will compare. In the example, the value or expression of the switch statement isgrade
. - Inside the block,
{}
, there are multiple cases. - The
case
keyword checks if the expression matches the specified value that comes after it. The value following the first case is9
. If the value of grade is equal to9
, then the code that follows the:
would run. - The
break
keyword tells the computer to exit the block and not execute any more code or check any other cases inside the code block. - At the end of each switch statement, there is a
default
statement. If none of the cases aretrue
, then the code in thedefault
statement will run. It’s essentially theelse
part in anif
/else if
/else
statement.
In the code above, suppose grade is equal to 10
, then the output would be “Sophomore”.
Note: Without the
break
keyword at the end of each case, the program would execute the code for the first matching case and all subsequent cases, including thedefault
code. This behavior is different fromif
/else
conditional statements which execute only one block of code.
Example
int rating = 3;switch (rating) {case 5:System.out.println("Exceptional");break;case 4:System.out.println("Good");break;case 3:System.out.println("Fair");break;default:System.out.println("Poor");break;}
All contributors
- Anonymous contributorAnonymous contributor3071 total contributions
- garanews222 total contributions
- christian.dinh2476 total contributions
- Anonymous contributor
- garanews
- christian.dinh
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.