Geeks With Blogs
Stephanie Grima C#, ASP.NET and my life.

 

Switch Statement

It is a control statement, which lets you transfer control to different statements within the switch, according to the value in the switch expression.

switch(expression)
{
     case "statement1" :
          statement1 body;
       break;
    case "statement2" :
          statement1 body;
       break;
    default :
          default body;
       break;
}

If the switch expression matches the criteria within one of the statements, the body beneath it is performed until it meets the end of the body, which is break.  If the expression doesn't meet any of the criteria, the code within the default is executed, if it is there. An example is the following:

String output = "";
switch
(choice)
{
     case "delivered" :
          output = "The packet has been recieved";
       break;
    case "transit" :
          output = "The packet is still being transferred";
       break;
    default :
          output = "The packet has been lost";
       break;
}

If the expression is choice is equal to delivered or transit, the body between their case and break is performed. If the expression in choice is NOT equal to any of the cases, the default case is used. If the packet is not delivered or in transit, we assume that it has been lost.

Posted on Wednesday, October 29, 2008 7:13 PM C# , Java | Back to top


Comments on this post: [C#] [Java] Control Structures Part 2 : Switch Statement

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Steffi | Powered by: GeeksWithBlogs.net