JDK 14 was released a few days ago and includes 16 new features.

In fact, from Java8 to Java14, there are not many features that have really changed the way programmers write code, and this article will take a look at some of them.

Lambda expressions

Lambda expressions are one of the most important new features in Java 8. Lambda allows functions to be taken as arguments to a method.

The syntax of a lambda expression is as follows:

(parameters) -> expression
或
(parameters) ->{ statements; }Copy the code

For example:

// 1. No arguments, return value 5 () -> 5 // 2. Take an argument (numeric type) and return twice its value x -> 2 * x // 3. Take two arguments (numbers) and return their difference (x, y) -> x -- y // 4. Accept 2 int integers and return their sum (int x, int y) -> x + y Take a string object and print it on the console without returning any value (looks like returning void) (string s) -> system.out.print (s)Copy the code

Lambda expressions have the advantages of conciseness, easy parallel computation and the future programming trend, but at the same time, they will bring debugging difficulties and high cost for newcomers to understand.

Streams API

In addition to Lambda expressions, the Stream API was introduced in Java 8, which finally brought Java into the functional programming fold.

Stream provides a high-level abstraction of Java collection operations and expressions in an intuitive manner similar to querying data from a database with SQL statements.

The Stream API can greatly improve the productivity of Java programmers, allowing programmers to write efficient, clean, and concise code.

Here is a series of operations on the collection via the Stream API:

List<String> strings = Arrays.asList("Hollis", "HollisChuang", "hollis", "Hello", "HelloWorld", "Hollis");
Stream s = strings.stream().filter(string -> string.length()<= 6).map(String::length).sorted().limit(3)
            .distinct();Copy the code

Moreover, Stream also supports parallel streams, which is much better in performance than traditional for loops. (Detailed usage: Stream, an elegant posture for handling collections in Java 8)

Lambda expressions and the Stream API have been around for six years now, and many of you have already used these features in your work.

Although there are many different opinions on the use of these two syntax, the author still thinks that this feature is very useful, as long as the code is not too “showy” with long streaming operations and the code is not too readable.

New date and time API

Prior to Java 8, the date-time API had many problems: Date was not thread-safe, both java.util and java.sql packages had Date classes, Date classes did not provide internationalization, and there was no time zone support.

So Java 8 has further enhanced Date and Time handling with the release of a new date-time API (JSR 310).

The new java.time package covers all operations that handle date, time, date/time, time zone, instants, during, and clock.

Common operations are as follows:

LocalDateTime currentTime = localDatetime.now (); System.out.println(" currentTime: "+ currentTime); LocalDate today = localdate.now (); LocalDate date1 = LocalDate.of(2014, 01, 14); If (date1.equals(today)){} LocalTime time = localtime.now (); LocalTime newTime = time.plusHours(2); // adding two hoursCopy the code

However, to be honest, the time API in Java8 is not used by the authors in their daily work, mainly because there is a lot of historical code, and still rely on Date and other types, using the new API will face conversion issues.

Local variable type inference

In versions prior to Java 10, we wanted to define when defining local variables. We need to provide an explicit type on the left side of the assignment and an implementation type on the right side of the assignment:

MyObject value = new MyObject();Copy the code

In Java 10, local variable type inference is provided and variables can be declared using var:

var value = new MyObject();Copy the code

Local variable type inference will introduce the “var” keyword without explicitly specifying the type of a variable.

In fact, the so-called local variable type inference is also the syntactic sugar that Java 10 provides to developers. Although var is defined in the code, it is not known to the virtual machine, and the real type of the variable is used instead of var when the Java file is compiled into a class file.

Switch

Switch expressions were introduced as a preview feature in JDK 12. This feature was modified in Java 13 to introduce yield statements, which are used to return values.

Later in Java 14, this functionality was officially provided as a standard feature.

In the past, we wanted to return the content in switch, or rather cumbersome, the general syntax is as follows:

int i;
switch (x) {
    case "1":
        i=1;
        break;
    case "2":
        i=2;
        break;
    default:
        i = x.length();
        break;
}Copy the code

Use the following syntax in JDK13:

int i = switch (x) { case "1" -> 1; case "2" -> 2; default -> { int len = args[1].length(); yield len; }};Copy the code

or

int i = switch (x) { case "1": yield 1; case "2": yield 2; default: { int len = args[1].length(); yield len; }};Copy the code

After that, there is another keyword in the switch that can be used to jump out of the switch block: yield, which returns a value. The difference is that a return jumps directly out of the current loop or method, whereas yield jumps only out of the current switch block.

Text Blocks

A Text Blocks preview feature is available in Java 13, and a second version preview is available in Java 14.

A text block, a block of text, is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, and lets the developer control the formatting when needed.

We used to copy a text string from the outside into Java, which would be automatically escaped, such as the following string:

 <html>
  <body>
      <p>Hello, world</p>
  </body>
</html>Copy the code

Copying it into a Java string displays the following:

"<html>\n" +
"    <body>\n" +
"        <p>Hello, world</p>\n" +
"    </body>\n" +
"</html>\n";Copy the code

In JDK 13, you can use the following syntax:

"""
<html>
  <body>
      <p>Hello, world</p>
  </body>
</html>
""";Copy the code

Using “”” as the beginning and end of a text block allows you to place a multi-line string in it without any need for escape. It looks very clean.

Such as a common SQL statement:

String query = """ SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB` WHERE `CITY` = 'INDIANAPOLIS' ORDER BY `EMP_ID`, `LAST_NAME`; "" ";Copy the code

It looks a little bit more intuitive and refreshing.

Records

Java 14 includes a new feature called EP 359: Records,

The goal of Records is to extend the Java language syntax by providing a compact syntax for declarative classes for creating classes that are “fields, just fields, and nothing but fields.” By making this declaration on a class, the compiler can automatically create all methods and have all fields participate in methods like hashCode(). This is a preview feature in JDK 14.

Use the record keyword to define a record:

record Person (String firstName, String lastName) {}Copy the code

Record solves a common problem with using classes as data wrappers. Pure data classes are dramatically reduced from a few lines of code to one. (See: Java 14 release: Can you define a class without “Class”? And kill Lombok!)

conclusion

Those are some of the major new features in Java 8 through Java 14 that could affect the way developers write code.

I don’t know if you’ve noticed, but some of the features introduced in recent releases make Java and languages like Kotlin look more and more like each other…

These new features do simplify the code to a certain extent and make the development process more efficient, but to be honest, they are not good enough to attract a large number of developers to abandon Java 8 for mass migration!

I’ll use Java 8. But there are new features to learn about.