Sitemap

Switch Statement evolution From java-2 to java- 21

5 min readOct 9, 2024

--

Press enter or click to view image in full size

switch statement in Java has evolved significantly since its introduction, gaining new features and becoming more powerful with each major update. Below is an evaluation of the evolution of the switch statement, highlighting key changes and improvements in various versions of Java, complete with examples.

1. Java 2 (Original Switch Statement)

In Java 2 (released in 1998), the switch statement was introduced with basic functionality. It supported switching on integers (int, byte, short, char), and enum types were added later in Java 5.

Syntax

int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}

Limitations:

  • Switch could only be used with primitive types (int, char, byte, short) and later with enums.
  • Required break to avoid falling through cases unintentionally.

2. Java 5 (Enums in Switch)

In Java 5 (released in 2004), enum support was added to the switch statement, making it possible to use enums as case expressions. This was a significant improvement for readability and type safety.

Syntax:

enum Day { MONDAY, TUESDAY, WEDNESDAY }
Day day = Day.TUESDAY;
switch (day) {
case MONDAY:
System.out.println("Monday");
break;
case TUESDAY:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}

3. Java 7 (Switch with Strings)

Java 7 (released in 2011) introduced the ability to use String in switch statements, greatly enhancing its flexibility. This change allowed developers to switch on textual data.

Syntax:

String day = "Tuesday";
switch (day) {
case "Monday":
System.out.println("Monday");
break;
case "Tuesday":
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}

Key Changes:

  • Switch now supported String, which made code that depended on string matching cleaner and more efficient.

4. Java 12 (Switch Expressions — Preview feature)

Java 12 (released in 2019) introduced switch expressions as a preview feature. This allowed switch to return values and eliminated the need for explicit break statements, making the syntax more concise.

Syntax (Java 12 Preview):

int day = 2;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
default -> "Invalid day";
};
System.out.println(dayName);

Key Changes:

  • The switch statement can now be used as an expression that returns a value.
  • Arrow (->) syntax introduced for cleaner case expressions.
  • The break statement is no longer needed in this context.

5. Java 13 (Switch Expressions — Standard feature )

Java 13 (released in 2019) standardized switch expressions, allowing them to be used both as statements and expressions. The arrow syntax (->) was finalized, and multiple labels for a single case were supported.

Get iamthatsoftwareguy’s stories in your inbox

Join Medium for free to get updates from this writer.

Syntax (Java 13+):

int day = 2;
String dayName = switch (day) {
case 1, 7 -> "Weekend";
case 2, 3, 4, 5, 6 -> "Weekday";
default -> "Invalid day";
};
System.out.println(dayName);

Key Changes:

  • Multiple case labels (case 1, 7 ->) can be grouped together to handle cases more concisely.
  • Switch expressions became a permanent feature, enhancing both readability and functionality.

6. Java 17 (Pattern Matching for Switch — Preview feature )

Java 17 (released in 2021) introduced pattern matching for switch as a preview feature. This extended switch to support type patterns, making it easier to perform type checks and casts within the same construct.

Syntax (Java 17 Preview):

Object obj = 123;
String result = switch (obj) {
case Integer i -> "Integer: " + i;
case String s -> "String: " + s;
default -> "Unknown type";
};
System.out.println(result);

Key Changes:

  • Switch can now match based on the type of the object being switched.
  • Automatic casting based on the type pattern (e.g., Integer i).

7. Java 19 (Pattern Matching for Switch — Improved)

Java 19 (released in 2022) refined pattern matching for switch, expanding its capabilities and offering more flexibility in type-based matching. This further enhanced type-checking and simplified code where multiple types could be handled within a single switch.

8. Java 21 (Finalization of Pattern Matching for Switch)

Java 21 has introduced exciting enhancements to the switch statement with expanded pattern matching, allowing developers to handle more complex scenarios and reduce boilerplate code. This new feature enables you to match patterns based on type, structure, and conditions, resulting in cleaner and more expressive code.

Key Features of Expanded Pattern Matching

  1. Type Patterns: You can match an object against a specific type and perform actions based on that type.
  2. Record Patterns: You can destructure records in the switch expression, making it easier to work with data classes.
  3. Guard Conditions: You can add additional conditions to your case statements, allowing for more granular control over the flow of logic.

Example: Using Expanded Pattern Matching in Java 21

Let’s explore a practical example that illustrates the new capabilities of the switch statement in Java 21.

Scenario: Suppose we have a system that processes different shapes. We want to calculate the area of various shapes, including Circle, Rectangle, and Triangle, leveraging pattern matching

// Define shape classes
sealed interface Shape permits Circle, Rectangle, Triangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
record Triangle(double base, double height) implements Shape {}
public class ShapeAreaCalculator {
public static void main(String[] args) {
Shape shape1 = new Circle(5);
Shape shape2 = new Rectangle(4, 6);
Shape shape3 = new Triangle(3, 4);
System.out.println("Area of shape1: " + calculateArea(shape1));
System.out.println("Area of shape2: " + calculateArea(shape2));
System.out.println("Area of shape3: " + calculateArea(shape3));
}
static double calculateArea(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius(); // Calculate area for Circle
case Rectangle r -> r.width() * r.height(); // Calculate area for Rectangle
case Triangle t when t.base() > 0 && t.height() > 0 -> 0.5 * t.base() * t.height(); // Calculate area for Triangle with guard condition
default -> throw new IllegalArgumentException("Unknown shape: " + shape);
};
}
}

Key Changes:

  • Finalization of type pattern matching in switch.
  • Simplified handling of complex data types like sealed types and records.

Summary of Switch Evolution:

  1. Java 2: Basic switch for int, char, byte, short.
  2. Java 5: Added support for enum.
  3. Java 7: Introduced support for String.
  4. Java 12–13: Introduced switch expressions, arrow syntax, multiple case labels.
  5. Java 17–21: Introduced and finalized pattern matching for switch, enabling type patterns.

Conclusion:

The evolution of the switch statement in Java demonstrates a clear trend toward greater flexibility and power, enabling more concise, readable, and maintainable code. From basic integer-based switches in Java 2 to powerful pattern-based expressions in Java 17 and 21, the switch statement has grown to support more complex logic and a wider variety of use case

--

--