Java Switch Statement

A switch statement is a compact form of multiple if statements within a construct. It increases the readability of the program code. It evaluates an expression like an if statement, but unlike an if statement, it takes one of many paths depending on the value derived from the expression. Its syntax is:

			

switch(expression) {    
    case 1: statement_1;  
    break;    
    case 2: statements_2;   
    break;    
    case 3: statement_3;  
    break;    
    ….
    default: statement   // executed when expression does not match any value    
}  

				

For example, to name the twelve months of a year by number, it is more efficient to use a switch statement instead of a series of if-else statements.

			

switch(month) {    
    case 1: print “January”;  
    break;    
    case 2: print “February”;  
    break;    
    case 3: print “March”;  
    break;    
    case 4: print “April”;  
    break;    
    case 5: print “May”;  
    break;    
    case 6: print “June”;  
    break;    
    case 7: print “July”;  
    break;    
    case 8: print “August”;  
    break;    
    case 9: print “September”;  
    break;    
    case 10: print “October”;  
    break;    
    case 11: print “November”;  
    break;    
    case 12: print “December”;  
    break;    
    default: print “Invalid Month”;    
}