By the end of this article you will have learned

  • Six useful New Java features

At about 1,760 words, this is about as long as Enrique Iglesias’s “Ring My Bells.”

Since 2018, Java has adopted a strategy of releasing new versions every six months. This strategy has kept Java fresh and alive, and in this article, I’ll bring you six useful new Java features.

1. Optioal class

NullPointerException is the most classic of all Java exceptions. I’m sure you’re all familiar with it, and it often shows up out of the blue, causing headaches. Fortunately, Java 8 introduced Optional classes, and Java 10 perfected this mechanism.

Essentially, the Optional class allows you to wrap a variable and then use the wrapper’s methods to deal more concisely with Null.

Let’s look at a comparison example:

Example 1.1 does not use a null pointer to the Optional class

public class MyClass { public static void main(String args[]) { InnerClass innerClass = null; NullPointerException System.out.println("innerClass = "+ innerclass.getName ())); } } class InnerClass { String name = ""; public String getName() { return this.name; }}Copy the code

Now how can we use Optional to avoid this situation?

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

Example 1.2 uses a null pointer to the 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 the 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

We are all familiar with Data Transfer Object (DTO), which is usually used to store and Transfer Data stored in databases and file systems. The Record keyword was introduced in Java 14, and Java15 improves on it.

Example 3.1 shows how to define a DTO before the introduction of 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 the code

As we can see, the example above is full of verbose boilerplate code. We can now use the Record keyword to simplify the 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 the code

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

Also, note that the Record class cannot be subclassed.

4. New string methods

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

4.1 New string methods in Java 10

  • IsBlank (): Returns true if the string is empty or contains only Spaces (including Tab).
  • Lines (): Splits a string into a string stream, with each string containing one line. Each line is separated by /r or /n or /r/n.

4.4.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 the code
  • Strip (), stripTrailing(), stripTrailing(): Remove blank from start and end, start only and end only respectively.
  • Repeat (int times): Returns a string taken from the original string and repeated the specified number of times.
  • ReadString (): Reads the string directly from the file path.

Cases of 4.1.2 readString ()

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

4.2 Java 12 new string methods

  • Indent (int level): Adjusts the indentation of a string line by adding or removing Spaces at the beginning of each string line.
  • Transform (Function f): Applies the given lambda expression to a string.

5. Switch expression

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

Java 13 goes a step further by introducing the yield keyword. Use the yield keyword to jump out of the current switch block and return a value.

Java 14 includes the new Switch expression syntax as a complete function.

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

Example 5.1 The 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 the code

This code is pretty verbose now, so let’s see how we can 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 the code

6. Text block

Java 13 solves the long-standing annoyance of handling complex text strings in Java by introducing text blocks. Java 14 improves this support.

Things like JSON, XML, and SQL can drive you crazy with multi-layer nested escapes. In Java, embedding a fragment of HTML, XML, SQL, or JSON into a string literal usually requires extensive editing through escape and concatenation before the code containing the fragment can be compiled. The segment is often difficult to read and difficult to maintain.

Take a look at the following example where the new text block syntax is used to create a JSON fragment.

Example 6.1 uses JSON for text blocks

class TextBlock { public static void main(String args[]) { String json = """ { "name" : "Jay", "age" : "18" } """; System.out.println(json); }}Copy the code

In the example above, you don’t see an escape character, notice the syntax of triple double quotes.

7. Sealed class

Java 15 introduced 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 lies in the fact that extensibility can be limited to a predictable and controllable range through closed classes, which provides new possibilities for interface design and implementation. In combination with type testing, the licensing classes can be exhausted, which gives us more control over the security and robustness of our code.

Example 7.1 Enclosing class

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

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

8. Conclusion

That’s my summary of six useful new Java features. Do you get it?

Thanks for watching yijun@Monday Commuter Radio. If you feel good, quickly give me three support, let’s next period see each other.