How to Create Character Cases in Java - dummies

How to Create Character Cases in Java

By Doug Lowe

Here, you learn how you can use a char variable rather than an integer in a Java switch statement. When you use a char type, providing two consecutive case constants for each case group is common, to allow for both lowercase and uppercase letters. Suppose that you need to set the commission rates for the sales class based on character codes rather than on integer values, according to this table:

Class Commission Rate
A or a 2%
B or b 3.5%
C or c 5%
Any other value 0%

Here’s a switch statement that can do the trick:

double commissionRate;

switch (salesClass)

{

case ‘A’:

case ‘a’:

commissionRate = 0.02;

break;

case ‘B’:

case ‘b’:

commissionRate = 0.035;

break;

case ‘C’:

case ‘c’:

commissionRate = 0.05;

break;

default:

commissionRate = 0.0;

break;

}

The key to understanding this example is realizing that you don’t have to code any statements at all for a case group — and that if you omit the break statement from a case group, control falls through to the next case group. Thus the case ‘A’ group doesn’t contain any statements, but control falls through to the case ‘a’ group.

You use apostrophes, not quotation marks, to create character literals.