Java 14 is coming



According to Oracle, the release of Java 14 is scheduled for March 17. I wonder if the release date is related to St. Patrick's Day (which is celebrated on this day) or not we will find out very soon. Let's look at the innovations that will be available in the new Java and decide whether we will drink beer for joy or sorrow.

Records


A fundamentally new language feature, available in preview mode in Java 14. The main goal is to get rid of a lot of vermicelli in the code. Records should replace classes that are used only for storing data in fields without any described behavior. Define Record , and the compiler itself will generate the constructor, getters, equals () and hashCode (), toString () methods. Somewhere we already saw it, right, Mr. Lombok? The entry is as follows:

public record Person(String name, int age){}

In order to compile Record, you must download jdk14 and enter the following command:

javac —enable-preview —release 14 Person.java

We decompile and see what the compiler did:

public final class Person extends java.lang.Record {
    private final java.lang.String name;
    private final int age;

    public Person(java.lang.String name, int age) { /* 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 java.lang.String name() { /* compiled code */ }

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

So, instead of Record, we got a final class that inherits from the new, abstract Record class . And as expected, we got the generated getters, constructor, equals (), hashCode (), toString () . Note that all fields are marked as final , which means that we cannot redefine them, however, Record itself is not completely unchanged, because objects stored in fields can be mutable. A detailed discussion of Record can be found here .

Talkative NullPointerExceptions


More friendly will be NullPointerExceptions . No, the compiler still does not know how to fix NPE for us, but now the description of the exception will become more informative. We simulate the situation: we call NPE in Java 11 and Java 14. For example, we have a complex composition, typical of Entity , and to get the data, we need to call several objects from the source to get to the desired field, and so:

var street = message.getAuthor().getAddress().getStreet();

In Java 11, we get an old familiar error log that leaves the main question: Who is null? Message, Author, Address?

Exception in thread "main" java.lang.NullPointerException
	at Main.main(Main.java:11)

To run on Java 14, you need to compile the class in the same way as Record above:

javac —enable-preview —release 14 Main.java

And execute by adding a special flag:

java -XX:+ShowCodeDetailsInExceptionMessages --enable-preview Main

As a result of execution, we get the following output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Address.getStreet()" because the return value of "Author.getAddress()" is null
	at Main.main(Main.java:11)

As we can see, the message has become more informative, and we can see where exactly in the call chain NPE occurred .

Text blocks


Text blocks introduced back in Java 13 are also available in Java 14 as a preview feature. Let me remind you that their main task is to simplify the work with multi-line literals. A very convenient feature for writing SQL queries, HTML code, JSON . I think this is one of the features that will become very useful. Recall the syntax. For example, we need to write an SQL query . Prior to Java 13, we would use string concatenation to write a readable query, and the query would look something like this:

String sql = "SELECT name, age " +
                 "FROM PERSON" +
                 "WHERE name = \'Igor\'" +
                 "AND car=\'Niva\'";

Starting with Java 13, we can use a text block by writing a line between triple double quotes like this:


    String sql = """ 
                 SELECT name, age 
                 FROM PERSON
                 WHERE name = 'Igor'
                   AND car='Niva'
                 """;

Java 14 adds two new delimiters that can be used in text blocks. The first is a single space: \ s . The second is the newline character: \ .

Switch expressions


Starting with Java 14, switch expressions moves from a preview feature to a full feature. Let us briefly recall the features of the new operator:

  • Lambda syntax
  • Ability to use more than one expression in a case
  • Error output in case of incomplete coverage of the set of possible switch () values . In other words, if you use an enumeration:

    public enum  Car {
        NIVA, NEXIA, KIA
    }

    Then if you write switch () as follows, the compiler will throw an error that says that not all possible cases from the enumeration are listed:

    switch (car) {
        case NIVA -> System.out.println("Niva");
        case NEXIA -> System.out.println("Nexia");
    }
    // error: the switch expressions does not cover all possible input values.

  • The ability to return a value:

    var avto = switch (car) {
        case NIVA, KIA -> "Niva are better";
        case NEXIA -> "Nexia";
        default -> "Niva still better";
    };


Pattern matching


Pattern Matching is a new preview feature available in Java 14. There has been a lot of talk about it, many have been waiting for it, and here it is. The goal is to combine object type checking and its conversion in the instanceof operator . In other words, before Java 14 we would write like this:

Object obj = "Igor";

if (obj instanceof String) {
    String s = (String) obj;
    System.out.println(s.length());
}

Those. in order to use the methods of the class that the object is, you need to cast it to this class. Starting with Java 14, a new syntax is available in which instanceof combines the functions of validation and conversion:

Object obj = "Igor";

if (obj instanceof String s){
    System.out.println(s.length());
}

Conclusion


Java continues to evolve, making life easier for ordinary mortal developers. New features are designed to make the code cleaner, life easier, higher salaries. What do you think, which of the new features will win the love of the community?

All Articles