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 id="Java-nbsp-nbsp-is-nbsp-here">\"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 id="Java-nbsp-nbsp-is-nbsp-here">"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!

大家都知道win7系统有很多种版本,比如win7旗舰版、win7专业版、win7家庭版等,有不少用户在家庭版和旗舰版之间纠结,不知道选择哪个版本比较好,所以今天小编来跟大家说说win7家庭餐与win7旗舰版的区别介绍,大家一起来看看吧。1、体验不同家庭普通版使您的日常操作变得更快、更简单,可以更快、更方便地访问使用最频繁的程序和文档。家庭高级版让您享有最佳的娱乐体验,可以轻松地欣赏和共享您喜爱的电视节目、照片、视频和音乐。旗舰版集各版本功能之大全,具备Windows7家庭高级版的所有娱乐功能和专

了解SpringMVC的关键特性:掌握这些重要的概念,需要具体代码示例SpringMVC是一种基于Java的Web应用开发框架,它通过模型-视图-控制器(MVC)的架构模式来帮助开发人员构建灵活可扩展的Web应用程序。了解和掌握SpringMVC的关键特性将使我们能够更加有效地开发和管理我们的Web应用程序。本文将介绍一些SpringMVC的重要概念

5g的三个特性是:1、高速率;在实际应用中,5G网络的速率是4G网络10倍以上。2、低时延;5G网络的时延大约几十毫秒,比人的反应速度还要快。3、广连接;5G网络出现,配合其他技术,将会打造一个全新的万物互联景象。

随着互联网的快速发展,编程语言也在不断演化和更新。其中,Go语言作为一种开源的编程语言,在近年来备受关注。Go语言的设计目标是简单、高效、安全且易于开发和部署。它具有高并发、快速编译和内存安全等特性,让它在Web开发、云计算和大数据等领域中有着广泛的运用。然而,目前Go语言也有不同的版本可供选择。在选择合适的Go语言版本时,我们需要考虑需求和特性两个方面。首

java的特性是:1、简单易学;2、面向对象,使得代码更加可重用和可维护;3、平台无关性,能在不同的操作系统上运行;4、内存管理,通过自动垃圾回收机制来管理内存;5、强类型检查,变量在使用之前必须先声明类型;6、安全性,可以防止未经授权的访问和恶意代码的执行;7、多线程支持,能提高程序的性能和响应能力;8、异常处理,可以避免程序崩溃;9、大量的开发库和框架;10、开源生态系统。

PHP8的五大亮点功能,让你的代码更高效!PHP(HypertextPreprocessor)是一种广泛使用的开源脚本语言,用于Web开发。它简单易学,可以与HTML嵌套使用,同时也支持面向对象编程。PHP8作为最新版本,具有许多令人兴奋的新特性和改进,以下是五个主要亮点功能,可以使你的代码更高效。一、JIT编译器(Just-In-TimeCompile

java三大特性是:1、面向对象,java最核心的特性之一,将现实世界中的事物抽象成类,并且用对象来描述和处理问题;2、平台无关性,java源代码经过编译后生成的是字节码,而不是机器码;3、高性能,通过即时编译和垃圾回收技术的应用,在运行时可以自动优化和处理性能问题。

PHP8带来的重大特性揭秘,让你的代码更强大2020年11月26日,PHP8正式发布,为全球的PHP开发者带来了一系列令人振奋的新特性。本文将带你揭秘PHP8带来的重大改进,让你的代码更加强大和高效。同时,为了更好地理解这些特性,我们将提供具体的代码示例。强类型定义PHP8引入了更加严格的类型定义机制。现在,开发者可以在函数的参数和返回值上指定具体的类型,包


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.