Chapter 6
Pulling a Switcheroo
In This Chapter
Avoiding the trouble with big else-if statements
Using the switch statement
Creating case groups
Using characters with case
In Book II, Chapter 4, you find out about the workhorses of Java decision-making: boolean expressions and the mighty if statement. In this chapter, you discover another Java tool for decision-making: the switch statement. The switch statement is a pretty limited beast, but it excels at making one particular type of decision: choosing one of several actions based on a value stored in an integer variable. As it turns out, the need to do just that comes up a lot. You want to keep the switch statement handy for use when such a need arises.
Battling else-if Monstrosities
Many applications call for a simple logical selection of things to be done depending on some value that controls everything. As I describe in Book II, Chapter 4, such things are usually handled with big chains of else-if statements all strung together.
Unfortunately, these things can quickly get out of hand. else-if chains can end up looking like DNA ...
Get Java All-in-One For Dummies, 4th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.