Home > Java > JavaBase > body text

What are the new features of java14

王林
Release: 2020-06-20 13:33:43
Original
3220 people have browsed it

What are the new features of java14

1. Switch expression

In previous releases, switch expression was only a feature in the "preview" stage. I would like to remind you that the purpose of the features in the "preview" stage is to collect feedback. These features may change at any time, and based on the feedback results, these features may even be removed, but usually all preview features will be fixed in Java in the end. .

(Recommended tutorial: java introductory program)

The advantage of the new switch expression is that there is no longer a default skip behavior (fall-through), and more Comprehensive, and expressions and combinations are easier to write, so bugs are less likely to occur. For example, switch expressions can now use arrow syntax, as shown below:

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;
}
};
Copy after login

2. Text Blocks

One of the preview features introduced in Java 13 is text blocks. With text blocks, multi-line string literals are easy to write. This feature is getting its second preview in Java 14, and there are some changes. For example, formatting of multiline text may require writing many string concatenation operations and escape sequences. The following code demonstrates an HTML example:

String html = "<HTML>" +
"\n\t" + "<BODY>" +
"\n\t\t" + "<H1>\"Java 14 is here!\"</H1>" +
"\n\t" + "</BODY>" +
"\n" + "</HTML>";
Copy after login

With text blocks, this process can be simplified. Just use triple quotes as the start and end tags of the text block, and you can write more elegant Code:

String html = """
<HTML>
<BODY>
<H1>"Java 14 is here!"</H1>
</BODY>
</HTML>""";
Copy after login

Text blocks are more expressive than ordinary string literals.

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

For example, the way to write a multi-line string now is as follows:

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

Using the \ escape sequence in a text block, it 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.\
""";
Copy after login

(Video tutorial Recommendation: java video tutorial)

3. Pattern matching of instanceof

Java 14 introduces a preview feature, with which it is no longer You need to write code that first passes instanceof judgment and then forced conversion. For example, the following code:

if (obj instanceof Group) {
Group group = (Group) obj;
// use group specific methods
var entries = group.getEntries();
}
Copy after login

Using this preview feature, it can be refactored into:

if (obj instanceof Group group) {
var entries = group.getEntries();
}
Copy after login

Since the conditional check requires obj to be of Group type, why do we need to include it in the conditional code like the first piece of code? What about specifying obj as Group type in the block? This may cause errors.

This more concise syntax can eliminate most casts in Java programs.

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

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

This paragraph The redundant CaseInsensitiveString cast in the code can be removed and transformed into the following way:

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

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

In other words, this preview function is just the beginning. In the future, this function will definitely reduce more code redundancy, thereby reducing the possibility of bugs.

4. Record

Another preview function is record. Like other preview functions introduced earlier, this preview function also follows the trend of reducing redundant Java code and can help developers write more accurate code. Record is mainly used for classes in specific fields. Its displacement function is to store data without any custom behavior.

Let’s get straight to the point and take the simplest example of a field class: BankTransaction, which represents a transaction and contains three fields: date, amount, and description. There are many aspects to consider when defining a class:

Constructor, getter, method toString(), hashCode() and equals(). The code for these parts is usually automatically generated by the 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=&#39;" + description + &#39;\&#39;&#39; +
&#39;}&#39;;
}
@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);
}
}
Copy after login

Java 14 provides a way to resolve this redundancy and express the purpose more clearly: the only purpose of this class is to bring data together. Record will provide 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) {}
Copy after login

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

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

javac --enable-preview --release 14 The fields of BankTransaction.javarecord are implicitly final. Therefore, record fields cannot be reassigned. But it should be noted that this does not mean that the entire record is immutable. The objects stored in the fields can be mutable.

5. NullPointerException

一些人认为,抛出NullPointerException异常应该当做新的“Hello World”程序来看待,因为NullPointerException是早晚会遇到的。玩笑归玩笑,这个异常的确会造成困扰,因为它经常出现在生产环境的日志中,会导致调试非常困难,因为它并不会显示原始的代码。例如,如下代码:

var name = user.getLocation().getCity().getName();
Copy after login

在Java 14之前,你可能会得到如下的错误:

Exception in thread "main" java.lang.NullPointerExceptionat NullPointerExample.main(NullPointerExample.java:5)
Copy after login

不幸的是,如果在第5行是一个包含了多个方法调用的赋值语句(如getLocation()和getCity()),那么任何一个都可能会返回null。实际上,变量user也可能是null。因此,无法判断是谁导致了NullPointerException。

在Java 14中,新的JVM特性可以显示更详细的诊断信息:

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

该消息包含两个明确的组成部分:

后果:Location.getCity()无法被调用原因:User.getLocation()的返回值为null增强版本的诊断信息只有在使用下述标志运行Java时才有效:

-XX:+ShowCodeDetailsInExceptionMessages
Copy after login

下面是个例子:

java -XX:+ShowCodeDetailsInExceptionMessages NullPointerExample
Copy after login

在以后的版本中,该选项可能会成为默认。

这项改进不仅对于方法调用有效,其他可能会导致NullPointerException的地方也有效,包括字段访问、数组访问、赋值等。

The above is the detailed content of What are the new features of java14. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!