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 value.
A switch can be rewritten with a series of cascading if statements, but in some cases the switch statement is easier to read, and in a some compilers it can produce more efficient code.
switch (expr) { case c1: statements // do these if expr == c1 break; case c2: statements // do these if expr == c2 break; case c2: case c3: case c4: // Cases can simply fall thru. statements // do these if expr == any of c's break; . . . default: statements // do these if expr != any above }
/** Returns a random ambiguous compliment. */ public static String ambiguousCompliment() { String result; // The generated insult which will be returned int which = (int)(Math.random() * 4); // Should result in 0 to 3. switch (which) { case 0: result = "You look so much better than usual."; break; case 1: result = "Your work is up to its usual standards."; break; case 2: result = "You're quite competent for so litte experience."; break; default: result = "Oops -- something is wrong with this code."; } return result; }
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. In fact the function above does have a bug in it that would be caught by the default clause!
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 some specific coded values
(eg, the number of the button that was clicked in a JOptionPane), or
or processing characters (whose codes are treated like numbers), you will not
use it.
Java's if
statement, which was taken directly from C++ to increase
its attractiveness to C++ programmers, is not well loved.
case 90-100:
. Many other languages do.