Remarkable features in Java 14

4 minute read

coffee

In this post we are going to talk about the new features in Java SE 14 and its open source Java Development kit (JDK 14) that was released on March 17th 2020 (yes during the covid-19 lock-down) and we will see also how we can take advantage of this new features to develop.

JEP-305: Pattern matching for instanceof (preview)

To reduce the number of casts in the Java applications a new feature has been introduced in this version. It’s called Pattern matching for instanceof and to understand it we will use an example:

In older versions of Java when we don’t know if an object is an instance of a class we have to do something like this:


if(object instanceof String){
	String value = (String)object;
	value.contains ...
}

Now with this new feature we will be able to do this:


if(object instanceof String s){
	s.contains ...
}

Notice that we don’t have to do the cast like in previous versions. This will reduce the bolierplate code that we had to do everytime that we were using an instanceof.

To use this feature within Intellij you have to enable preview features and accept the warning that you are using a preview feature. If you don’t enable preview features and you want to try this you will get an error saying “patterns are not supported at language level 14” and your code will not compile.

To enable preview features like this you have to go to File > Project structure > Project settings > Project

project settings

And then in the project language level dropdown look for the Java14 preview option.

accept preview features

In my opinion, Java code that is using instanceof has poor design and is not using polimorphism the right way. However, If you have to deal with instanceof in your legacy code you can take advantage of this new feature ;)

More info in JEP 305 link.

JEP-358: Detailed message in NullPointerExceptions

This can be really useful because when encountering a null pointer, the JVM analyses the program to determine which reference was null and provide more details in the NullPointerException.getMessage(). Also the method, filename and line number are returned.

This option is disabled by default, to active it we need to use -XX:+ShowCodeDetailsInExceptionMessages. If you want to know how to configure it I share with this post where you can see how to do the configuration.

More info can be found in the JEP 358

JEP-359: Records (preview)

Records is a new kind of declaration in Java programming language. Like an enum a record is a restricted form of class. Java has been criticized for being a verbose programming language and this goes in the direction to reduce the boilerplate code.

Think about classes that only have state without any logic that have constructor, getters, setters, equals, hashcode and toString. All these methods have to be created every time we want to create a class that just carries data. For example:

record Appartment(int squareMeters) { }

A record acquires many standard members automatically.

  • a private final field for each component declared.
  • a public read accessor for each member.
  • a public constructor
  • implementatons of equals and hashcode
  • an implementation of toString()

All components are final by default, so this new way to define a data carrier in Java embraces inmutability by default policy.

What if we need to control the input arguments that we receive? In the following code snippet we can see how to do it.

record Appartment(int squareMeters) {
  public Appartment {
    if (squareMeters<=0)  /* referring here to the implicit constructor parameters */
      throw new IllegalArgumentException(String.format("(%d)", squareMeters));
  }
}

More info can be found in JEP 359

JEP-361: Switch expressions

How many times we had to deal with switch case expressions? Are you familiar with the usage of break if you don’t remember, here is a java code snipped.

switch (month) {
    case JANUARY:
    case FEBRUARY:
    case MARCH:
        System.out.println(6);
        break;
    case APRIL:
        System.out.println(7);
        break;
    case :
    case MAY:
        System.out.println(8);
        break;
    case JUNE:
        System.out.println(9);
        break;
}

A new form of switch label, “case L ->”, has been added to this new version and now only the code to the right of the label is going to be executed if the label is matched. Also, multiple constants per case are allowed, separated by commas. The previous code can now be written like this:

switch (month) {
    case JANUARY, FEBRUARY, MARCH -> System.out.println(6);
    case APRIL  -> System.out.println(7);
    case MAY -> System.out.println(8);
    case JUNE   -> System.out.println(9);
}

More info can be found in JEP 361

JEP-368: Text blocks

In this new feature we will be able to print a multi-line string literal that avoids the need to scape sequences.

Using “one-dimensional” string literals

String query = "SELECT `EMPLOYEE_ID`, `SUR_NAME` FROM `EMPLOYEE_TB`\n" +
               "WHERE `CITY` = 'BARCELONA'\n" +
               "ORDER BY `EMPLOYEE_ID`, `SUR_NAME`;\n";

Using a “two-dimensional” block of text

String query = """
               SELECT `EMPLOYEE_ID`, `SUR_NAME` FROM `EMPLOYEE_TB`
               WHERE `CITY` = 'BARCELONA'
               ORDER BY `EMPLOYEE_ID`, `SUR_NAME`;
               """;

From now on embedding a snippet of HTML, XML, SQL, or JSON in a string literal will be easier than before.

For more information about this feature you can read JEP 368

Conclusion

In this post we have seen the more remarkable features in Java 14. Pattern matching for instanceof and Records are just preview features and should not be used in a production environment yet. The full release of this function is expected in java 15.

I won't give your address to anyone else, won't send you any spam, and you can unsubscribe at any time.
Disclaimer: Opinions are my own and not the views of my employer

Updated:

Comments