Skip to main content

Command Palette

Search for a command to run...

Modern Java Features Every Developer Should Know: Switch Expressions(Java 14) & Text Blocks(Java 15)

Updated
6 min read
Modern Java Features Every Developer Should Know: Switch Expressions(Java 14) & Text Blocks(Java 15)
N
Java & Spring Boot learner | Writing beginner-friendly technical articles | Exploring backend development

Java keeps evolving to make code cleaner, safer, and more readable. Earlier versions of Java often required verbose syntax, especially when dealing with switch statements or multi-line strings.

To solve these issues, Java introduced several improvements:

  • Switch Expressions (Java 14)

  • Text Blocks (Java 15)

These features reduce boilerplate code and make programs easier to maintain.

In this article we will understand:

  • Problems with older Java syntax

  • How modern Java solves them

  • Syntax and examples

  • Best practices

  • Interview insights

Switch Expressions in Java 14

What is a Switch Expression?

Before Java 14, the switch was only a statement. It was used to execute different blocks of code depending on a value.

Example:

int day = 3;

switch(day){

    case 1:
        System.out.println("Monday");
        break;
   
    case 2:
         System.out.println("Tuesday");
         break;
 
    case 3:
         System.out.println("Wednesday");
         break;

    default:
         System.out.println("Invalid day");
}

But the traditional switch statement had several problems.

Problems with Old Switch Statements

1. Multiple Case Lines (Code Repetition)

Old switch statements often required repeating code for similar cases.

Example:

switch(day){
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
         System.out.println("Weekday");
         break;
    case 6:
    case 7:
         System.out.println("Weekend");
         break;
}

This makes the code long and less readable.

Solution in Java 14

We can group cases using comma-separated values.

switch(day){

     case 1,2,3,4,5 -> System.out.println("Weekday");
     
     case 6,7 -> System.out.println("Weekend");
}

Cleaner and easier to read.

Fall-Through Problem

In traditional switch statements, if break is missing, execution falls through to the next case.

Example:

int number = 1;

switch(number){

      case 1:
          System.out.println("One");
 
      case 2:
          System.out.println("Two");

      case 3:
          System.out.println("Three");
}

Output:

One
Two
Three

This happens because break was missing, which often leads to bugs.

Solution: Arrow Syntax

Java 14 introduced a new Syntax:

case value -> expression

Example:

switch(number){

   case 1 -> System.out.println("One");
   case 2 -> System.out.println("Two");
   case 3 -> System.out.println("Three");
}

Now only the matching case executes and no fall-through occurs.

Switch Can Now Return Values

Earlier, switch could only execute code.

But many times we want to return a value from switch.

Example:

String result;

switch(day){

    case 1:
       result = "Monday";
       break;
    case 2:
       result = "Tuesday";
       break;
    case 3:
       result = "Invalid";
}

This requires extra variables and repeated code.

Switch Expression Solution

Now switch can directly return a value.

String result = switch(day){
     
          case 1 -> "Monday";
          case 2 -> "Tuesday";
          case 3 -> "Invalid";
};

This makes the code more concise and readable.

Using yield in Switch Blocks

If the switch case contains multiple statements, we must use yield.

Example:

String result = switch(day){

     case 1 -> {
           System.out.println("First day of week");
           yield "Monday";
          }

     case 2 -> {
           System.out.println("Second day");
           yield "Tuesday";
          }

     default -> "Invalid";
};

yield is used to return the value from the switch block.

Exhaustiveness Check

Old switch statements did not ensure all cases were handled.

Exampele:

enum Days {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY}

Days day = Days.FRIDAY;

switch(day){
     case MONDAY;
          System.out.println("Start of week");
}

If no case matches, nothing happens.

Java 14 Improvement

When using switch as an expression, the compiler ensures all cases are handled.

You must:

  • Cover all values OR

  • Use a default case

Example:

String result = switch(day){
       case MONDAY -> "Start";
       case TUESDAY -> "Second day";
       default -> "Other day";
};

Separate Scope for Each Case

Earlier, all switch cases shared the same scope, which could cause variable conflicts.

Java 14 arrow syntax treats each case as an independent scope.

Example:

switch(day){
      case 1 -> {
            int x = 10;
            System.out.println(x);
      }

      case 2 -> {
            int x = 20;
            System.out.println(x);
      }
}

Now there is no variable conflict.

Advantages of Switch Expressions

  • No fall-through errors

  • Cleaner syntax

  • Can return values

  • Less boilerplate code

  • Better compiler checks

  • Improved readability

Text Blocks in Java 15

What are Text Blocks?

Text Blocks are multi-line string literals introduced in Java 15.

They allow developers to write multi-line strings easily without escape characters.

They start and end with:

"""

Problem with Traditional Multi-Line Strings

Before Java 15, writing multi-line strings required:

  • Escape characters

  • String concatenation

  • \n for new lines

Example:

String query = "SELECT e.id, e.name\n"
             + "FROM employees e\n"
             + "WHERE e.salary > 6000\n"
             + "ORDER BY e.name ASC;";

Problems:

  • Hard to read

  • Error-prone

  • Difficult to maintain

  • Not easy to copy-paste

These strings often contain many escape characters like \n and \\.

Text Block Solution

Using text blocks:

String query = """
       SELECT e.id, e.name
       FROM employees e
       WHERE e.salary > 6000
       ORDER BY e.name ASC;
       """;

This is much cleaner and readable.

JSON Example

Old approach:

String json = "{\n" +
              " \"name\"\"John\",\n"+
              " \"country\":\"India\"\n"+
              "}";

Text Block approach:

String json = """
       {
          "name":"john",
          "country":"India"
        }
       """;

Important Rules of Text Blocks

1. Opening Delimiter Rule

Text must start on the next line after " " ".

Correct:

String text = """
  Hello
  World
  """;

Incorrect:

String text = """Hello World""";

2. Indentation Handling

Java automatically removes common leading spaces.

This makes text blocks look clean and aligned.

3. Trailing Whitespace

Trailing spaces are removed by default.

If you want to preserve them, use:

\s

4. Continuation Character

Each line normally adds a newline (\n).

To avoid newline, use:

\

Example:

String text = """
Hello
World
""";

Output:

Hello World

Text Blocks Are Still Strings

Internally, text blocks are compiled into regular String objects.

So all String methods still work.

Example:

text.toUpperCase();
text.length();
text.contains();

Advantages of Text Blocks

  • Easy to write multi-line text

  • Improves readability

  • No escape characters

  • Better for SQL, JSON, XML

  • Cleaner code

Real World Use Cases

Text blocks are very useful for:

  • SQL queries

  • JSON payloads

  • HTML templates

  • XML documents

  • Logging templates

Example:

String html = """
<html>
  <body>
     <h1>Welcome</h1>
  </body>
</html>
""";

Conclusion

Modern Java versions continue to improve developer productivity.

Switch Expressions(Java 14) simplify decision-making logic and eliminate common switch statement errors.

Text Blocks(Java 15) make multi-line strings easier to write and maintain.

These features help developers write cleaner, safer, and more readable Java code, which is especially important in modern applications.

Learning these improvements not only improves coding style but also helps in Java interviews and real-world development.

More from this blog

CoreJava

19 posts

I have written and published a comprehensive blog series titled "CoreJava" on Hashnode, based on my learning journey from basics to advanced. The series includes topics like OOP, Collections, Exception Handling, Multithreading, and Java Streams, explained with clear examples and practical insights to help learners build a strong foundation in java.