It’s been a week since Java 14 was released, and I’m going to open the box and take a look at some of the new features with the rest of you. We programmers should embrace the mentality of experimentation and curiosity, otherwise it is easy to be stuck in a rut and the technology stagnates. Let’s take a look at what’s new in Java 14.

The red lines are the ones I’m more interested in, and the rest don’t have much attraction for me, so I’ll skip them.

01. Download JDK 14

To unpack it, you need to download JDK 14. Otherwise, you can’t unpack it, right? There are two places to download: Oracle for commercial use and JDk.java.net for open source. Let’s go with the latter.

I am currently using a Windows operating system, so choose the Windows version of the ZIP package to download, remember to unzip when finished.

02. Upgrade IntelliJ IDEA

IDEA needs to be upgraded to early Access 2020.1 EAP, otherwise the new Java 14 features will not be supported.

The download address for the community edition is as follows:

[https://www.jetbrains.com/idea/nextversion/#section=windows](https://www.jetbrains.com/idea/nextversion/#section=windows)
Copy the code

When installing, you can uninstall the previous version or choose to keep it. With that done, let’s create a new Java 14 project.

01, instanceof

In order of new features, let’s start with Instanceof. The old-fashioned use of instanceof is as follows:

public class OldInstanceOf {
    public static void main(String[] args) {
        Object str = "Java 14 smells good.";
        if (str instanceofString) { String s = (String)str; System.out.println(s.length()); }}}Copy the code

You need to use instanceof to determine if STR is of type String in the if condition (step 1), then force STR to be a String in the if statement (step 2), and redeclare a variable for the strong assignment (step 3).

Three steps isn’t much, but I always thought there was a better syntax, and that’s what Java 14 came up with.

public class NewInstanceOf {
    public static void main(String[] args) {
        Object str = "Java 14 smells good.";
        if (str instanceofString s) { System.out.println(s.length()); }}}Copy the code

You can simply add a variable to the type of the if condition without having to force and declare new variables. Is it super neat? However, instanceof pattern matching is previewed in Java 14 and is disabled by default, so this code has a strange compilation error (instanceof pattern matching is not supported in Java 14).

So how do you solve this problem? The language version needs to be set manually in the project configuration.

Once that’s done, the compilation error is blown away. The output of the program is as follows:

10
Copy the code

That’s good. That smells good. Want to know what the Java compiler does for us behind the scenes? Take a look at the decompiled bytecode.

public class NewInstanceOf {
    public NewInstanceOf(a) {}public static void main(String[] args) {
        Object str = "Java 14 smells good.";
        String s;
        if (str instanceofString && (s = (String)str) == (String)str) { System.out.println(s.length()); }}}Copy the code

Before the if condition is judged, the variable s is declared first, and then the strong transformation s = (String) STR) is carried out in the if condition, and whether s and STR are equal is judged. It’s a really good feature that frees up the productivity of openers, and it’s strongly expected to be implemented in the next release.

02, Records

In a previous article, I talked about immutability of classes, which is defined like this:

public final class Writer {
    private final String name;
    private final int age;

    public Writer(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public int getAge(a) {
        return age;
    }

    public String getName(a) {
        returnname; }}Copy the code

So, for Records, a Record represents an unchanging state. Although it provides things like equals(), hashCode(), toString(), constructors, and getters for fields, it is not intended to replace mutable object classes (without setters) and the functionality Lombok provides.

Replace the Writer class with Records:

public record Writer(String name, int age) {}Copy the code

You see, one line of code. The point is that it’s more features-rich than the previous code, so let’s take a look at the decompiled bytecode:

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

    public Writer(java.lang.String name, int age) { /* compiled code */ }

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

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

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

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

    public int age(a) { /* compiled code */}}Copy the code

The class is final, the field is private final, and the constructor has two arguments, toString(), hashCode(), equals(), and getter methods, but without the get prefix. But there are no setter methods, which means that Records is really for immutable objects — authenticated. How do you use Records?

public class WriterDemo {
    public static void main(String[] args) {
        Writer writer = new Writer("Silent King II.".18);
        System.out.println("The toString." + writer);
        System.out.println("hashCode:" + writer.hashCode());
        System.out.println("name:" + writer.name());
        System.out.println("age:" + writer.age());

        Writer writer1 = new Writer("Silent King II.".18);
        System.out.println("equals:"+ (writer.equals(writer1))); }}Copy the code

The output of the program is as follows:

ToString: Writer[name= age=18]hashCode: 1130697218 Name: Age: 18 equals:true
Copy the code

Nice, nice. It will be easier to define immutable classes in the future. Hopefully this feature will be implemented in the next version.

03. Switch expressions

Switch expressions, which I explained in detail in a previous article, can be jumped to by clicking on a portal. Two weeks later, the switch expression has finally become normal. Congratulations.

I remember when this article was published to the Nuggets, all kinds of brainless diss were trolled, saying: “I thought you had some skills, but I didn’t expect to use Java 13, but we are still stuck in Java 8!” This is obviously a stuck in the past, which is not desirable and should not be the case for programmers. One of the simplest things is that Java 6 was a classic and was replaced by Java 8. As time goes on, Java 8 will eventually be replaced by a newer, more revolutionary version — there has to be progress.

Here’s a quick example of the switch expression:

public class SwitchDemo {
    enum PlayerTypes {
        TENNIS,
        FOOTBALL,
        BASKETBALL,
        PINGPANG,
        UNKNOWN
    }

    public static void main(String[] args) {
        System.out.println(createPlayer(PlayerTypes.BASKETBALL));
    }

    private static String createPlayer(PlayerTypes playerType) {
        return switch (playerType) {
            case TENNIS -> "Federer the Tennis player.";
            case FOOTBALL -> "Cristiano Ronaldo, soccer player.";
            case BASKETBALL -> "James the Basketball Player";
            case PINGPANG -> "Ma Long, table Tennis Player.";
            case UNKNOWN -> throw new IllegalArgumentException("Unknown"); }; }}Copy the code

In addition to using the new syntax ->, it can also be used as a return result.

04, Text Blocks

Before Text Blocks, if we wanted to concatenate multi-line strings, we needed a lot of double quotes and plus signs, which looked like old woman’s foot wrap. If you happen to concatenate some HTML-formatted text (as is the case with native SQL), the tedious work of formatting it with Spaces and wrapping it with line breaks (\n) can be a disaster for a developer.

public class OldTextBlock {
    public static void main(String[] args) {
        String html = "<html>\n" +
                " \n" +
                " 

Hello, world

\n"
+ " \n" + "</html>\n"; System.out.println(html); }}Copy the code

Java 14 is completely different:

public class NewTextBlock { public static void main(String[] args) { String html = """ <html> <body> <p>Hello, world</p> </body> </html> """; System.out.println(html); }}Copy the code

Redundant English double quotes, plus signs, line breaks, all gone. This is done simply by using three English double quotation marks. All I can say is, it smells, it smells!

05, thanks

Well, my dear readers, that’s all for this article, and the best programmers you can see here. Original is not easy, do not want a free ticket, please praise for this article, this will be my writing more high-quality articles of the strongest power.

If you feel that the article is a little help to you, please wechat search “Silent King two” for the first time to read, reply [666] [1024] more I prepared for you 500G HD teaching video (has been classified), as well as dfactory technology niu people finishing the face by a copy, the source of this article has been included in the code cloud, portal ~