Conditionals Series: Switch Expressions - Determining a Value

Conditionals Series: Switch Expressions - Determining a Value

Before we look at #SwitchExpressions, lets take a few moments to explore #SwitchStatements and the difference between them and Switch Expressions.

If you are an #APCSA teacher, please remember that switch statements and switch expressions are OUTSIDE the AP CSA #Java subset. Therefore, this topic does not need to be taught to students and might be best left for after the AP exam or a post-AP type course.


What are switch statements used for?

  • Switch statements are often used when you have a menu of options to choose from.
  • Algorithms that use switch statements can also be written with a series of nested if..else statements.
  • Using switch statements instead of a series of nested if..else statements can make code more readable.
  • Default statements are often required to ensure that all cases are addressed, and the switch is exhaustive.
  • Only certain data types can be used in a switch: byte, short, char, int, long, enums, String, Integer, Short, Byte, and Long

Basic Structure of a Switch Statement

switch (<variable>) { 
   case <value>: {
      //statements to use if variable == value
      break; 
   }
   //additional case statements
   default: {
      //statements to use if no case values match the value of variable
      break;
   }
}         

Grade Level Example

Consider the following code segment which prints out what year a student is in high school based on the grade given. A grade of 9 prints "Freshman"; a grade of 10 prints "Sophomore"; a grade of 11 prints "Junior"; a grade of 12 prints "Senior"; and all other values of grade prints "Not in High School“.

int grade = 9;
if (grade == 9) {
   System.out.println("Freshman");
} else {
   if (grade == 10) {
      System.out.println("Sophomore");
   } else {
      if (grade == 11) {
         System.out.println("Junior");
      } else {
         if (grade == 12) {
            System.out.println("Senior");
         } else {
            System.out.println("Not in High School");
        }
      }
   }
}        

We can re-write this if statement as a switch statement as follows:

switch (grade) {
    case 9: {
       System.out.println("Freshman");
       break;
    }
    case 10: {
       System.out.println("Sophomore");
       break;
    }
    case 11: {
       System.out.println("Junior");
       break;
    }
    case 12: {
       System.out.println("Senior");
       break;
    }
    default: {
       System.out.println("Not in High School");
   }
 }        

Often a switch statement can make the code more readable, especially as the options available grow.

Basic Structure of a Switch Statement with Lambda

We can use lambda notation when writing switch statements as well.

switch (<variable>) { 
   case <value> -> //statements to use if variable == value
   //additional case statements
   default -> //statements to use if no case values match the value of variable
}         

We can re-write the switch statement above with lambda as follows:

 switch (grade) {
    case 9 -> System.out.println("Freshman");
    case 10 -> System.out.println("Sophomore");
    case 11 -> System.out.println("Junior");
    case 12 -> System.out.println("Senior");
    default ->  System.out.println("Not in High School");
 }        

Switch Expressions

How are switch expressions different from switch statements?

  • Switch expressions yield a value, typically assigned to a variable
  • Switch expressions use the keyword yield and do not require a break statement as yield will return a value and the execution stops
  • Switch expressions require a ; at the end.

Basic Structure of a Switch Expression

<type> returnVariable = switch (<variable>) { 
   case <value>: {
      yield valueAssignedtoreturnVariable; 
   }
   //additional case statements
   default: {
      yield valueAssignedtoreturnVariable; 
   }
};        

Revisiting the Grade Level Example

 String gradeLevel = switch (grade) {
    case 9: {
       yield "Freshman“;
    }
    case 10: {
       yield "Sophomore";
    }
    case 11: {
       yield "Junior";
    }
    case 12: {
       yield "Senior";
    }
    default: {
      yield "Not in High School";
    }
 };
 System.out.println(gradeLevel);        

We've embedded the expression into a statement requiring a semi-colon at the end.

Note that the keyword yield is being used to return the value for each case.

Basic Structure of a Switch Expression with Lambda

