< Java Tutorial

Java switch

← Previous Next →


The switch statement is a multi-way decision maker that tests the value of an expression against a list of constants. When  a  match is found, the statements associated with that constant are executed. The break statement ensures immediate exit from the switch statement 

Syntax :

switch(variable)
{
    case value1:
        //do operation; 
        break ; //<-- it will exit the switch block
        
    case value2:
        // do operation;
        break;
        
    .
    .
    default:
        // do operation;    
}

Example:

public class Exmple2
{  
   public static void main(String[] args) 
   {  
      int id = 2 ;
    
      switch(id)
      {
        case 2:
            printf("id is 2\n");
            break ;
            
        case 14:
            printf("id is 14\n");
            break ;
            
        case 24:
            printf("id is 24\n");
            break ;
      }
   }
}
← Previous Next →