SlideShare a Scribd company logo
1 of 10
Download to read offline
Features in Java 14 (JDK 14)
Mutlu Okuducu/ Software Developer
Oracle has been announcement Java 14 (JDK 14) open-source released on 17 March 2020 offers for all developers and enterprises. JAVA
14 addresses a total of 16 main enhancements/changes.
The list of most important features to Java 14 for developers.
JEP 305 — Pattern Matching for instanceof
JEP 358 — NullPointerExceptions
JEP 359 — Records
JEP 361 — Switch Expressions
JEP 368 — Text Blocks (Second Preview)
For all features https://openjdk.java.net/projects/jdk/14/
JEP 305 — Pattern Matching for instanceof
We use instanceof-and-cast to check the object’s type and cast to a variable.
Before Java14
Java 14, we can refactor above code cast and bind like this:
Following example restriction
if (obj instanceof String) { // if true instanceof then
String t= (String) obj; // cast
System.out.println("String: " + t);
}
if (obj instanceof String t) { // instanceof, cast and bind variable in one line.
System.out.println("String: " + t);
}
You can find the code, instanceofs.
JEP 358 — Helpful NullPointerExceptions
NullPointerExceptions cause frustrations because they often appear in application logs when code is running in a production
environment, which can make debugging difficult. After all, the original code is not readily available. For example, consider the code
below:
Before Java 14, you might get the following error:
Exception in thread “main” java.lang.NullPointerException
com.java14features.nullpointerexception.Example1.main(Example1.java:15)
Unfortunately, if at line 15, there’s an assignment with multiple method invocations getAmount() and getCurrency() either one could be
returning null. So, it’s not clear what is causing the NullPointerException
//Legal use
if (obj instanceof String t && t.length() > 4) {
System.out.println("String: " + t);
}
//Cannot resolve symbol 't'
if(obj instanceof String t || t.length()>4){
System.out.println("String: "+t);
}
Account account =new Account();
String accountNumber=account.getAmount().getCurrency(); //line 15
System.out.println(accountNumber.length());
Now, with Java 14, there’s a new JVM feature through which you can receive more-informative diagnostics:
Exception in thread “main” java.lang.NullPointerException: Cannot invoke “com.java14features.dto.Amount.getCurrency()”
because the return value of “com.java14features.dto.Account.getAmount()” is null at
com.java14features.nullpointerexception.Example1.main(Example1.java:16)
The message now has two clear components:
The consequence: Amount.getCurrency() cannot be invoked.
The reason: The return value of Account.getAmount() is null.
The enhanced diagnostics work only when you run Java with the following flag: -XX:+ShowCodeDetailsInExceptionMessages
You can find the code, null pointer exception.
JEP 359 — Records
Records focus on certain domain classes whose purpose is only to store data in fields. A new class called record , it is a final class, not
abstract, and all of its fields are final as well. The record will automatically generate
the constructors , getters , equals() , hashCode() , toString() during compile-time and it can implements interfaces.
Restrictions:
A record is a final class
A record cannot extend a class
The value (reference) of a field is final and cannot be changed
A record class is an immutable
A record can not setters
You can find the code, records.
JEP 361 — Switch Expressions
The Switch Expressions is a preview feature in Java 12 and 13, it becomes a standard language feature, it means from Java 14 and
onward, we can use these Switch Expressions which can be used as an expression with help of arrow (->) , and now
can yield/return the value.
public record Transaction(
int id, double amount, String description {
}
/*
---- You can use JShell with the flag --enable-preview
Automatically generate:
* constructors
* getters
* equals()
* hashCode()
* toString()
*/
VehicleType vehicleType = VehicleType.AUTOMOBILE;
int speedLimit = switch (vehicleType) {
case BIKE, SCOOTER -> 40;
case MOTORBIKE, AUTOMOBILE -> 140;
case TRUCK -> 80;
default -> throw new IllegalStateException("No case found for: " + vehicleType);
};
System.out.println("Speed limit: " + speedLimit);
Following examples call method and return a new yield.
/////////////////////////////////////////
VehicleType vehicleType = VehicleType.TRUCK;
int speedLimit = switch (vehicleType) {
case BIKE, SCOOTER -> 40;
case MOTORBIKE, AUTOMOBILE -> 140;
case TRUCK -> {
int randomSpeed = ThreadLocalRandom.current().nextInt(70, 80);
yield randomSpeed;
}
};
System.out.println("Speed limit: " + speedLimit);
/////////////////////////////////////////
public static void main(String[] args) {
System.out.println( grade(9));
}
public static String grade(int mark) {
return switch (mark) {
case 9 -> "A";
case 8 -> "B";
case 7 -> "C";
case 6 -> "D";
default -> "F";
};
}
public static void main(String[] args) {
for (VehicleType vehicle : VehicleType.values()) {
int speedLimit = getSpeedLimit(vehicle);
System.out.println("Speed limit: " + vehicle + ":" + speedLimit);
You can find the code, switches.
JEP 368 — Text Blocks (Second Preview)
In Java, to embed HTML, XML, SQL, TEXT BLOCK or JSON snippet into code is often hard to read and hard to keep, and to
overcome this problem, Java 14 has introduced Text Block. A text block contains zero or more content characters, which are enclosed by
open and close delimiters.
}
}
private static int getSpeedLimit(VehicleType vehicleType) {
return switch (vehicleType) {
case BIKE, SCOOTER -> 40;
case MOTORBIKE, AUTOMOBILE -> 140;
case TRUCK -> 80;
};
}
/////////////////////////////////////////
public static void main(String[] args) {
Days day = FRIDAY;
int j = switch (day) {
case MONDAY -> 0;
case TUESDAY -> 1;
default -> {
int result = day.toString().length();
yield result;
}
};
System.out.println(j);
}
}
Text block using three double-quote characters
newlines (line-terminator) denoted by 
for white space (single space) denoted by /s
string format for a parameter using %s
String text = """"""; // illegal text block start
String text = """ """; // illegal text block start
String text = """
"""; // Text block
//Without Text Block HTML
String html = "<html>n" +
" <body>n" +
" <p>Hello, world</p>n" +
" </body>n" +
"</html>n";
System.out.println(html);
// Text Block HTML
String htmlTag = """
<html>
<body>
<p>Hello, world</p>
</body>
</html>
""";
// Text Block multi line (paragraph)
String text = """
two escape sequences first is for newlines 
and, second is to signify white space 
or single space.
""";
Following examples are string formatted.
// Text Block SQL Query
String query1 = """
SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB`
WHERE `CITY` = 'INDIANAPOLIS'
ORDER BY `EMP_ID`, `LAST_NAME`;
""";
// Text Block JSON Example
String json= """
{
"amount": {
"currency": "string",
"value": 0
},
"creditorAccount": {
"accountName": "string",
"accountNumber": "string",
"sortCode": "string"
},
"debtorAccount": {
"accountName": "string",
"accountNumber": "string",
"sortCode": "string"
},
"paymentDate": "string",
"reference": "string"
}
""";
String html1 = """
<html>
<body>
<p>%s, %s</p>
</body>
You can find the code, textsblocks.
</html>
""";
String print = html1.formatted("Hello1", "Java 14");
String html2 =
String.format("""
<html>
<body>
<p>%s, %s</p>
</body>
</html>
""", "Hello2", "Java 14");
String html3 = """
<html>
<body>
<p>%s, %s</p>
</body>
</html>
""".formatted("Hello3", "Java 14");

