The purpose of a switch
statement is to provide a convenient and simple method of making multi-branch selections based upon integer, enumeration, or String
expression. The switch
statement has the following basic form:
switch ( expression ) { //case clauses }
There are usually multiple case
clauses within the statement block. The basic form of the case
clause uses the case
keyword followed by a colon, zero or more statements, and usually a break
statement. The break
statement consists of a single keyword, break
, shown as follows:
case <constant-expression>: //statements break;
There is also an optional default clause that can be used. This will catch any values not caught by a case
clause. This is demonstrated as follows:
default: //statements break; // Optional
The basic form of the switch
statement is shown as follows:
switch (expression) { case value: statements case value: statements … default: statements }