Switch Operator in Java : Tutorial 4


03 Oct  

 

We have seen both ‘if …else’ and ‘else…if’, now let’s take a glance at the switch operator:

 

   1: public class NewClass {

   2:     public static void main (String arg [])

   3:     {

   4:         char nation;

   5:         System.out.println("I for India");

   6:         System.out.println("E for England");

   7:         System.out.println("U for United States");

   8:         System.out.print("Enter Choice:" );

   9:         System.out.flush();

  10:         try

  11:         {

  12:             switch (nation= (char)System.in.read())

  13:             {

  14:                 case 'I':

  15:                   System.out.println("It is in Asia");

  16:                     break;

  17:                 case 'E':

  18:                     System.out.println("It is in Europe");

  19:                     break;

  20:                 case 'U':

  21:                     System.out.println("It is in N America");

  22:                     break;

  23:  

  24:  

  25:  

  26:  

  27:             }

  28:  

  29:  

  30:         }

  31:         catch (Exception e)

  32:         {System.out.println("I/O Error!");

  33:  

  34:         }

  35:         

  36:  

  37:     }

  38: }

 

 

Here are few points you need to note:

1. There is no semi colon after catch

2. Catch is required to match with try

3. After the case we use a colon.

4. The input should be quotes (each case)

5. System.in.read() is used to read the input

6. Break is used for separating each case.

Note: You are using flush to send the data to the buffer.  You can also write the code without this, since System.out can perform low level works.

 

run:
I for India
E for England
U for United States
Enter Choice:I
It is in Asia

 

You can employ the ‘?:’ operator as well for decision making.

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

Tags:


TechBlog on Facebook

Leave a Reply