The switch-case Structure

Java provides the extremely handy switch-case construct to facilitate selecting between multiple alternatives. This is such a common programming situation that the Java Virtual Machine (JVM) has bytecodes designed to speed this operation. The parameter in a switch statement is evaluated to int and this value determines what happens next.

Within the block of code controlled by a switch statement, the programmer can place case statements and (optionally) a default statement. In the following example, a String variable gets set according to the value of the integer variable x:

switch( x ) {
  case 0 : str = "none" ; break ;
  case 1 :
    str = "single" ; break ;
  case 2 :
    str = "pair" ;
    break ;
  default :  str = "many" ;

Each ...

Get Java 2™ Programmer Exam Cram™ 2 (Exam CX-310-035) 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.