More Related Content

Similar to Java 14

Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
Appium Automation with Kotlin
Appium Automation with KotlinAppium Automation with Kotlin
Appium Automation with KotlinRapidValue
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...Akaks
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Create a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfCreate a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfmalavshah9013
 
Integration Project Inspection 3
Integration Project Inspection 3Integration Project Inspection 3
Integration Project Inspection 3Dillon Lee
 
C#i need help creating the instance of stream reader to read from .pdf
C#i need help creating the instance of stream reader to read from .pdfC#i need help creating the instance of stream reader to read from .pdf
C#i need help creating the instance of stream reader to read from .pdfajantha11
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2PVS-Studio
 
C-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorC-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorNeeraj Kaushik
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeletonIram Ramrajkar
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handlingsanya6900
 

Similar to Java 14 (20)

Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Appium Automation with Kotlin
Appium Automation with KotlinAppium Automation with Kotlin
Appium Automation with Kotlin
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Create a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfCreate a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdf
 
J Unit
J UnitJ Unit
J Unit
 
Integration Project Inspection 3
Integration Project Inspection 3Integration Project Inspection 3
Integration Project Inspection 3
 
Operator overloading
Operator overloading Operator overloading
Operator overloading
 
C#i need help creating the instance of stream reader to read from .pdf
C#i need help creating the instance of stream reader to read from .pdfC#i need help creating the instance of stream reader to read from .pdf
C#i need help creating the instance of stream reader to read from .pdf
 
