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; } };
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>";
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>""";
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.";
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.\ """;
(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(); }
Using this preview feature, it can be refactored into:
if (obj instanceof Group group) { var entries = group.getEntries(); }
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); }
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); }
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='" + 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 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) {}
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();
在Java 14之前,你可能会得到如下的错误:
Exception in thread "main" java.lang.NullPointerExceptionat NullPointerExample.main(NullPointerExample.java:5)
不幸的是,如果在第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)
该消息包含两个明确的组成部分:
后果:Location.getCity()无法被调用原因:User.getLocation()的返回值为null增强版本的诊断信息只有在使用下述标志运行Java时才有效:
-XX:+ShowCodeDetailsInExceptionMessages
下面是个例子:
java -XX:+ShowCodeDetailsInExceptionMessages NullPointerExample
在以后的版本中,该选项可能会成为默认。
这项改进不仅对于方法调用有效,其他可能会导致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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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

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

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

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++ 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.

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.

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.
