Switch Statement






Switch statements are also used when we need our program to make a certain decision based on a condition and then execute accordingly.

Syntax:

switch(expression)
{
   case value-1:
   statements which will be executed if the value obtained by evaluating the expression is value-1

              break;

   case value-2:
   statements which will be executed if the value obtained by evaluating the expression is value-2

              break;
   ...
   ...
   ...
   case value-n:
    statements which will be executed if the value obtained by evaluating the expression is value-n

              break;

    default :
    statements which will be executed if the value is not matching with any of the above values

              break;
   }
   //statements after the switch block

Example:

/*
* File Name : SwitchStatementDemo1.java
*/
public class SwitchStatementDemo1
{

   public static void main(String args[])
   {

       int choice = 2;

       switch (choice)
       {
       case 1:
           System. out .println( "Bank Menu" );
           break ;

       case 2:
           System. out .println( "Loan Menu" );
           break ;

       case 3:
           System. out .println( "Credit Card Menu" );
           break ;

       default :
           System. out .println( "No Match Found" );
       break ;

       }
   }
}


Output:
Loan Menu
Here the program displayed the message “Loan Menu” because the variable “choice” is assigned as 2.





Popular posts from this blog

Naming Conventions

if..else..if Loader

Nested if..else Statement