Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

View RSS Feed

JD1's Personal Development Blog

The Switch Statement

Rate this Entry
It's to my understanding that the Switch Statement is used as a means of saving time. If you want to test multiple conditions, but are looking for a more efficient way of doing things than using the If or Else If Statements, the Switch Statement is the way to go. I have trouble remembering what the switch statement means because I fail to make its connection to the 'case' keyword. The 'case' is the most important part of the switch statement. I know I'll be able to remember to use the switch statement more frequently if I can realise its relationship with the 'case' structure. Basically, think of switch; think of case.

Switch Statement

switch(variable){
case firstcondition:
   instructions if firstcondition is true...
   instructions if firstcondition is true...
   instructions if firstcondition is true...
   break;
case secondcondition:
   instructions if secondcondition is true...
   instructions if secondcondition is true...
   instructions if secondcondition is true...
   break;
case thirdcondition:
   instructions if thirdcondition is true...
   instructions if thirdcondition is true...
   instructions if thirdcondition is true...
   break;
default:
   instructions if all above conditions are false...
   instructions if all above conditions are false...
   instructions if all above conditions are false...
   break;
}
Note: The 'break;' isn't always going to be present. You only use break if you want to exit the Switch Statement if the current condition proves true. In some situations, it will pay to go through several conditions of the Switch Statement regardless of whether the current one is true or not. However, in most cases, the 'break;' will be necessary.

Java Example

switch(age){
case 1:
   System.out.println("You're 1 year old!");
   break;
case 2:
   System.out.println("You're 2 years old!");
   break;
case 3:
   System.out.println("You're 3 years old!");
   break;
default:
   System.out.printkn("I don't know how old you are!");
   break;
}
Categories
Uncategorized

Comments