7 Reasons: Upgrade from Java 8 to Java 17 [Translation]

7 reasons to upgrade from Java 8 to Java 17

Unleash the full power of Java. [Manual dog head]

Introduction

From Java8 to Java18, Java has gone through a long development process (Java20 is not a long-term maintenance version). At the same time, since Java 8, many changes have taken place in the Java ecosystem. One of the most obvious changes is the change in Java version release cadence. Java 8 was released in 2014, while Java 17 was released in 2021, a seven-year gap between the two versions. However, in September 2017, Mark Reinhold, the chief architect of the Java platform, issued a proposal to reduce Java's feature update cycle from a new version every two years to a new version every six months. The proposal was adopted and became effective shortly after it was proposed. Therefore, developers of the Java ecosystem can use the latest version of Java features faster.

If you, like me, have been using Java 8 for a long time and feel that you need to learn new features of Java, then this article is for you.

Since Java8, many new features have been added to the JDK, but obviously not all of them are useful, easy to use, and popular with everyone. Therefore, in this article, I list the most popular functions of Java programmers since Java8. You can use this article as a reference for learning. At the same time, you can find your colleagues to brag about.

key function

1.Local Variable Type Inference[local variable type inference]

Arguably the most popular feature added since Java 8, local variable type inference allows you to declare local variables without specifying their type. The type when the actual code is executed is inferred from the content on the right side of the expression. This function is also called the var type. (Yes, gradually Js).

For example: var a = 1

Java8 uses local variables

URL url = new URL("https://www.baidu.com");
System.out.println(url.getClass());

After Java10 has local variable type inference

var url = new URL("https://www.baidu.com");
System.out.println(url.getClass());

The final output of the above code is exactly the same, but obviously, after Java10, there is no need to declare specific local variable types.

ps: lombok in Java8 provides a similar function, which is also var, but it needs to import the package.

import lombok.var;
import org.junit.jupiter.api.Test;
import java.net.MalformedURLException;
import java.net.URL;
//使用 lombok
public class JdkTests {
    @Test
    public void test1() throws MalformedURLException {
        var url = new URL("https://www.baidu.com");
        System.out.println(url.getClass());
    }
}

2.switch expression[switch expression enhancement]

When using switch expressions in Java 14, you don't have to use the break keyword to break out of the switch statement, and you don't have to use the return keyword on each switch case to return a value; instead, you can return the entire switch expression. This enhanced switch expression makes the whole code look cleaner and easier to read.

Use switch in Java8

int flag = 1;
switch(flag) {
    case 1:
        System.out.println("hello");
        break;
    case 2:
        System.out.println("world");
        break;
    case 3:
        System.out.println("hello world");
        break;
    case 4:
        System.out.println("hello");
        break;
    default:
        System.out.println("haha");
}

Use switch after Java14

int flag = 1;
switch(flag) {
    case 1,4 -> System.out.println("hello");
    case 2 -> System.out.println("world");
    case 3 -> System.out.println("hello world");
    default -> System.out.println("haha");
}

3.Text blocks[text block]

Text blocks are a new feature in Java 15 that allow you to create multi-line strings without using escape symbols. It is very comfortable when writing Json in the code and want to break the line. Through the following example, you can see how concise and comfortable the code can be if you use text blocks.

Java8

String json = "{\n" +
        "  "id": 3,\n" +
        "  "username": "fake_data",\n" +
        "  "password": "fake_data",\n" +
        "  "ips": [\n" +
        "    "fake_data"\n" +
        "  ],\n" +
        "  "firstLoginTime": 29,\n" +
        "  "lastLoginTime": 69,\n" +
        "  "failedAttempts": 62,\n" +
        "  "lockedUntil": "2013-11-20 20:23:23"\n" +
        "}";

After Java15

String json = """
    {"id": 3, 
    "username": "fake_data", 
    "password": "fake_data", 
    "ips": ["fake_data"], 
    "firstLoginTime": 29, 
    "lastLoginTime": 69, 
    "failedAttempts": 62, 
    "lockedUntil": "2013-11-20 20:23:23"}
""";
System.out.println(json);

4.Records[record class]

The record class is a new way of declaring classes introduced by Java14 (before and after class). Through this keyword, you can create a class similar to POJO with less code (harmful, it is an ordinary Java class, such as User class, Student class, etc., or entity class, which does not need to be divided into details) . Compared with the past, most developers used Lombok to simplify the writing of POJO classes (no need to write get set, etc.), but now, using record, you don't need to use any third-party library, you can put the code Write more concisely. In the example below, you can see how concise the record code can be.

Java8

public class User {
    private String name;
    private String password;
    public User() {
    }
    
    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

Java8 uses lombok

@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
    private String name;
    private String password;
}

use record

public record User(String name,String password) {}

test code

@Test
public void test7() {
    User user = new User("2","3");
    System.out.println(user.name());
}

5.Pattern matching for instanceof[instanceof pattern matching]

instanceof pattern matching is a new feature added in Java 16. It allows you to use the instanceof operator as an expression and return the converted object (no coercion required). Useful when dealing with nested if-else statements. In the example below, you can see how we use the instanceof operator to return the Employee object without casting.

Java8

if (obj instanceof Employee){
    Employee emp = (Employee)obj;
    return emp.getName();
}

Use instanceof pattern matching

if (obj instanceof Employee emp){
    return emp.getName();
}

6.Sealed classes[Sealed class]

Enclosed classes are a new feature added in Java 17. It allows you to restrict the inheritance of a class or interface to a limited set of subclasses. To put it simply, you have a UserService interface that you only want to be implemented by UserServieImpl. It was not restricted before, but now with the Sealed classes feature, how to do it?

Use the sealed modifier to describe a class as a sealed class, and use the permits keyword to specify which types can inherit or implement this class. Note that what sealed can modify is a class (class) or an interface (interface), so the position of the permits keyword should be after extends or implements.

example:

Use sealed to declare that a UserService can only be implemented by UserServiceImpl and UserServiceFinalImpl.

 
 

kotlin

copy code

public sealed interface UserService permits UserServiceImpl, UserServiceFinalImpl{ }

If you want to implement the interface declared by sealed (the same is true for inherited classes), subclasses, or implementation classes, you need to modify it with final or non-sealed.

 
 

java

copy code

public final class UserServiceFinalImpl implements UserService{ } ​ public non-sealed class UserServiceImpl implements UserService{ }

The difference between the above two is:

A final modified implementation class cannot be further inherited, while a non-sealed modified implementation class can be further inherited.

 
 

scala

copy code

//进一步继承 public class UserServiceImplNonSealed extends UserServiceImpl{ }

7.Useful NullPointerException

NullPointerExceptions is a new feature added in Java 14. It allows you to get more information about NullPointerExceptions. This is very useful when you are debugging NullPointerExceptions. In the example below, you can see that the same code produces different NullPointerExceptions in Java 8 and Java 14, but in Java 14, you can get more information about the exception. (seeing more exception stack information can better locate bugs)

summary

I have not covered all the features added since Java 17 in this article, but I have covered the most popular ones. If you want to know more about the new features of Java, then I suggest you to check out the links provided below. 

Guess you like

Origin blog.csdn.net/Jernnifer_mao/article/details/131249419