Using break

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

(Trick Question:) What would be the discount if code were 'a' ?

Answer:

0.3 — Notice that the code is a lower case 'a', not upper case.

Using break

There is one label per case statement, and there must be an exact match with the expression in the switch for the case to be chosen.

The break at the end of each case is not always needed. If it is omitted, then after the statements in the selected case have executed, execution will continue with the following case. This is not usually what you want. Examine the following program:

class Switcher
{
  public static void main ( String[] args )
  {
    char   color = 'Y' ;    
    String message = "Color is";
    
    switch ( color )
    {
    
      case 'R':
        message = message + " red" ;
                        
      case 'O':
        message = message + " orange" ;
                        
      case 'Y':
        message = message + " yellow" ;
                        
      case 'G':
        message = message + " green" ;
                        
      case 'B':
        message = message + " blue" ;
                        
      case 'V':
        message = message + " violet" ;
                        
      default:
        message = message + " unknown" ;
            
    }

  System.out.println ( message ) ;
  }
}

The program fragment will print:

Color is yellow green blue violet unknown

This is probably not what the program was intended to do.

QUESTION 9:

Mentally fix the program fragment so that it prints just one color name.