Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Spring Framework | Web Services | BioInformatics | Java Server Faces | Jboss 3.0 tutorial | Hibernate 3.0 | XML

Tutorial Categories: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML


Java Tutorials



Struts Tutorials

Struts Resources

Visit Forum! Post Questions!
Jobs At RoseIndia.net!

Java Notes

switch Statement - Overview


Purpose of switch: select one of many possible statements to execute


The if statement allows you to select one of two sections of code to execute based on a boolean value (only two possible values).

The switch statement allows you to choose from many statements based on an integer (including char) or enum value.


Syntax example




switch (expr) {
  case c1:
        statements // do these if expr == c1
  case c2: 
        statements // do these if expr == c2
  case c2:
  case c3:
  case c4:         //  Cases can simply fall thru.
        statements // do these if expr ==  any of c's
  . . .
        statements // do these if expr != any above

Switch keywords

The switch keyword is followed by a parenthesized integer expression, which is followed by the cases, all enclosed in braces.. The switch statement executes the case corresponding to the value of the expression. Normally the code in a case clause ends with a break statement, which exits the switch statement and continues with the statement following the switch. If there is no corresponding case value, the default clause is executed. If no case matched and there is no default clause, execution continues after the end of the switch statement.
The case keyword is followed by an integer constant and a colon. This begins the statements that are executed when the switch expression has that case value.
If no case value matches the switch expression value, execution continues at the default clause. This is the equivalent of the "else" for the switch statement. It is written after the last case be convention, and typically isn't followed by break because execution just continues out the bottom of switch if this is the last clause.
The break statement causes execution to exit to the statement after the end of the switch. If there is no break, execution flows thru into the next case. Flowing directly into the next case is almost always an error.

Example - Random comment

String comment;   // The generated insult.
int which = (int)(Math.random() * 3);  //  Result is 0, 1, or 2.

switch (which) {
    case 0:  comment = "You look so much better than usual.";
    case 1:  comment = "Your work is up to its usual standards.";
    case 2:  comment = "You're quite competent for so little experience.";
    default: comment = "Oops -- something is wrong with this code.";

Equivalent if statement

A switch statement can often be rewritten as an if statement in a straightforward manner. For example, the preceding switch statement could be written as follows. When one of a number of blocks of code is selected based on a single value, the switch statement is generally easier to read. The choice of if or switch should be based on which is more readable.

String comment;   // The generated insult.
int which = (int)(Math.random() * 3);  //  Result is 0, 1, or 2.

if (which == 0) {
    comment = "You look so much better than usual.";
} else if (which == 1) {
    comment = "Your work is up to its usual standards.";
} else if (which == 2) {
    comment = "You're quite competent for so little experience.";
} else {
    comment = "Oops -- something is wrong with this code.";

Defensive programming

Always include a default clause in your switch statement as a general policy of defensive programming - assume there will be bugs in your code and make sure they are caught.

Where to use switch?

The ability of switch to choose between many sections of code seems to make it more powerful than if. However, selecting sections of code depending on specific integer values turns out not to be very common. If you are handling specific coded values (eg, the number of the button that was clicked in a JOptionPane), or processing characters (whose codes are treated like numbers), you may find it useful.

Efficiency? Some compilers can produce more efficient code for certain switch statements than for equivalent if statements. I haven't bothered to test the Java compiler because, if there is a speed difference, it would be extremely small and the choice between switch and if should be based on readability.

Comments on switch

Java's switch statement, which was taken directly from C++ to increase its attractiveness to C++ programmers, is not well loved.

  • No ranges. It doesn't allow ranges, eg case 90-100:. Many other languages do.
  • Integers only. It requires integers and doesn't allow useful types like String. Many other languages do.
  • Error-prone. It is error-prone and a common source of bugs - forgetting break or default silently ignores errors. Some languages have eliminated these dangerous situations.
Ask programming questions?



Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

0 comments so far (post your own) View All Comments Latest 10 Comments:
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification

Tell A Friend
Your Friend Name


Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright 2007. All rights reserved.

[an error occurred while processing this directive]