Home Java JavaBase What are the new features of java14

What are the new features of java14

Jun 20, 2020 pm 01:33 PM
characteristic

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Introduction to the differences between win7 home version and win7 ultimate version Introduction to the differences between win7 home version and win7 ultimate version Jul 12, 2023 pm 08:41 PM

Everyone knows that there are many versions of win7 system, such as win7 ultimate version, win7 professional version, win7 home version, etc. Many users are entangled between the home version and the ultimate version, and don’t know which version to choose, so today I will Let me tell you about the differences between Win7 Family Meal and Win7 Ultimate. Let’s take a look. 1. Experience Different Home Basic Edition makes your daily operations faster and simpler, and allows you to access your most frequently used programs and documents faster and more conveniently. Home Premium gives you the best entertainment experience, making it easy to enjoy and share your favorite TV shows, photos, videos, and music. The Ultimate Edition integrates all the functions of each edition and has all the entertainment functions and professional features of Windows 7 Home Premium.

Master the key concepts of Spring MVC: Understand these important features Master the key concepts of Spring MVC: Understand these important features Dec 29, 2023 am 09:14 AM

Understand the key features of SpringMVC: To master these important concepts, specific code examples are required. SpringMVC is a Java-based web application development framework that helps developers build flexible and scalable structures through the Model-View-Controller (MVC) architectural pattern. web application. Understanding and mastering the key features of SpringMVC will enable us to develop and manage our web applications more efficiently. This article will introduce some important concepts of SpringMVC

Choose the applicable Go version, based on needs and features Choose the applicable Go version, based on needs and features Jan 20, 2024 am 09:28 AM

With the rapid development of the Internet, programming languages ​​are constantly evolving and updating. Among them, Go language, as an open source programming language, has attracted much attention in recent years. The Go language is designed to be simple, efficient, safe, and easy to develop and deploy. It has the characteristics of high concurrency, fast compilation and memory safety, making it widely used in fields such as web development, cloud computing and big data. However, there are currently different versions of the Go language available. When choosing a suitable Go language version, we need to consider both requirements and features. head

Are there any class-like object-oriented features in Golang? Are there any class-like object-oriented features in Golang? Mar 19, 2024 pm 02:51 PM

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

What are the three characteristics of 5g What are the three characteristics of 5g Dec 09, 2020 am 10:55 AM

The three characteristics of 5g are: 1. High speed; in practical applications, the speed of 5G network is more than 10 times that of 4G network. 2. Low latency; the latency of 5G network is about tens of milliseconds, which is faster than human reaction speed. 3. Broad connection; the emergence of 5G network, combined with other technologies, will create a new scene of the Internet of Everything.

C++ function types and characteristics C++ function types and characteristics Apr 11, 2024 pm 03:30 PM

C++ functions have the following types: simple functions, const functions, static functions, and virtual functions; features include: inline functions, default parameters, reference returns, and overloaded functions. For example, the calculateArea function uses π to calculate the area of ​​a circle of a given radius and returns it as output.

What are the characteristics of java What are the characteristics of java Aug 09, 2023 pm 03:05 PM

The characteristics of Java are: 1. Simple and easy to learn; 2. Object-oriented, making the code more reusable and maintainable; 3. Platform-independent, able to run on different operating systems; 4. Memory management, through automatic garbage collection mechanism Manage memory; 5. Strong type checking, variables must declare their type before use; 6. Security, which can prevent unauthorized access and execution of malicious code; 7. Multi-threading support, which can improve the performance and responsiveness of the program ; 8. Exception handling can avoid program crashes; 9. A large number of development libraries and frameworks; 10. Open source ecosystem.

What are Linux gems? Learn more about the definition and characteristics of Linux Gem What are Linux gems? Learn more about the definition and characteristics of Linux Gem Mar 14, 2024 pm 02:18 PM

LinuxGem is a common term in the computer field, which refers to software or applications that perform well on the Linux operating system. The Linux operating system itself is an open source operating system with the support of many developers and communities, so it is easy to find high-quality, powerful software on Linux. However, even among so many high-quality software, there are still some software called "LinuxGem", which are popular in Linux with their excellent design, performance and functions.

See all articles