- “MoreThanJava” is about “learning, not just CODE”. This series of Java basics tutorials is a general review of the basics of Java by myself after combining all aspects of knowledge, aiming to “help new friends learn quickly and with high quality”.
- Of course, both old and new, I believe you will benefit from it. If you feel “good” friends, welcome to “follow + message + share”, at the end of the article there is a complete link to get, your support is the biggest motivation for me to move forward!
Features overview
The following are some of the new features introduced in Java 14. A more detailed description of the new Java 14 features can be found here.
Language and feature changes:
- Switch Expressions – Standard (JEP 361)
- Instanceof Pattern Matching – Preview (JEP 305)
- Useful NullPointerExceptions (JEP 358)
- Record – Preview (JEP 359)
- Text Block – Preview (JEP 368)
The JVM changes:
- Optimization of G1 NUMA-aware Memory Allocation (JEP 345)
- Delete concurrent mark Scan (CMS) garbage collector (JEP 363)
- JFR Event Flow (JEP 349)
- ZGC on macOS – Experimental (JEP 364)
- ZGC on Windows – Experimental (JEP 365)
- Insane + SerialOld GC Combination (JEP 366)
Other features:
- Packaging Tools (JEP 343)
- Non-volatile mapped byte buffer (JEP 352)
- Deprecating Solaris and SPARC ports (JEP 362)
- Delete Pack200 Tools and apis (JEP 367)
- External Memory Access API (JEP 370)
I. Switch Expressions – Standard (JEP 361)
The reservation features that were preserved in the last two releases are now finally gaining a permanent place in Java 14.
-
Java 12 introduced the Lambda syntax for expression, which allows pattern matching with multiple case tags and prevents errors that lead to lengthy code. It also enforces exhaustion and throws a compilation error if all input cases are not covered.
-
In the second preview release of Java 13, yield was used instead of the break keyword to return the return value of an expression.
Java 14 has now finally made these features standard:
String result = switch (day) {
case "M"."W"."F" -> "MWF";
case "T"."TH"."S" -> "TTS";
default- > {if (day.isEmpty()) {
yield "Please insert a valid day.";
} else {
yield "Looks like a Sunday."; }}}; System.out.println(result);Copy the code
Pay attention to,yield
It is not a new keyword in Java and is only used in Switch expressions.
Ii. Instanceof Pattern Matching – Preview (JEP 305)
Before Java 14, we used instanceof-and-cast to check the type of an object and convert it to a variable.
if (obj instanceof String) { // instanceof
String s = (String) obj; // cast
if("jdk14".equalsIgnoreCase(s)){
/ /...}}else {
System.out.println("not a string");
}
Copy the code
Now, in Java 14, we can refactor the above code like this:
if (obj instanceof String s) { // instanceof, cast and bind variable in one line.
if("jdk4".equalsIgnoreCase(s)){
/ /...}}else {
System.out.println("not a string");
}
Copy the code
If obj is an instance of String, its String is cast to the binding variable and assigned to the binding variable S.
NullPointerExceptions (JEP 358)
Null-pointer exceptions are any developer’s nightmare. Until Java 13, debugging the notorious NPE was tricky. Developers have to rely on other debugging tools, or manually calculate empty variables/methods, because the stack trace only shows the line number.
Before Java 14:
String name = jd.getBlog().getAuthor()
//Stacktrace
Exception in thread "main" java.lang.NullPointerException
at NullPointerExample.main(NullPointerExample.java:5)
Copy the code
14 in the introduction of the new Java JVM functions (with – XX: + ShowCodeDetailsInExceptionMessages option), it provides better insights through more descriptive stack, as shown below:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Blog.getAuthor()" because the return value of "Journaldev.getBlog()" is null
at NullPointerExample.main(NullPointerExample.java:4)
Copy the code
Note: The above features are not language features. This is an enhancement to the runtime environment.
Iv. Record – Preview (JEP 359)
A record is a data type that stores pure data. The idea behind introducing Record was to quickly create simple, concise classes without boilerplate code. (This is somewhat similar to the data types in Kotlin, which is one of the reasons there is talk of Java becoming “Kotlinized.”)
Typically, classes in Java require you to implement equals(), hashCode(), getters, and setters methods. Although some ides support automatic generation of this type, the code is still verbose. To use Record, you simply define a class as follows.
record Author(a){}
//or
record Author (String name, String topic) {}
Copy the code
The Java compiler automatically generates a class with constructors, private final fields, accessors, and equals, hashCode, and toString methods. The automatically generated getters for the above class are name() and Topic ().
Record Author (String name, String topic){}
final class Author extends java.lang.Record {
private final java.lang.String name;
private final java.lang.String topic;
public Author(java.lang.String name, java.lang.String topic) { /* compiled code */ }
public java.lang.String toString(a) { /* compiled code */ }
public final int hashCode(a) { /* compiled code */ }
public final boolean equals(java.lang.Object o) { /* compiled code */ }
public java.lang.String name(a) { /* compiled code */ }
public java.lang.String topic(a) { /* compiled code */}}Copy the code
In addition, we can add additional fields, methods, and constructors to the record by:
record Author (int id, String name, String topic) {
static int followers;
public static String followerCount(a) {
return "Followers are "+ followers;
}
public String description(a){
return "Author "+ name + " writes on "+ topic;
}
public Author{
if (id < 0) {
throw new IllegalArgumentException( "id must be greater than 0."); }}}Copy the code
The other constructors defined within Record are called Compact constructors. It contains no arguments, just arguments to the specification’s own constructor.
A few things to note about Record:
record
It can neither extend a class nor be extended by another class. This is afinal class
.record
It can’t be abstract.record
You cannot extend any other classes, nor can you define instance fields within the body. Instance fields can only be defined in the state description.- Declared fields are private fields and
final
Field. record
Static fields and methods are allowed in the definition.
Values in the reference fields of the Record class can be changed
It is worth noting that for fields defined as objects, only references are immutable. The underlying values can be modified.
A record for modifying the ArrayList is shown below. As you can see, this value is modified every time the ArrayList is changed.
jshell> record Author(String name, A List < String > switchable viewer) {} | created records the Author jshell > var topicList = new ArrayList < String > (arrays.aslist ("Java"));
topicList ==> [Java]
jshell> var author = new Author("Wmyskxz", topicList);
author ==> Author[name=Wmyskxz, topics=[Java]]
jshell> topicList.add("Python");
$6= = >true
jshell> author.topics();
$7 ==> [Java, Python]
jshell>
Copy the code
Record can implement the interface
The following code shows an example of implementing a recorded interface:
interface Information {
String getFullName(a);
}
record Author(String name, String topic) implements Information {
public String getFullName(a) {
return "Author "+ name + " writes on "+ topic; }}Copy the code
Record supports multiple constructors
The record allows you to declare multiple constructors with or without arguments, as follows:
record Author(String name, String topic) {
public Author(a) {
this("NA"."NA");
}
public Author(String name) {
this(name, "NA"); }}Copy the code
Record allows you to modify accessor methods
While Records generate public access methods for fields defined in the state description, they also allow you to redefine access methods in the body, as follows:
record Author(String name, String topic) {
public String name(a) {
return "This article was written by " + this.name; }}Copy the code
Examine the Record and its components at run time
Record provides isRecord() and getRecordComponents() to check whether the class is a record and to see its fields and types. Here’s how it works:
jshell> record Author(String name, String topic){} | created records the Author jshell >var author = new Author("Wmyskxz"."MoreThanJava");
author ==> Author[name=Wmyskxz, topic=MoreThanJava]
jshell> author.getClass().isRecord();
$3= = >true
jshell> author.getClass().getRecordComponents();
$4 ==> RecordComponent[2] { java.lang.String name, java.lang.String topic }
jshell>
Copy the code
Tips: While we added additional fields and methods to the record in the above code example, make sure you don’t overdo it. Records are designed to be generic data carriers, and if you want to implement many other methods, it’s best to go back to regular classes.
V. Text Block – Preview (JEP 368)
Text blocks are a preview feature in Java 13 designed to allow easy creation of multi-line string literals. Useful for easily creating HTML and JSON or SQL query strings.
In Java 14, text blocks are still being previewed and some new features have been added. We can now use:
\
The backslash is used to display a nice multi-line string block.\s
Allows for trailing whitespace, which is ignored by the compiler by default. It preserves all the space in front of it.
String text = """ Did you know \ Java 14 \ has the most features among\ all non-LTS versions so far\ """;
String text2 = """ line1 line2 \s line3 """;
String text3 = "line1\nline2 \nline3\n"
//text2 and text3 are equal.
Copy the code
Optimization of G1 NUMA-aware Memory Allocation (JEP 345)
The new NUMA-aware memory allocation pattern improves G1 performance on mainframe computers. Add the +XX:+UseNUMA option to enable it.
7. Delete concurrent mark Scan (CMS) garbage collector (JEP 363)
Java 9 — JEP 291 has deprecated this concurrent mark scan (CMS) garbage collector and has now officially removed it.
/usr/lib/jvm/jdk-14/bin/java -XX:+UseConcMarkSweepGC Test
OpenJDK 64-Bit Server VM warning: Ignoring option UseConcMarkSweepGC; support was removed in 14.0
Copy the code
Viii. JFR Event Flow (JEP 349)
The JDK Flight Recorder (JFR) is a tool for collecting diagnostic and performance analysis data about running Java applications. Typically, we start recording, stop recording, and then dump the recorded events to disk for analysis, which is great for profiling, analysis, or debugging.
The JEP improves the existing JFR to support event flow, which means that we can now transfer JFR events in real time without having to dump recorded events to disk and parse them manually.
ZGC on macOS – Experimental (JEP 364)
Java 11 — JEP 333 introduced the Z garbage Collector (ZGC) on Linux and is now portable to macOS.
10. ZGC on Windows – Experimental (JEP 365)
Java 11 — JEP 333 introduced the Z garbage Collector (ZGC) on Linux and is now portable to Windows version >= 1803 machines.
Insane + SerialOld GC avenge (JEP 366)
Java 14 discourages the use of a combination of parallel young generation and serial old generation GC algorithms due to low usage and heavy maintenance.
/usr/lib/jvm/jdk-14/bin/java -XX:-UseParallelOldGC Test
OpenJDK 64-Bit Server VM warning: Option UseParallelOldGC was deprecated inVersion 14.0 and will likely be removedin a future release.
Copy the code
Xii. Other characteristics
Packaging Tools (JEP 343)
Jpackage is a new tool for packaging Java applications into platform-specific packages.
- Linux: deb and RPM
- MacOS: PKG and DMG
- Windows: MSI and EXE
For example, package JAR files to a Windows platform that supports EXE.
Non-volatile mapped byte buffer (JEP 352)
The improved FileChannel API creates MappedByteBuffer access to non-volatile memory (NVM) that can retrieve stored data even after power is turned off. For example, this feature ensures that any changes that might still be in the cache are brought back into memory.
Ps: Only Linux/X64 and Linux/AArch64 OS support this feature!
Deprecating Solaris and SPARC ports (JEP 362)
No longer supported for Solaris/SPARC, Solaris/X64 and Linux/SPARC ports, less platform support means faster delivery of new features.
Delete Pack200 Tools and apis (JEP 367)
Java 11 — JEP 336 deprecated the use of the pack200 and unpack200 tools, as well as the pack200 API java.util.jar in the package, which is now officially removed.
External Memory Access API (JEP 370)
Incubator module that allows The Java API to access external memory outside the Java heap.
The external memory access API introduces three main abstractions:
- MemorySegment: Provides access to contiguous memory regions with a given range.
- MemoryAddress: Provides an offset (basically a pointer) to a MemorySegment.
- MemoryLayout: Provides a way to describe the layout of memory segments, which greatly simplifies usage
var
The process by which a handle accesses a MemorySegment. With this approach, you don’t have to calculate the offset based on how memory is used. For example, the offset of an integer or long integer array will be different, but it will be handled transparently using MemoryLayout.
Here’s an example:
import jdk.incubator.foreign.*;
import java.lang.invoke.VarHandle;
import java.nio.ByteOrder;
public class Test {
public static void main(String[] args) {
VarHandle intHandle = MemoryHandles.varHandle(int.class, ByteOrder.nativeOrder());
try (MemorySegment segment = MemorySegment.allocateNative(1024)) {
MemoryAddress base = segment.baseAddress();
System.out.println(base); // print memory address
intHandle.set(base, 999); // set value 999 into the foreign memory
System.out.println(intHandle.get(base)); // get the value from foreign memory}}}Copy the code
Compile and run jdk.incubator. Foreign using the incubator module.
$ /usr/lib/jvm/jdk-14/bin/javac --add-modules jdk.incubator.foreign Test.java
warning: using incubating module(s): jdk.incubator.foreign
1 warning
$ /usr/lib/jvm/jdk-14/bin/java --add-modules jdk.incubator.foreign Test
WARNING: Using incubator modules: jdk.incubator.foreign
MemoryAddress{ region: MemorySegment{ id=0x4aac6dca limit: 1024 } offset=0x0 }
999
Copy the code
Further reading: the official document – download.java.net/java/GA/jdk…
The resources
- Its official instructions – openjdk.java.net/projects/jd…
- What is New in Java 14 – mkyong.com/java/what-i…
- 14 the Features of Java | JournalDev – www.journaldev.com/37273/java-…
The article recommended
- This is JDK15, JDK7 do not know? – www.wmyskxz.com/2020/08/18/…
- So the most fully Java version features about 8 – www.wmyskxz.com/2020/08/19/…
- Didn’t you know about these epic updates to Java9? – www.wmyskxz.com/2020/08/20/…
- You want to know about the JDK 10 version update is here – www.wmyskxz.com/2020/08/21/…
- Here you have to understand the Java features 11 – www.wmyskxz.com/2020/08/22/…
- Java version features 12 – is to understand 】 【 www.wmyskxz.com/2020/08/22/…
- Java edition characteristic is to understand 】 【 13 – www.wmyskxz.com/2020/08/22/…
- “MoreThanJava” series of corpus – www.wmyskxz.com/categories/…
- Github: More Than Java: More Than Code star: github.com/wmyskxz/Mor…
- Personal public number: wmyskxz, personal independent domain name blog: wmyskxz.com, adhere to the original output, below the scan code concern, 2020, and you grow together!
Thank you very much for reading this, if you think this article is well written, if you think there is something about “I don’t have three hearts”, please like, follow, share and leave a comment!
Creation is not easy, your support and recognition, is the biggest motivation for my creation, we will see you in the next article!