<type> returnVariable = switch (<variable>) { 
   case <value> -> //value to assign if variable == value ;
   //additional case statements
   default -> //value to assign if no case values match the value of variable ;
};         

The above example re-written with lambda


 String gradeLevel = switch (grade) {
    case 9 -> "Freshman“;
    case 10 -> "Sophomore";
    case 11 -> "Junior";
    case 12 -> "Senior";
    default -> "Not in High School";
 };
 System.out.println(gradeLevel);        

What's Next for Switch Statements and Switch Expressions?

Previewing in Java 24, Primitive Types in Patterns, instanceof, and switch. NOTE: Preview features are not guaranteed to be released. Potential new features are proposed openly in the community via a document called a JDK Enhancement Proposal or JEP. Each JEP goes through the following lifecycle:

  • Each must be approved for inclusion with a target release.
  • Each goes through at least 1 preview cycle to address feedback. Most go through 2-3 previews but it could be more.
  • Once feedback is addressed and the community approves the implementation, the JEP is targeted for a release as a final candidate.
  • With each release revision, the proposal documentation is updated to reflect the current state of the proposal and it is given a new identifying number to ensure traceability through history on versions of the idea.

JEP 488: Primitive Types in Patterns, instanceof, and switch

For instanceof – allows the use of instanceof with primitive types instead of just reference types. It checks whether a variable can be represented by a specific type without any loss of precision of data.

For switch - allows for the use of a switch over all primitive types.

To ensure all cases are being covered, we can add guards to our switch expressions.

int x = //…
String result = switch (x) {
  case 0 -> "zero";
  case int y when y < 0 -> "negative";
  case int z -> "positive";
}        

  • when is being used as a condition
  • The third case is for anything that isn’t the first two
  • No default is required, the third case acts as the default

Other Primitive Data Types for Switch

Currently, we can not use a switch for boolean variables. This new feature would allow for the following:

String result = switch(x % 2 == 0) {
   case true -> "Even";
   case false -> "Odd";
}        

Or if you wanted to report out the information, use a switch statement:

switch(x % 2 == 0) {
   case true -> System.out.println ("Even");
   case false -> System.out.println ("Odd");
}        

For more about about Java Patterns, read my article on Java Patterns here.


#Java #LearnJvaa #TeachJava #JavaEducators

To view or add a comment, sign in

More articles by Crystal Sheldon

  • AP CSA Free Response Questions #4

    Last question!! Question #4 has students analyze and manipulate data in a 2D array. Sometimes these questions…

    1 Comment
  • AP CSA Exam FRQ #3 Tips

    The third free response question has students analyzing and manipulating data stored in array or ArrayList objects or…

  • AP CSA FRQ #2 Class Design

    In FRQ 2: Class Design, you are expected to write a class that meets the given specification. The question might…

  • AP CSA FRQ #1 String Version

    Sometimes you will find that FRQ #1 Methods and Control Structures involves manipulating String objects. This article…

  • AP CSA Free Response Question #1 Tips

    The first free response question, Methods and Control Structures, tests students on units 1 - 4, with a special focus…

    1 Comment
  • Tips for Preparing Students for AP CSA FRQs

    The last article was about test taking strategies for students, but how should teachers prepare their students for the…

  • AP CSA Exam Day Tips

    Attention #APCSA teachers! The exam is a little more than a month away. In this article series, I will be sharing tips…

    1 Comment
  • Local-Variable Types and AP CSA

    When I first heard of using var, I didn't quite understand why we would want to use it. After all, one of Java's…

  • Local-Variable Type

    When I first heard of using var, I didn't quite understand why we would want to use it. After all, one of Java's…

  • Conditionals Series: Switch Expressions and the AP CSA Free Response Questions

    Looking for a refresher on Switch Statements and Switch Expressions? Check out my article here. If you are an #APCSA…

Insights from the community

Others also viewed

Explore topics