Class SwitchExpressionPreviewExamples

java.lang.Object
net.jrodolfo.java_evolution.java12.SwitchExpressionPreviewExamples

public class SwitchExpressionPreviewExamples extends Object
Demonstrates switch expressions as a Java 12 preview feature.

Before switch expressions, returning a value from switch usually required a mutable local variable and careful break statements. Accidental fall-through was also a common source of bugs.

Java 12 previewed switch expressions to solve those problems. Its first preview included value-bearing break; Java 13 replaced that form with yield, and Java 14 finalized switch expressions. The runnable method uses the current syntax so it can compile on JDK 26, while firstPreviewSource() preserves the historically important Java 12 form as source text.

  • Constructor Details

    • SwitchExpressionPreviewExamples

      public SwitchExpressionPreviewExamples()
  • Method Details

    • dayType

      public String dayType(int dayNumber)
      Uses a switch expression to return a value directly.
      Parameters:
      dayNumber - day number from 1 to 7
      Returns:
      whether the day is a weekday or weekend
    • firstPreviewSource

      public String firstPreviewSource()
      Returns a minimal source example of the Java 12 first-preview form.

      The text is intentionally not compiled by the main build: a modern compiler cannot use --release 12 --enable-preview to compile a preview feature from an older JDK release.

      Returns:
      Java 12 switch-expression source using value-bearing break