Java 14 Features With Examples - New JDK 14 Tutorial


A quick guide to java 14 features with example programs step by step explanation.

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

Java 14 Features With Examples - New JDK 14 Tutorial

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 -> {
                    yield "Please insert a valid day.";
                    yield "Looks like a Sunday.";



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;
} else if (obj instanceof PatientMessage) {
  PatientMessage pm = (DoctorMessage) obj;

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) {
} else if (obj instanceof PatientMessage pm) {

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:

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


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

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.


|  illegal text block open delimiter sequence, missing line terminator
|  String s = """ Hello\


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





About Us

Author: Venkatesh - I love to learn and share the technical stuff.

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
JavaProgramTo.com: Java 14 Features With Examples - New JDK 14 Tutorial
Java 14 Features With Examples - New JDK 14 Tutorial
A quick guide to java 14 features with example programs step by step explanation.
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content