SCJP Chapter 5

Page 14

CertPrs8/Java 5 Cert. Study Guide/Sierra-Bates/225360-6/Chapter 5

328 

Chapter 5:   Flow Control, Exceptions, and Assertions

int x = 1; switch(x) { case 1: { System.out.println("x is one"); break; } case 2: { System.out.println("x is two"); break; } case 3: { System.out.println("x is two"); break; } } System.out.println("out of the switch");

Running the preceding code, now that we've added the break statements, will print x is one out of the switch

and that's it. We entered into the switch block at case 1. Because it matched the switch() argument, we got the println statement, then hit the break and jumped to the end of the switch. An interesting example of this fall-through logic is shown in the following code: int x = someNumberBetweenOneAndTen; switch (x) { case 2: case 4: case 6: case 8: case 10: { System.out.println("x is an even number"); } }

break;

This switch statement will print x is an even number or nothing, depending on whether the number is between one and ten and is odd or even. For example, if x is 4, execution will begin at case 4, but then fall down through 6, 8, and 10, where it prints and then breaks. The break at case 10, by the way, is not needed; we're already at the end of the switch anyway. Note: Because fall-through is less than intuitive, Sun recommends that you add a comment like: // fall through when you use fall-through logic.

chap5-1127f.indd 328

11/28/05 12:40:36 AM


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.