Connecting Tech Pros Worldwide Forums | Help | Site Map

Switch

Expert
 
Join Date: Nov 2006
Location: UK
Posts: 1,320
#1   Apr 11 '07
Switch
If there are large number of selections the if statement can become very cumbersome.
When the comparisons are for equality with integral values known in advance we may use switch. e.g. if d is a char
Expand|Select|Wrap|Line Numbers
  1.    if (d=='s') System.out.println(" Saturday or Sunday");
  2.    else if (d=='m') System.out.println(" Monday");
  3.         else if (d=='t') System.out.println(" Tuesday");
  4.             //etc......
  5.  
could be implemented as a switch
Expand|Select|Wrap|Line Numbers
  1.  
  2.     switch (day)
  3.        {
  4.         case 's': System.out.println("Saturday or Sunday");
  5.                   break;
  6.         case 'm': System.out.println("Monday");
  7.                   break;
  8.         case 't': System.out.println("Tuesday or Thursday");
  9.                   break;
  10.         case 'w': System.out.println("Wednesday");
  11.                   break;
  12.         case 'f': System.out.println("Friday");
  13.                   break;
  14.         default:  System.out.println("I don't know this day");
  15.        }
  16.  
note:
(1) The condition must have type byte, char, int etc.
(2) The expression after each case must be a constant.
(3) The expression must be assignable to the type of the switch.
(4) break is required to break out of switch



Closed Thread