x

Java – Switch statement

PREV     NEXT

Java Switch Statement can have multiple execution paths. It is similar to that of ‘if else-if’ statement except that switch can handle expressions which results to any primitive data type and if statements handle only boolean expressions.


Syntax for java Switch Statement:

switch (expression)

{

case ‘value1’:

//statements

break;

case ‘value2’:

//statements

break;

case ‘value3’:

//statements

break;

default:

//statements


}

  • The value of the expression is matched with the case values. Only the statements inside the matched case are executed.
  • The ‘break’ keyword is added after each case in order to exit from the switch case. If  the ‘break’ keyword is not specified, all the cases would be checked and the matching cases would be executed.
  • The default case is considered when no case value is matched.

Example for java Switch Statement:

Output:

Two

In the above program the value of n decides which statement to be executed. Here it is 2 and hence the statement inside the case 2 is executed.

PREV     NEXT



Like it? Please Spread the word!