BIT211_2.pdf
BIT211_2.pdfBIT211_2.pdf
BIT211_2.pdf
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
 
C-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorC-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression Calculator
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
Ocl 09
Ocl 09Ocl 09
Ocl 09
 

Recently uploaded

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 

Recently uploaded (20)

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 

Java 14

  • 1. Features in Java 14 (JDK 14) Mutlu Okuducu/ Software Developer Oracle has been announcement Java 14 (JDK 14) open-source released on 17 March 2020 offers for all developers and enterprises. JAVA 14 addresses a total of 16 main enhancements/changes. The list of most important features to Java 14 for developers. JEP 305 — Pattern Matching for instanceof
  • 2. JEP 358 — NullPointerExceptions JEP 359 — Records JEP 361 — Switch Expressions JEP 368 — Text Blocks (Second Preview) For all features https://openjdk.java.net/projects/jdk/14/ JEP 305 — Pattern Matching for instanceof We use instanceof-and-cast to check the object’s type and cast to a variable. Before Java14 Java 14, we can refactor above code cast and bind like this: Following example restriction if (obj instanceof String) { // if true instanceof then String t= (String) obj; // cast System.out.println("String: " + t); } if (obj instanceof String t) { // instanceof, cast and bind variable in one line. System.out.println("String: " + t); }
  • 3. You can find the code, instanceofs. JEP 358 — Helpful NullPointerExceptions NullPointerExceptions cause frustrations because they often appear in application logs when code is running in a production environment, which can make debugging difficult. After all, the original code is not readily available. For example, consider the code below: Before Java 14, you might get the following error: Exception in thread “main” java.lang.NullPointerException com.java14features.nullpointerexception.Example1.main(Example1.java:15) Unfortunately, if at line 15, there’s an assignment with multiple method invocations getAmount() and getCurrency() either one could be returning null. So, it’s not clear what is causing the NullPointerException //Legal use if (obj instanceof String t && t.length() > 4) { System.out.println("String: " + t); } //Cannot resolve symbol 't' if(obj instanceof String t || t.length()>4){ System.out.println("String: "+t); } Account account =new Account(); String accountNumber=account.getAmount().getCurrency(); //line 15 System.out.println(accountNumber.length());
  • 4. Now, with Java 14, there’s a new JVM feature through which you can receive more-informative diagnostics: Exception in thread “main” java.lang.NullPointerException: Cannot invoke “com.java14features.dto.Amount.getCurrency()” because the return value of “com.java14features.dto.Account.getAmount()” is null at com.java14features.nullpointerexception.Example1.main(Example1.java:16) The message now has two clear components: The consequence: Amount.getCurrency() cannot be invoked. The reason: The return value of Account.getAmount() is null. The enhanced diagnostics work only when you run Java with the following flag: -XX:+ShowCodeDetailsInExceptionMessages You can find the code, null pointer exception. JEP 359 — Records Records focus on certain domain classes whose purpose is only to store data in fields. A new class called record , it is a final class, not abstract, and all of its fields are final as well. The record will automatically generate the constructors , getters , equals() , hashCode() , toString() during compile-time and it can implements interfaces. Restrictions: A record is a final class A record cannot extend a class The value (reference) of a field is final and cannot be changed A record class is an immutable
  • 5. A record can not setters You can find the code, records. JEP 361 — Switch Expressions The Switch Expressions is a preview feature in Java 12 and 13, it becomes a standard language feature, it means from Java 14 and onward, we can use these Switch Expressions which can be used as an expression with help of arrow (->) , and now can yield/return the value. public record Transaction( int id, double amount, String description { } /* ---- You can use JShell with the flag --enable-preview Automatically generate: * constructors * getters * equals() * hashCode() * toString() */ VehicleType vehicleType = VehicleType.AUTOMOBILE; int speedLimit = switch (vehicleType) { case BIKE, SCOOTER -> 40; case MOTORBIKE, AUTOMOBILE -> 140; case TRUCK -> 80; default -> throw new IllegalStateException("No case found for: " + vehicleType); }; System.out.println("Speed limit: " + speedLimit);
  • 6. Following examples call method and return a new yield. ///////////////////////////////////////// VehicleType vehicleType = VehicleType.TRUCK; int speedLimit = switch (vehicleType) { case BIKE, SCOOTER -> 40; case MOTORBIKE, AUTOMOBILE -> 140; case TRUCK -> { int randomSpeed = ThreadLocalRandom.current().nextInt(70, 80); yield randomSpeed; } }; System.out.println("Speed limit: " + speedLimit); ///////////////////////////////////////// public static void main(String[] args) { System.out.println( grade(9)); } public static String grade(int mark) { return switch (mark) { case 9 -> "A"; case 8 -> "B"; case 7 -> "C"; case 6 -> "D"; default -> "F"; }; } public static void main(String[] args) { for (VehicleType vehicle : VehicleType.values()) { int speedLimit = getSpeedLimit(vehicle); System.out.println("Speed limit: " + vehicle + ":" + speedLimit);
  • 7. You can find the code, switches. JEP 368 — Text Blocks (Second Preview) In Java, to embed HTML, XML, SQL, TEXT BLOCK or JSON snippet into code is often hard to read and hard to keep, and to overcome this problem, Java 14 has introduced Text Block. A text block contains zero or more content characters, which are enclosed by open and close delimiters. } } private static int getSpeedLimit(VehicleType vehicleType) { return switch (vehicleType) { case BIKE, SCOOTER -> 40; case MOTORBIKE, AUTOMOBILE -> 140; case TRUCK -> 80; }; } ///////////////////////////////////////// public static void main(String[] args) { Days day = FRIDAY; int j = switch (day) { case MONDAY -> 0; case TUESDAY -> 1; default -> { int result = day.toString().length(); yield result; } }; System.out.println(j); } }
  • 8. Text block using three double-quote characters newlines (line-terminator) denoted by for white space (single space) denoted by /s string format for a parameter using %s String text = """"""; // illegal text block start String text = """ """; // illegal text block start String text = """ """; // Text block //Without Text Block HTML String html = "<html>n" + " <body>n" + " <p>Hello, world</p>n" + " </body>n" + "</html>n"; System.out.println(html); // Text Block HTML String htmlTag = """ <html> <body> <p>Hello, world</p> </body> </html> """; // Text Block multi line (paragraph) String text = """ two escape sequences first is for newlines and, second is to signify white space or single space. """;
  • 9. Following examples are string formatted. // Text Block SQL Query String query1 = """ SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB` WHERE `CITY` = 'INDIANAPOLIS' ORDER BY `EMP_ID`, `LAST_NAME`; """; // Text Block JSON Example String json= """ { "amount": { "currency": "string", "value": 0 }, "creditorAccount": { "accountName": "string", "accountNumber": "string", "sortCode": "string" }, "debtorAccount": { "accountName": "string", "accountNumber": "string", "sortCode": "string" }, "paymentDate": "string", "reference": "string" } """; String html1 = """ <html> <body> <p>%s, %s</p> </body>
  • 10. You can find the code, textsblocks. </html> """; String print = html1.formatted("Hello1", "Java 14"); String html2 = String.format(""" <html> <body> <p>%s, %s</p> </body> </html> """, "Hello2", "Java 14"); String html3 = """ <html> <body> <p>%s, %s</p> </body> </html> """.formatted("Hello3", "Java 14");