web analytics

Java Switch Statement

Java switch statement is used to execute one or multiple blocks of code based on equality of a variable or output of an expression to a list of values. Each value in the list is called a case and variable or output of expression is compared to each case.

Syntax of Java Switch Statement

Following is syntax of java switch statement:

switch(expression){
case value1:
//// some statements
break;
case value2:
//// some other statements
break;
case value3:
case value4:
case value5:
//////// statements for multiple cases.
break;
default:
///// statements to run of no case matches from above cases.
}

Rules for Java Switch Statement

Following are rules for switch statement:

  • Variable used in a switch statement can only be of primitive data type ( integer, short, char, byte) strings or enums.
  • There may be any number of cases within a switch statement. In each case the keyword case is followed by the value to be compared to and a colon(:).
  • The variable in the switch and value for a case must be of same data type.
  • When the variable and case value match the statements after the case are executed until a break statement is encountered.
  • The switch terminates at break statement and controls goes to next statement right after switch statement.
  • break statement is not mandatory. If there is no break statement in a case then next all cases are executed until break is reached.
  • At the end of switch statement there may be an optional default statement.
  • The default statement will be executed if no other case has been matched.

Example


public class JavaSwitchTest {
public static void main(String args[]) {
char grad = 'B';
switch(grad) {
case 'A' :
System.out.println("Great!");
break;
case 'B' :
case 'C' :
System.out.println("Good");
break;
case 'D' :
System.out.println("Statisfactory");
case 'F' :
System.out.println("Try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grad);
}
}

One Reply to “Java Switch Statement”

Comments are closed.