After working as a programmer for so long, how many new features of Java 8-15 do you know?

Posted by kimberlc on Sun, 23 Jan 2022 10:59:14 +0100

Since 2018, Java has adopted the strategy of releasing a new version every six months. This strategy keeps Java fresh and strong vitality. In this article, I will bring you six practical new Java features.

1. Optional class

NullPointerException is the most classic of all Java exceptions. Everyone must be familiar with it. It often appears unexpectedly and gives people a headache. Fortunately, Java 8 introduces the Optional class for us, and Java 10 improves this mechanism.

In essence, the Optional class allows you to wrap a variable and then use the wrapper method to deal with Null more concisely.

Let's take a comparison example:

Example 1.1 null pointer of Optional class not used

public class MyClass {
    public static void main(String args[]) {
        InnerClass innerClass = null;
        // Here, a null pointerexception is generated by method access to the variable with null reference
        System.out.println("innerClass = " + innerClass.getName());
    }
}

class InnerClass {
    String name = "";

    public String getName() {
        return this.name;
    }
}

Copy code

Now how can we use Optional to avoid the above situation?

The Optional class has an isPresent() method, which you can use as an if check. However, we use a shorter method, ifPresent(), to continue running the code only if the value exists.

Example 1.2 using null pointer of Optional class

public class MyClass {
    public static void main(String args[]) {
        InnerClass innerClass = null;
        Optional fooWrapper = Optional.ofNullable(innerClass);
        fooWrapper.ifPresent(x -> System.out.println("innerClass = " + x.getName()));
    }
}

class InnerClass {
    String name = "";

    public InnerClass(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }
}
Copy code

Of course, when you use the Optional class, you can also use the orElse() method to call a default value, or consider orElseGet() to provide a function reference.

2. Record class

DTO(Data Transfer Object) is familiar to us. It is usually used to store and transfer data stored in databases, file systems, etc. The Record keyword is introduced into Java 14, and Java 15 has improved on this basis.

Example 3.1 shows how to define a DTO before introducing the Record class.

Example 3.1 a simple DTO

public class MyClass {
    public static void main(String args[]) {
        Student student = new Student("Jay", 18);
        // . . .
    }
}
class Student {
    String name;
    Integer age;
    public Student(String name, Integer age){
        this.name = name;
        this.age = age;
    }
    public String getName(){
        return this.name;
    }
    public Integer getAge(){
        return this.age;
    }
}
Copy code

We can see that the above example is full of verbose template code. Now we can use the Record keyword to simplify DTO.

Example 3.2 using the Record keyword

public class MyClass {
    public static void main(String args[]) {
      Student student = new Student("Jay", 18);

      // . . .
    }
}

public record Student(String name, Integer age) {}
Copy code

The Record type also defines the default implementations of equals(), hashCode(), and toString(), and also allows developers to override these implementations. We can also provide a custom constructor.

In addition, please note that the Record class cannot be subclassed.

4. New string method

In Java 10 and Java 12, several useful new String methods have been added. In addition to String manipulation, two new methods are introduced to simplify text file access.

4.1 new string method in Java 10

  • isBlank(): returns true if the string is empty, or if the string contains only spaces (including tabs).
  • lines(): splits a string into a character stream, and each string contains one line. Each row is separated by / r or / N or / r/n.

Example 4.1.1 lines()

import java.io.IOException;
import java.util.stream.Stream;
public class MyClass {
    public static void main(String args[]) throws IOException{
      String str = "test \ntest2 \n\rtest3 \r";
      Stream lines = str.lines();
      lines.forEach(System.out::println);
    }
}

/*
outputs:
test
test2
test3
*/
Copy code
  • Strip(), stripleading(), striptraining(): delete whitespace from the beginning and end, beginning only and end only, respectively.
  • repeat(int times): returns a string taken from the original string and repeated a specified number of times.
  • readString(): read the string directly from the file path.

Example 4.1.2 readString()

Path path = Path.of("test.txt"); 
String text = Files.readString(path);
Copy code
  • Writestring (path): write the string directly to the file with the specified path.

4.2 new string method in Java 12

  • indent(int level): add or remove spaces at the beginning of each line of string to adjust the indentation of the string line.
  • transform(Function f): applies the given lambda expression to a string.

5. Switch expression

Java 12 introduces a new switch expression that allows switch to be used inline in statements. In other words, the switch expression returns a value.

Java 13 goes further and introduces the yield keyword. Using the yield keyword, you can directly jump out of the current switch block and return a value.

Java 14 takes the new switch expression syntax as a complete function.

Let's look at the similarities and differences between new and old Switch expressions.

Example 5.1 ancient Java Switch

public class Test {
    public static void main(String args[]) {
        int size = 3;
        String message = "";

        switch (size) {
            case 1:
                message = "one";
                break;
            case 3:
                message = "three";
                break;
            default:
                message = "unknown";
                break;
        }

        System.out.println("The number is " + message);
    }

}
Copy code

At present, this code is rather verbose. Let's see how we simplify it.

Example 5.2 new Java Switch

public class Test {
        public static void main(String args[]) {
            int size = 3;
            var message = switch (status) {
                case 1 -> "one";
                case 2 -> "two";
                case 3 -> "three";
                default -> {
                    System.out.println("closed");
                    yield "unknown";
                }
            };
            System.out.println("The number is " + message);
        }

}
Copy code

6. Text block

Java 13 solves the problem of dealing with complex text strings in Java for a long time by introducing text blocks. Java 14 improves this support.

Things like JSON, XML and SQL will drive you crazy because of multi-level nested escape. In Java, embedding fragments of HTML, XML, SQL or JSON into a literal string usually requires a lot of editing through escape and connection, and then the code containing the fragment can be compiled. This clip is usually difficult to read and difficult to maintain.

Let's look at the following example, in which the new text block syntax is used to create a JSON fragment.

Example 6.1 JSON using text blocks

class TextBlock { 
  public static void main(String args[]) {
    String json = """
      {
        "name" : "Jay",
        "age" : "18"
      }
    """;

    System.out.println(json);
  }
}
Copy code

In the above example, you don't see an escape character. Please pay attention to the syntax of triple double quotation marks.

7. Sealed class - closed class

Java 15 introduces the concept of closed classes. In short, the new sealed keyword allows you to define which classes can subclass an interface.

The significance of closed classes is that the extensibility can be limited to the scope of prediction and control through closed classes, which provides new possibilities for interface design and implementation; By combining with type testing, license classes can be exhaustive, which allows us to better control the security and robustness of the code.

Example 7.1 closed class

public abstract sealed class Pet
    permits Cat, Dog, Bird {...}
Copy code

In the above example, we use the sealed keyword to specify which classes are allowed to extend the Pet class.

Original link: https://juejin.cn/post/7051348082826412039

Topics: Java Back-end