Pre-Lab Assignment: Lab 6      Name ___________________________________

The Switch Statement

The Java switch statement (pp. 128 - 132) is another conditional statement. Switch provides a compact, efficient syntax that is useful when you would otherwise have a cascading if statement in which each condition checks the value of the same expression. For example, the if and switch statements below do the same thing -- either could be used as shown in the program. (Note: remainder is a variable of type int and hexDigit is a variable of type String.)

if (remainder == 10)
{
   hexDigit = "A";
}
else if (remainder == 11) 
{
   hexDigit = "B";     
}
else if (remainder == 12)
{
   hexDigit = "C";
}
else if (remainder == 13)
{
   hexDigit = "D";
}
else if (remainder == 14)
{
   hexDigit = "E";
}
else if (remainder == 15)
{
   hexDigit = "F";
}
else
{
   hexDigit = "Error";
}
switch (remainder)
{
   case 10:
      hexDigit = "A";
      break;
   case 11:
      hexDigit = "B";
      break;
   case 12:
      hexDigit = "C";
      break;
   case 13:
      hexDigit = "D";
      break;
   case 14:
      hexDigit = "E";
      break;
   case 15:
      hexDigit = "F";
      break;
   default:
      hexDigit = "Error";
}

A few things to note about switch statements:

Exercises

  1. In the code below, replace the cascading if statement with a switch statement.
    System.out.println("Enter size box you want");
    int boxSize = scan.nextInt();
    double price;
    
    if (boxSize == 10)
    {
       System.out.println("Small");
       price = 2.5;
    }
    else if (boxSize == 20) 
    {
       System.out.println("Medium");     
       price = 3.75;
    }
    else if (boxSize == 30)
    {
       System.out.println("Large");
       price = 5.0;
    }
    else
    {
       System.out.println ("Not a valid size.");     
       price = -1;
    }
    
    

  2. Rewrite each condition below in valid Java syntax (give a boolean expression):
    1. x > y > z

       

       

    2. neither x nor y is equal to 0

       

       

    3. both x and y are equal to 0

       

       

    4. x is greater than y but less than z

       

       

     

  3. Use the laws of logic to write a Java expression equivalent to the following without using the not (!) operator.
              ! (age >= 65 && income < 20000)
    
    
    
    
    
    
  4. Suppose age is a variable that has been declared and given a value. Fill in the blank with a valid Java condition for "age is divisible by 5" in the following if statement.
    
            if ( _______________________________________________________ )
              System.out.println ("Your age is divisible by 5.");
            else
              System.out.println ("Your age is not divisible by 5.");
    
    
  5. Use truth tables to determine whether the following two expressions are equivalent. Show work!
    1. !(p || !q)
      ! p || q