1. Introduction
In this tutorial, We'll be learning what are the new features in java 14 and example programs in each area. This may be asked in the interview to check whether you are seeing regular updates on java and its latest changes.
Below are the features are added to the new JDK 14.
- Switch Expressions (Standard) – JEP 361
- Pattern Matching for instanceof (Preview) – JEP 305
- Helpful NullPointerExceptions – JEP 358
- Records (Preview) – JEP 359
- Text Blocks (Second Preview) – JEP 368
- Packaging Tool (Incubator) – JEP 343
- NUMA-Aware Memory Allocation for G1 – JEP 345
- JFR Event Streaming – JEP 349
- Non-Volatile Mapped Byte Buffers – JEP 352
- ZGC on macOS – JEP 364
- ZGC on Windows – JEP 365
- Foreign-Memory Access API (Incubator) – JEP 370
2. Download JDK 14
First, Download the latest java from the website here.
As you learn, It is easy than older versions of java. You need to just download it as zip and extract it to the specific location. Finally, add ../jdk-14/bin to the JAVA_HOME in the system environment variables in windows.
If you are on mac OS then export "/Library/Java/JavaVirtualMachines/jdk-14.jdk/Contents/Home" as JAVA_HOME below.
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-14.jdk/Contents/Home
3. Enable Preview features
Now, Your set up is ready to write the JDK 14 compatibility code. Let us start the code and compile and run the code in java 14. We will be using JShell, an interactive REPL command-line tool for quickly testing the new Java 14 features.
It’s important to note that many features released in Java 14 are in preview. This means that's though they’re fully working right now, things may be modified in the future. Some could be made a standard or simply removed in the next release cycles. In order to test preview features, you need to explicitly set --enable-preview when running the JShell or Java Program as shown below
jshell --enable-preview javac --release 14 --enable-preview Java14program.java
4. Java 14: Switch Expression with yield
Next new interesting one, yield is introduced in java 13 preview features but now in jdk 14 is live as a standard feature. Lamdas are added in java 12.
Let us start running the code in JSHELL.
Full article on "Switch Statement with yield"
String day = "TUE"; String result = switch (day) { case "MON", "TUE", "WED" -> "monday to wednesday"; case "THU", "FRI", "SAT", "SUN" -> "THURUSDAY TO SUNDAY"; default -> { if(day.isEmpty()) yield "Please insert a valid day."; else yield "Looks like a Sunday."; } }; System.out.println(result);Output:
Take a look at the following commands and its output immediately.
jshell> String day = "TUE"; day ==> "TUE" jshell> String result = switch (day) { ...> case "MON", "TUE", "WED" -> "monday to wednesday"; ...> case "THU", "FRI", "SAT", "SUN" -> "THURUSDAY TO SUNDAY"; ...> default -> { ...> if(day.isEmpty()) ...> yield "Please insert a valid day."; ...> else ...> yield "Looks like a Sunday."; ...> } ...> ...> }; result ==> "monday to wednesday" jshell> System.out.println(result); monday to wednesday
5. Java 14: Pattern Matching for instanceof (Preview)
Another important preview feature is that instanceof is used to check the instance is a type of a particular class. You might have seen this in your project many times.
Let us see a case where we different types of objects.
Before Java 14:
if (obj instanceof DoctorMessage) { DoctorMessage dm = (DoctorMessage) obj; System.out.println(dm.getName()); } else if (obj instanceof PatientMessage) { PatientMessage pm = (DoctorMessage) obj; System.out.println(pm.getName()); }
In the above code, we need to perform the casting to the right class after confirming with instanceof.
In Java 14:
JDK 14 avoid typecasting right after the instanceof success as below.
if (obj instanceof DoctorMessage dm) { System.out.println(dm.getName()); } else if (obj instanceof PatientMessage pm) { System.out.println(pm.getName()); }
As shown in the above code, Once the condition is true then only obj will be casted to the DoctorMessage and assigned the obj to the dm ref otherwise dm will be null and will not be casted. The scope of this variable will be limited to the conditional block only. In this case, it is legal to access within if statement.
6. Java 14: Precise NullPointerExceptions
Mostly all you aware, When we get the NullPointerException then right away you will see the log and find the line number first where the exception is being thrown.
Next, review the code which causing for NullPointerException and find which object is null. At last, adding the null condition that resolves the run time exception.
Before java 14:
Let us take a look at the below code that may produce the run time exception.
doctor.getPatient().getNominee().getName(); // line 3
Let us see the stack trace.
//Errir Stacktrace Exception in thread "main" java.lang.NullPointerException at NullPointerExample.main(NullPointerExample.java:3)
When we see the exception, we get the doubt that which object is null now. Here may be any one of the below objects can be null.
doctor object
patient object that is returned by doctor.getPatient()
nominee object may be null which is returned by doctor.getPatient().getNominee()
If we get a clear direction by the JVM which object is producing this error should be helpful to fix the problem.
Java 14:
Let us run the same code in java 14 and see how the stack trace is simplified. This Java 14 new JVM feature which gives better insights with more descriptive stack details as shown below:
doctor object
patient object that is returned by doctor.getPatient()
nominee object may be null which is returned by doctor.getPatient().getNominee()
If we get a clear direction by the JVM which object is producing this error should be helpful to fix the problem.
Java 14:
Let us run the same code in java 14 and see how the stack trace is simplified. This Java 14 new JVM feature which gives better insights with more descriptive stack details as shown below:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Nominee.getName()" because the return value of "doctor.getPatient().getNominee()" is null at NullPointerExample.main(NullPointerExample.java:4)
In the above trace, it is clearly mentioned that the Nominee object is null.
Please note: This is not a feature but enhancement to the runtime environment.
7. Java 14: Records (Preview)
Another new interesting concept. This the new way to create POJO or Value Object(VO) classes. In general, We create a class with a set of private properties, setters and getter methods and toString() method, equals() and hashcode() methods manually adding to the POJO or VO classes.
Some of the IDE's provides the flexibility to create or generate these methods for us automatically.
But, Using new java 14 record feature functionality, we will be completely avoiding the boilerplate code with a record.
Let us create a class with the record as below.
record Doctor (String name, String specialization)
This statement will create getter methods for these properties as name() and specialization(). As well as provide equals(), hashCode() and toString() methods. All these are inherited from Object class.
jshell> record Doctor (String name, String specialization) {} | Error: | records are a preview feature and are disabled by default. | (use --enable-preview to enable records) | record Doctor (String name, String specialization) {} | ^
If you run directly record statement then will get the above error. Before we use the preview feature, we must and should enable the preview features.
javac --release 14 --enable-preview Doctor.java
or
Open the shell prompt with review features as below.
jshell --enable-preview jshell> record Doctor(String name, String specialization) {} | created record Doctor jshell> Doctor d = new Doctor("Ram", "ENT"); d ==> Doctor[name=Ram, specialization=ENT] jshell> jshell> d.name() $4 ==> "Ram" jshell> d d ==> Doctor[name=Ram, specialization=ENT] jshell> d. equals( getClass() hashCode() name() notify() notifyAll() specialization() toString() wait(
Key points:
A) Records can not extend any class and These are Final classes.
B) The record can not extend any class
C) The record can be abstract
D) Record values can be set by using the only constructors.
E) All fields are private and final by default.
F) Values Inside Reference Fields Of A Record Can Be Mutated
G) Records Can Implement Interfaces
H) Records support multiple constructors
I) Records Allow Modifying Accessor Methods
J) Check Record and its Components at Run-time
8. Java 14: Text Blocks (Preview)
This is already a preview feature in JDK 13 changes and the main goal of this feature is to provide the support to multi-line string literals using """ triple colon.
https://www.javaprogramto.com/2019/10/java-13-new-features.html
It is very handy in creating JSON or HTML content as String literals.
But, We expected to be as part of JDK 14 and seeing it as a preview feature that means java team is some more things to the text blocks.
String text = """ Hello \ Welcome to \ Java 14 \ That has the most features among\ all non-LTS versions so far\ """;Note: Always """ must be in the first line in text blocks. Otherwise will get a compile-time error when running from jshell.
Error:
| illegal text block open delimiter sequence, missing line terminator | String s = """ Hello\
Key-points:
A) Backslash for displaying nice-looking multi-line string blocks.B) \s is used to consider trailing spaces which are by default ignored by the compiler. It preserves all the spaces present before it.
9. Conclusion
In this article, We've seen the major changes in the new JDK 14 as below.
- Switch Expression with yield
- instnaceof simplified type casting
- NullPointerExample with a precise pointer
- record concept with examples
- String multi-line support with Text Blocks
References:
techgeeknextopenjdk.java
InfoWorld
No comments:
Post a Comment
Please do not add any spam links in the comments section.