Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the new features of Java14

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "what are the new features of Java14", friends who are interested may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the new features of Java14.

1. Switch expression

The switch expression in Java 14 will be permanent.

In previous releases, switch expressions were just a feature of the "preview" phase. I would like to remind you that the purpose of the features in the "preview" phase is to collect feedback, which may change at any time, and may even be removed based on the feedback, but usually all preview features end up fixed in Java.

The advantage of the new switch expression is that there is no default skip behavior (fall-through), it is more comprehensive, and expressions and combinations are easier to write, so bug is less likely. For example, switch expressions can now use arrow syntax, as follows:

Var log = switch (event) {case PLAY-> "User has triggered the play button"; case STOP, PAUSE-> "User needs a break"; default-> {String message = event.toString (); LocalDateTime now = LocalDateTime.now (); yield "Unknown event" + message + "logged on" + now;}

2. Text block

One of the preview features introduced in Java 13 is text blocks. With a text block, the literal amount of a string with multiple lines can be easily written. This feature is previewed for the second time in Java 14, and some changes have taken place. For example, formatting multiline text may require writing many string concatenation operations and escape sequences. The following code demonstrates an example of HTML:

String html = "" + "\ n\ t" + "+"\ n\ t\ t "+"\ "Java 14 is here!\"+"\ n\ t "+" + "\ n" + "

With a text block, this process can be simplified, and more elegant code can be written simply by using three quotes as the opening and closing tags of the text block:

String html = "Java 14 is here!"

Compared with ordinary string literals, text blocks are more expressive.

Java 14 introduces two new escape sequences. First, you can use the new\ s escape sequence to represent a space. Second, you can use a backslash\ to avoid inserting newline characters at the end of the line. This makes it easy to break a long line into multiple lines in a text block to increase readability.

For example, you can now write multiline strings as follows:

String literal = "Lorem ipsum dolor sit amet, consectetur adipiscing" + "elit, sed do eiusmod tempor incididunt ut labore" + "et dolore magna aliqua."

Using the\ escape sequence in a text block can be written like this:

String text = "" Lorem ipsum dolor sit amet, consectetur adipiscing\ elit, sed do eiusmod tempor incididunt ut labore\ et dolore magna aliqua.\ ""

3. Pattern matching of instanceof

Java 14 introduces a preview feature that eliminates the need to write code that is judged by instanceof and then cast. For example, the following code:

If (obj instanceof Group) {Group group = (Group) obj; / / use group specific methods var entries = group.getEntries ();

Using this preview feature, you can reconstruct to:

If (obj instanceof Group group) {var entries = group.getEntries ();}

Since the conditional check requires obj to be of type Group, why specify obj as type Group in the conditional code block as in the first piece of code? This can lead to errors.

This more concise syntax removes most of the cast in Java programs.

JEP 305 explains this change and gives an example from Joshuoa Bloch's book "Effective Java" that demonstrates the following two equivalent ways of writing:

@ Override public boolean equals (Object o) {return (o instanceof CaseInsensitiveString) & & ((CaseInsensitiveString) o) .s.equals IgnoreCase (s);}

The redundant CaseInsensitiveString cast in this code can be removed and converted to the following ways:

@ Override public boolean equals (Object o) {return (o instanceof CaseInsensitiveString cis) & & cis.s.equalsIgnoreCase (s);}

This preview feature is worth trying because it opens the door to more generic pattern matching. The idea of pattern matching is to provide a convenient syntax for the language to extract components from objects according to specific conditions. This is the use case of the instanceof operator, because the condition is type checking, and the extraction operation requires calling the appropriate method or accessing a specific field.

In other words, the preview feature is just the beginning, and it will certainly reduce more code redundancy in the future, thus reducing the likelihood of bug.

4 、 Record

Another preview feature is record. Like other preview features described earlier, this preview feature conforms to the trend of reducing redundant code in Java and helps developers write more accurate code. Record is mainly used for domain-specific classes, and its displacement function is to store data without any custom behavior.

Let's cut to the chase and give an example of the simplest domain class: BankTransaction, which represents a transaction and contains three fields: date, amount, and description. There are several aspects to consider when defining a class:

Constructor

Getter method

ToString ()

HashCode () and equals ()

The code for these parts is usually automatically generated by IDE and takes up a lot of space. Here is the complete generated BankTransaction class:

Public class BankTransaction {private final LocalDate date; private final double amount; private final String description; public BankTransaction (final LocalDate date, final double amount, final String description) {this.date = date; this.amount = amount; this.description = description } public LocalDate date () {return date;} public double amount () {return amount;} public String description () {return description } @ Override public String toString () {return "BankTransaction {" + "date=" + date + ", amount=" + amount + ", description='" + description +'\'+'}';} @ Override public boolean equals (Object o) {if (this = = o) return true If (o = = null | | getClass ()! = o.getClass ()) return false; BankTransaction that = (BankTransaction) o; return Double.compare (that.amount, amount) = = 0 & & date.equals (that.date) & & description.equals (that.description);} @ Override public int hashCode () {return Objects.hash (date, amount, description) }}

Java 14 provides a way to address this redundancy and to articulate the purpose more clearly: the sole purpose of this class is to integrate the data. Record provides implementations of equals, hashCode, and toString methods. Therefore, the BankTransaction class can be refactored as follows:

Public record BankTransaction (LocalDate date, double amount, String description) {}

With record, you can "automatically" get the implementation of equals,hashCode and toString, as well as constructors and getter methods.

To try this example, you need to compile the file with the preview flag:

Javac-enable-preview-release 14 BankTransaction.java

The field of record is implied as final. Therefore, the fields of record cannot be reassigned. Note, however, that this does not mean that the entire record is immutable, and that objects stored in fields can be mutable.

5 、 NullPointerException

Some people think that throwing NullPointerException exceptions should be treated as a new "Hello World" program, because NullPointerException will encounter sooner or later. Joking aside, this exception does cause trouble because it often appears in the logs of the production environment and makes debugging very difficult because it does not show the original code. For example, the following code:

Var name = user.getLocation (). GetCity (). GetName ()

Before Java 14, you might get the following error:

Exception in thread "main" java.lang.NullPointerException at NullPointerExample.main (NullPointerExample.java:5)

Unfortunately, if line 5 is an assignment statement that contains multiple method calls (such as getLocation () and getCity ()), any one of them may return null. In fact, the variable user may also be null. Therefore, it is impossible to determine who caused the NullPointerException.

In Java 14, the new JVM feature can display more detailed diagnostic information:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Location.getCity ()" because the return value of "User.getLocation ()" is null at NullPointerExample.main (NullPointerExample.java:5)

The message contains two clear components:

Consequence: Location.getCity () cannot be called

Reason: the return value of User.getLocation () is null

The enhanced version of diagnostics is valid only if you run Java with the following flag:

-XX:+ShowCodeDetailsInExceptionMessages

Here is an example:

Java-XX:+ShowCodeDetailsInExceptionMessages NullPointerExample

In future releases, this option may become the default.

This improvement works not only for method calls, but also for other areas that may lead to NullPointerException, including field access, array access, assignment, and so on.

At this point, I believe you have a deeper understanding of "what are the new features of Java14?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report