HelloKoding

Practical coding guides

Java 14 Features with Examples

In this article, you will explore the following Java 14 major features with examples

  • Switch Expressions (Standard)
  • Helpful NullPointerException
  • Text Blocks (Second Preview)
  • Records (Preview)
  • Pattern Matching for instanceOf (Preview)
  • Remove the Concurrent Mark Sweep (CMS) Garbage Collector

Switch Expressions (Standard)

  • Beside using switch case with break statement, you can also write swith case expression with yield statement by using arrow syntax
public String toWord(int val) {
    var str = switch (val) {
        case 0 -> "zero";
        case 1 -> "one";
        default -> {
            System.out.println("no fall through and less verbose");
            yield "many";
        }
    };

    return str;
}

@Test
public void testSwitchExpressions() {
    var str1 = toWord (0);
    var str2 = toWord (1);
    var str3 = toWord (2);

    assertThat(str1).isEqualTo("zero");
    assertThat(str2).isEqualTo("one");
    assertThat(str3).isEqualTo("many");
}
  • In Java 14, Switch Expressions are standard. This was a preview language feature in Java 12 and 13

Helpful NullPointerException

  • JVM describes NullPointerException precisely which variable was null

HelpfulNullPointerException.java

package com.hellokoding.java.java14;

import org.junit.Test;

public class HelpfulNullPointerException {
    public void nullString(Pojo pojo) {
        pojo.field1 = "a";
    }

    @Test
    public void testNullString() {
        nullString(null);
    }
}

class Pojo {
    String field1;
}
  • Run the above test before Java 14
java.lang.NullPointerException
	at com.hellokoding.java.java14.HelpfulNullPointerException.nullString(HelpfulNullPointerException.java:7)
	at com.hellokoding.java.java14.HelpfulNullPointerException.testNullString(HelpfulNullPointerException.java:12)
  • Run with this VM option -XX:+ShowCodeDetailsInExceptionMessages since Java 14
java.lang.NullPointerException: Cannot assign field "field1" because "pojo" is null
	at com.hellokoding.java.java14.HelpfulNullPointerException.nullString(HelpfulNullPointerException.java:7)
	at com.hellokoding.java.java14.HelpfulNullPointerException.testNullString(HelpfulNullPointerException.java:12)
  • This feature might be enabled by default in a future Java version

Text Blocks (Second Preview)

  • A text block is a multi-line string literal that avoids the need for most escape sequences, formats the string in a predictable way
  • The verbose multiple lines strings
String html = "<html>\n" +
              "    <body>\n" +
              "        <p>Hello, world</p>\n" +
              "    </body>\n" +
              "</html>\n";

String query = "SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB`\n" +
               "WHERE `CITY` = 'INDIANAPOLIS'\n" +
               "ORDER BY `EMP_ID`, `LAST_NAME`;\n";
  • The clean multiple lines strings with text blocks
String html = """
              <html>
                  <body>
                      <p>Hello, world</p>
                  </body>
              </html>
              """;

String query = """
               SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB`
               WHERE `CITY` = 'INDIANAPOLIS'
               ORDER BY `EMP_ID`, `LAST_NAME`;
               """;

Records (Preview)

Records provide a compact syntax for declaring classes, reduce the POJO boilerplate by providing the default implementation for constructors, accessors, equals(), hashCode() and toString()

You can think record as Lombok @Value

record Book(int id, String title) {
}

@Test
public void testRecord() {
    Book b = new Book(1, "Java 14");
    int id = b.id();
    String title = b.title();

    assertThat(id).isEqualTo(1);
    assertThat(title).isEqualTo("Java 14");
}

The Book record is compiled as the following

final class Book extends java.lang.Record {
    private final int id;
    private final java.lang.String title;

    public Book(int id, java.lang.String title) { /* compiled code */ }

    public java.lang.String toString() { /* compiled code */ }

    public final int hashCode() { /* compiled code */ }

    public final boolean equals(java.lang.Object o) { /* compiled code */ }

    public int id() { /* compiled code */ }

    public java.lang.String title() { /* compiled code */ }
}

Pattern Matching for instanceOf (Preview)

Pattern matching allows conditional extraction of components from objects to be expressed more concisely and safely

PatternMatchingForInstanceOf.java

package com.hellokoding.java.java14;

import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class PatternMatchingForInstanceOf {
    public String instanceOf(Object o) {
        if (o instanceof Book) {
            Book b = (Book) o;
            if (b.id() == 1) {
                return b.title();
            }
        }

        return "";
    }

    public String instanceOfWithPatternMatching(Object o) {
        if (o instanceof Book b && b.id() == 1) {
            return b.title();
        } else {
            return "";
        }
    }

    @Test
    public void testInstanceOf() {
        Book b = new Book(1, "Java 14");
        String s = instanceOfWithPatternMatching(b);

        assertThat(s).isEqualTo("Java 14");
    }
}

Remove the Concurrent Mark Sweep (CMS) Garbage Collector

Trying to use CMS via the -XX:+UseConcMarkSweepGC option will result in the following warning message:

Java HotSpot(TM) 64-Bit Server VM warning: Ignoring option UseConcMarkSweepGC; \
support was removed in <version>

and the VM will continue execution using the default collector

Follow HelloKoding