Java 17

Features in Java 17 (JDK 17)
Mutlu Okuducu/ Software Developer
Programmers typically target a specific, long-term support (LTS)
release when they develop applications. That means for the past
several years, most Java developers were limited to the Java 8 or Java
11 feature set.
The newest long-term support release for the Java SE platform is Java
17 LTS. Under the Oracle No-Fee Terms and Conditions License, JDK
17 binaries are free to use in production and redistribute at no cost.
LTS stands for long-term support. It will be available on September
15, 2021.
Several improvements in these Java 17 features will make enterprise
software development much easier.
Spring Boot 3.0 is now generally available. The new release is
based on Spring Framework 6.0 and requires Java 17.
Top 5 Java 17 features that developers
will love.
The new Java Record data type (JDK 14)
Java text blocks (JDK 14)
Helpful NullPointerException guidance (JDK 14)
Pattern Matching for Switch (Preview)
Sealed classes
Enhanced Pseudo-Random Number Generator
•
1.
2.
3.
4.
5.
6.
1-The new Java Record data type;
Records:
Records focus on certain domain classes whose purpose is only to
store data in fields. A new class called record 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() and 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
•
•
•
•
•
public record Transaction(int id, double amount,
}
/*
---- * You can use JShell with the flag --enable
Automatically generate:
You can find the code, records.
2- Java text blocks;
In Java, embedding HTML, XML, SQL, TEXT BLOCK or JSON snippets
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 enclosed by open and
closed delimiters.
The text block starts and ends with three quotation marks each. The
following rules apply:
* constructors
* getters
* equals()
* hashCode()
* toString()
*/
//You can use Transaction like any regular class
Transaction trans = new Transaction(5, 100, "Pay
int amount= trans.amount();
int description= trans.description();
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
You do not need to escape single or double quotes within the
text block, but you may (though SCA tools such as SonarLint
recommend not doing so).
•
•
•
•
•
String text = """"""; // illegal text block star
String text = """ """; // illegal text block sta
String text = """
"""; // legal text block
// 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 fo
and, second is to signify white
or single space.
""";
// Text Block SQL Query
String query1 = """
SELECT `EMP_ID`, `LAST_NAME`
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",
The following examples are string formatted.
"reference": "string"
}
""";
String html1 = """
<html>
<body>
<p>%s, %s</p>
</body>
</html>
""";
String print = html1.formatted("Hello1", "Java 1
String html2 =
String.format("""
<html>
<body>
<p>%s, %s</p>
</body>
</html>
""", "Hello2", "Java 14");
String html3 = """
<html>
<body>
<p>%s, %s</p>
You can find the code, textsblocks.
3- Helpful NullPointerException guidance;
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
</body>
</html>
""".formatted("Hello3", "Java 14");
Account account =new Account();
String accountNumber=account.getAmount().getCur
System.out.println(accountNumber.length());
“main” java.lang.NullPointerException
com.java14features.nullpointerexception.Example1.main(Example
1.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
Now, with Java 17, 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(Example
1.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.
4- Pattern Matching for Switch (Preview):
The Switch Expressions were released in Java 14, and it becomes a
standard language feature, we can use these Switch Expressions
which can be used as an expression with help of an arrow (->) ,
and now can yield/return the value.
Switch Expressions are actually two enhancements that can be used
independently but also combined:
Arrow notation without break and fall-throughs
Using switch as an expression with a return value
The following examples call the method and return a new yield.
1.
2.
switch (day) {
case MONDAY, FRIDAY, SUNDAY -> System.out.prin
case TUESDAY -> System.out.prin
case THURSDAY, SATURDAY -> System.out.prin
case WEDNESDAY -> {
int three = 1 + 2;
System.out.println(three * three);
}
}
public static void main(String[] args) {
for (VehicleType vehicle : VehicleType.values())
int speedLimit = getSpeedLimit(vehicle);
System.out.println("Speed limit: " + vehicle
}
}
private static int getSpeedLimit(VehicleType veh
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);
}
}
Pattern matching and null
Now we can test the null in switch directly.
Old code.
After JDK 17
public static void main(String[] args) {
testString("Java 16"); // Ok
testString("Java 11"); // LTS
testString(""); // Ok
testString(null); // Unknown!
}
static void testString(String s) {
if (s == null) {
System.out.println("Unknown!");
return;
}
switch (s) {
case "Java 11", "Java 17" -> System.
default -> System.
}
}
Further Reading
JEP 406: Pattern Matching for switch (Preview)
You can find the code, switches.
5- Sealed classes:
Sealed classes and interfaces were the big news in Java 17.
public static void main(String[] args) {
testStringJava17("Java 16"); // Ok
testStringJava17("Java 11"); // LTS
testStringJava17(""); // Ok
testStringJava17(null); // Unknown
}
static void testStringJava17(String s) {
switch (s) {
case null -> Syste
case "Java 11", "Java 17" -> Syste
default -> Syste
}
}
Inheritance is a powerful construct. But there are very few Java
syntax checkpoints that limit the potential for inheritance-based,
object-oriented corruption. The sealed Java class helps reign in the
overzealous and often detrimental abuse of Java inheritance.
Sealed classes allow a developer to explicitly declare the names of
the components that can legally inherit from a class they create. No
longer is the inelegant use of an access modifier the only way to
restrict the use of a superclass.
In this section, you will learn:
What are sealed classes and interfaces?
How exactly do sealed classes and interfaces work?
What do we need them for?
Why should we restrict the extensibility of a class hierarchy?
•
•
•
•
Let’s start with an example…
Sealed classes are declared using sealed modifier and
permits clause. permits clause specifies the sub-classes
which can extend the current sealed class.
•
sealed class SuperClass permits SubClassOne, Sub
{
//Sealed Super Class
}
final class SubClassOne extends SuperClass
{
//Final Sub Class
}
From: https://blogs.oracle.com/javamagazine/post/java-sealed-classes-fight-ambiguity
Permitted sub-classes must be either final or sealed or non-
sealed . If you don’t declare permitted sub-classes with any one
of these modifiers, you will get compile time error.
final class SubClassTwo extends SuperClass
{
//Final Sub Class
}
•
sealed class SuperClass permits SubClassOne, Sub
{
//Sealed Super Class
}
final class SubClassOne extends SuperClass
{
//Final Sub Class
}
sealed class SubClassTwo extends SuperClass perm
{
//Sealed Sub Class permitting another subcla
}
non-sealed class SubClassThree extends SuperClas
{
//non-sealed subclass
final permitted sub-classes can not be extended further,
sealed permitted sub-classes are extended further by only
permitted sub-classes and non-sealed permitted sub-classes
can be extended by anyone.
Sealed class must and should specify its permitted subclasses
using permits clause otherwise there will be a compilation
error.
Permitted sub-classes must and should extend their sealed
superclass directly.
}
final class AnotherSubClass extends SubClassTwo
{
//Final subclass of SubClassTwo
}
•
•
sealed class AnyClass
{
//Compile Time Error: Sealed class must spec
}
•
In the same way, you can also declare sealed interfaces with
permitted sub interfaces or sub classes.
sealed class SuperClass permits SubClassOne, Sub
{
//Sealed Super Class
}
final class SubClassOne
{
//Compile Time Error: It must extend SuperCl
}
non-sealed class SubClassTwo
{
//Compile Time Error: It must extend SuperCl
}
•
sealed interface SealedInterface permits SubInte
{
//Sealed Super Interface
}
non-sealed interface SubInterface extends Sealed
{
//Non-sealed Sub Interface
}
Permitted subinterfaces must be either sealed or non-sealed
but not final .
non-sealed class SubClass implements SealedInter
{
//Non-sealed subclass
}
•
sealed interface SealedInterface permits SubInte
{
//Sealed Super Interface
}
sealed interface SubInterfaceOne extends SealedI
{
//Sealed Sub Interface
}
non-sealed class SubClass implements SubInterfac
{
//non-sealed subclass implementing SubInterf
}
non-sealed interface SubInterfaceTwo extends Sea
{
//Non-sealed Sub Interface
}
Permitted sub types must have name. Hence, anonymous inner
classes or local inner classes can’t be permitted sub types.
A sealed super class can be abstract , and permitted sub
classes can also be abstract provided they can be either
sealed or non-sealed but not final .
final interface SubInterfaceThree extends Sealed
{
//Compile time Error: Permitted subinterface
}
•
•
abstract sealed class SuperClass permits SubClas
{
//Super class can be abstract and Sealed
}
abstract final class SubClassOne extends SuperCl
{
//Compile Time Error : Sub class can't be fi
}
abstract non-sealed class SubClassTwo extends Su
{
//Sub class can be abstract and Non-sealed
}
abstract sealed class SubClassThree extends Supe
While declaring sealed classes and sealed interfaces, permits
clause must be used after extends and implements clause.
With the introduction of sealed classes, two more methods are
added to java.lang.Class (Reflection API). They are
getPermittedSubclasses() and isSealed() .
Also Read :
Sealed Classes & Interfaces OpenJDK Reference
6- Enhanced Pseudo-Random Number
Generators:
This JEP introduced a new interface called RandomGenerator to make
future pseudorandom number generator (PRNG) algorithms easier
to implement or use.
{
//Sub class can be abstract and Sealed
}
final class AnotherSubClass extends SubClassThre
{
//Final sub class of SubClassThree
}
•
•
•
The below example uses the new Java 17 RandomGeneratorFactory to
get the famous Xoshiro256PlusPlus PRNG algorithms to generate
random integers within a specific range, 0 – 5.
RandomNumberGenerator.java
package java.util.random;
public interface RandomNumberGenerator {
//...
}
import java.util.random.RandomGenerator;
import java.util.random.RandomGeneratorFactory;
public class RandomNumberGenerator {
public static void main(String[] args) {
// legacy
// RandomGeneratorFactory.of("Random").cre
// default L32X64MixRandom
// RandomGenerator randomGenerator =
// RandomGeneratorFactory
RandomGenerator randomGenerator =
Output:
All the Java 17 PRNG algorithms.
RandomGeneratorFactory.of("Xoshi
System.out.println(randomGenerator.getClas
int counter = 0;
while(counter<=5){
// 0-5
int result = randomGenerator.nextInt(6
System.out.println(result);
counter++;
}
}
}
class jdk.random.Xoshiro256PlusPlus
4
6
9
5
7
6
Java 17 also refactored the legacy random classes like
java.util.Random , SplittableRandom and SecureRandom to extend
the new RandomGenerator interface.
Further Reading
JEP 356: Enhanced Pseudo-Random Number Generators
Java 17’s Enhanced Pseudo-Random Number Generators
Group ---- Name
-------------------------
LXM : L128X1024MixRandom
LXM : L128X128MixRandom
LXM : L128X256MixRandom
LXM : L32X64MixRandom
LXM : L64X1024MixRandom
LXM : L64X128MixRandom
LXM : L64X128StarStarRandom
LXM : L64X256MixRandom
Legacy : Random
Legacy : SecureRandom
Legacy : SplittableRandom
Xoroshiro : Xoroshiro128PlusPlus
Xoshiro : Xoshiro256PlusPlus
Java 17
1 von 25

Recomendados

Deep Dive Java 17 Devoxx UK von
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKJosé Paumard
984 views77 Folien
From Java 11 to 17 and beyond.pdf von
From Java 11 to 17 and beyond.pdfFrom Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdfJosé Paumard
475 views100 Folien
Spring Boot 3 And Beyond von
Spring Boot 3 And BeyondSpring Boot 3 And Beyond
Spring Boot 3 And BeyondVMware Tanzu
147 views47 Folien
Spring Boot in Action von
Spring Boot in Action Spring Boot in Action
Spring Boot in Action Alex Movila
3K views55 Folien
Spring Boot and REST API von
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
670 views27 Folien
Introduce yourself to java 17 von
Introduce yourself to java 17Introduce yourself to java 17
Introduce yourself to java 17ankitbhandari32
287 views7 Folien

Más contenido relacionado

Was ist angesagt?

Introduction to Spring Boot von
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring BootPurbarun Chakrabarti
1.1K views18 Folien
From Spring Framework 5.3 to 6.0 von
From Spring Framework 5.3 to 6.0From Spring Framework 5.3 to 6.0
From Spring Framework 5.3 to 6.0VMware Tanzu
2.6K views11 Folien
Javaday Paris 2022 - Java en 2022 : profiter de Java 17 von
Javaday Paris 2022 - Java en 2022 : profiter de Java 17Javaday Paris 2022 - Java en 2022 : profiter de Java 17
Javaday Paris 2022 - Java en 2022 : profiter de Java 17Jean-Michel Doudoux
70 views50 Folien
Migrating to Java 11 von
Migrating to Java 11Migrating to Java 11
Migrating to Java 11Arto Santala
2.1K views33 Folien
Java 9/10/11 - What's new and why you should upgrade von
Java 9/10/11 - What's new and why you should upgradeJava 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgradeSimone Bordet
3.2K views44 Folien
Spring Boot von
Spring BootSpring Boot
Spring BootJaran Flaath
543 views51 Folien

Was ist angesagt?(20)

From Spring Framework 5.3 to 6.0 von VMware Tanzu
From Spring Framework 5.3 to 6.0From Spring Framework 5.3 to 6.0
From Spring Framework 5.3 to 6.0
VMware Tanzu2.6K views
Javaday Paris 2022 - Java en 2022 : profiter de Java 17 von Jean-Michel Doudoux
Javaday Paris 2022 - Java en 2022 : profiter de Java 17Javaday Paris 2022 - Java en 2022 : profiter de Java 17
Javaday Paris 2022 - Java en 2022 : profiter de Java 17
Migrating to Java 11 von Arto Santala
Migrating to Java 11Migrating to Java 11
Migrating to Java 11
Arto Santala2.1K views
Java 9/10/11 - What's new and why you should upgrade von Simone Bordet
Java 9/10/11 - What's new and why you should upgradeJava 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgrade
Simone Bordet3.2K views
REST APIs with Spring von Joshua Long
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
Joshua Long25.6K views
Loom Virtual Threads in the JDK 19 von José Paumard
Loom Virtual Threads in the JDK 19Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19
José Paumard401 views
WebSphere Application Server V8.5.5 Libertyプロファイルのご紹介 #jjug_ccc #ccc_r51 von Takakiyo Tanaka
WebSphere Application Server V8.5.5Libertyプロファイルのご紹介 #jjug_ccc #ccc_r51WebSphere Application Server V8.5.5Libertyプロファイルのご紹介 #jjug_ccc #ccc_r51
WebSphere Application Server V8.5.5 Libertyプロファイルのご紹介 #jjug_ccc #ccc_r51
Takakiyo Tanaka5.6K views
Spring annotations notes von Vipul Singh
Spring annotations notesSpring annotations notes
Spring annotations notes
Vipul Singh548 views
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor von VMware Tanzu
Reactive Card Magic: Understanding Spring WebFlux and Project ReactorReactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
VMware Tanzu3.7K views
Introduction to Spring's Dependency Injection von Richard Paul
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
Richard Paul4K views

Similar a Java 17

00_Introduction to Java.ppt von
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.pptHongAnhNguyn285885
8 views84 Folien
Java 7 new features von
Java 7 new featuresJava 7 new features
Java 7 new featuresShivam Goel
2.2K views23 Folien
Bring the fun back to java von
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
640 views32 Folien
Java 7 & 8 New Features von
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New FeaturesLeandro Coutinho
280 views60 Folien
Dynamic websites lec3 von
Dynamic websites lec3Dynamic websites lec3
Dynamic websites lec3Belal Arfa
667 views28 Folien
Cordova training : Day 3 - Introduction to Javascript von
Cordova training : Day 3 - Introduction to JavascriptCordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to JavascriptBinu Paul
237 views36 Folien

Similar a Java 17(20)

Java 7 new features von Shivam Goel
Java 7 new featuresJava 7 new features
Java 7 new features
Shivam Goel2.2K views
Bring the fun back to java von ciklum_ods
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods640 views
Dynamic websites lec3 von Belal Arfa
Dynamic websites lec3Dynamic websites lec3
Dynamic websites lec3
Belal Arfa667 views
Cordova training : Day 3 - Introduction to Javascript von Binu Paul
Cordova training : Day 3 - Introduction to JavascriptCordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to Javascript
Binu Paul237 views
Javascript sivasoft von ch samaram
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
ch samaram709 views
Examples from Pune meetup von Santosh Ojha
Examples from Pune meetupExamples from Pune meetup
Examples from Pune meetup
Santosh Ojha435 views
Java script von bosybosy
 Java script Java script
Java script
bosybosy1.1K views
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen... von Codemotion
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Codemotion808 views
Python RESTful webservices with Python: Flask and Django solutions von Solution4Future
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future72.5K views
Smoothing Your Java with DSLs von intelliyole
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
intelliyole1.1K views
Java script basics von John Smith
Java script basicsJava script basics
Java script basics
John Smith39 views

Último

HarshithAkkapelli_Presentation.pdf von
HarshithAkkapelli_Presentation.pdfHarshithAkkapelli_Presentation.pdf
HarshithAkkapelli_Presentation.pdfharshithakkapelli
11 views16 Folien
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx von
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptxanimuscrm
15 views19 Folien
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko... von
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...Deltares
14 views23 Folien
DSD-INT 2023 The Danube Hazardous Substances Model - Kovacs von
DSD-INT 2023 The Danube Hazardous Substances Model - KovacsDSD-INT 2023 The Danube Hazardous Substances Model - Kovacs
DSD-INT 2023 The Danube Hazardous Substances Model - KovacsDeltares
10 views17 Folien
nintendo_64.pptx von
nintendo_64.pptxnintendo_64.pptx
nintendo_64.pptxpaiga02016
5 views7 Folien
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P... von
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...NimaTorabi2
12 views17 Folien

Último(20)

2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx von animuscrm
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
animuscrm15 views
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko... von Deltares
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
Deltares14 views
DSD-INT 2023 The Danube Hazardous Substances Model - Kovacs von Deltares
DSD-INT 2023 The Danube Hazardous Substances Model - KovacsDSD-INT 2023 The Danube Hazardous Substances Model - Kovacs
DSD-INT 2023 The Danube Hazardous Substances Model - Kovacs
Deltares10 views
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P... von NimaTorabi2
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
NimaTorabi212 views
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols von Deltares
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - DolsDSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols
DSD-INT 2023 European Digital Twin Ocean and Delft3D FM - Dols
Deltares9 views
Headless JS UG Presentation.pptx von Jack Spektor
Headless JS UG Presentation.pptxHeadless JS UG Presentation.pptx
Headless JS UG Presentation.pptx
Jack Spektor8 views
DSD-INT 2023 Exploring flash flood hazard reduction in arid regions using a h... von Deltares
DSD-INT 2023 Exploring flash flood hazard reduction in arid regions using a h...DSD-INT 2023 Exploring flash flood hazard reduction in arid regions using a h...
DSD-INT 2023 Exploring flash flood hazard reduction in arid regions using a h...
Deltares9 views
Fleet Management Software in India von Fleetable
Fleet Management Software in India Fleet Management Software in India
Fleet Management Software in India
Fleetable11 views
Copilot Prompting Toolkit_All Resources.pdf von Riccardo Zamana
Copilot Prompting Toolkit_All Resources.pdfCopilot Prompting Toolkit_All Resources.pdf
Copilot Prompting Toolkit_All Resources.pdf
Riccardo Zamana10 views
SUGCON ANZ Presentation V2.1 Final.pptx von Jack Spektor
SUGCON ANZ Presentation V2.1 Final.pptxSUGCON ANZ Presentation V2.1 Final.pptx
SUGCON ANZ Presentation V2.1 Final.pptx
Jack Spektor23 views
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI... von Marc Müller
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...
Marc Müller41 views
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium... von Lisi Hocke
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Lisi Hocke35 views
FIMA 2023 Neo4j & FS - Entity Resolution.pptx von Neo4j
FIMA 2023 Neo4j & FS - Entity Resolution.pptxFIMA 2023 Neo4j & FS - Entity Resolution.pptx
FIMA 2023 Neo4j & FS - Entity Resolution.pptx
Neo4j8 views
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra... von Marc Müller
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra....NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
Marc Müller40 views

Java 17

  • 1. Features in Java 17 (JDK 17) Mutlu Okuducu/ Software Developer Programmers typically target a specific, long-term support (LTS) release when they develop applications. That means for the past
  • 2. several years, most Java developers were limited to the Java 8 or Java 11 feature set. The newest long-term support release for the Java SE platform is Java 17 LTS. Under the Oracle No-Fee Terms and Conditions License, JDK 17 binaries are free to use in production and redistribute at no cost. LTS stands for long-term support. It will be available on September 15, 2021. Several improvements in these Java 17 features will make enterprise software development much easier. Spring Boot 3.0 is now generally available. The new release is based on Spring Framework 6.0 and requires Java 17. Top 5 Java 17 features that developers will love. The new Java Record data type (JDK 14) Java text blocks (JDK 14) Helpful NullPointerException guidance (JDK 14) Pattern Matching for Switch (Preview) Sealed classes Enhanced Pseudo-Random Number Generator • 1. 2. 3. 4. 5. 6.
  • 3. 1-The new Java Record data type; Records: Records focus on certain domain classes whose purpose is only to store data in fields. A new class called record 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() and 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 • • • • • public record Transaction(int id, double amount, } /* ---- * You can use JShell with the flag --enable Automatically generate:
  • 4. You can find the code, records. 2- Java text blocks; In Java, embedding HTML, XML, SQL, TEXT BLOCK or JSON snippets 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 enclosed by open and closed delimiters. The text block starts and ends with three quotation marks each. The following rules apply: * constructors * getters * equals() * hashCode() * toString() */ //You can use Transaction like any regular class Transaction trans = new Transaction(5, 100, "Pay int amount= trans.amount(); int description= trans.description();
  • 5. 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 You do not need to escape single or double quotes within the text block, but you may (though SCA tools such as SonarLint recommend not doing so). • • • • • String text = """"""; // illegal text block star String text = """ """; // illegal text block sta String text = """ """; // legal text block // 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>
  • 6. </html> """; // Text Block multi line (paragraph) String text = """ two escape sequences first is fo and, second is to signify white or single space. """; // Text Block SQL Query String query1 = """ SELECT `EMP_ID`, `LAST_NAME` 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",
  • 7. The following examples are string formatted. "reference": "string" } """; String html1 = """ <html> <body> <p>%s, %s</p> </body> </html> """; String print = html1.formatted("Hello1", "Java 1 String html2 = String.format(""" <html> <body> <p>%s, %s</p> </body> </html> """, "Hello2", "Java 14"); String html3 = """ <html> <body> <p>%s, %s</p>
  • 8. You can find the code, textsblocks. 3- Helpful NullPointerException guidance; 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 </body> </html> """.formatted("Hello3", "Java 14"); Account account =new Account(); String accountNumber=account.getAmount().getCur System.out.println(accountNumber.length());
  • 9. “main” java.lang.NullPointerException com.java14features.nullpointerexception.Example1.main(Example 1.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 Now, with Java 17, 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(Example 1.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.
  • 10. 4- Pattern Matching for Switch (Preview): The Switch Expressions were released in Java 14, and it becomes a standard language feature, we can use these Switch Expressions which can be used as an expression with help of an arrow (->) , and now can yield/return the value. Switch Expressions are actually two enhancements that can be used independently but also combined: Arrow notation without break and fall-throughs Using switch as an expression with a return value The following examples call the method and return a new yield. 1. 2. switch (day) { case MONDAY, FRIDAY, SUNDAY -> System.out.prin case TUESDAY -> System.out.prin case THURSDAY, SATURDAY -> System.out.prin case WEDNESDAY -> { int three = 1 + 2; System.out.println(three * three); } }
  • 11. public static void main(String[] args) { for (VehicleType vehicle : VehicleType.values()) int speedLimit = getSpeedLimit(vehicle); System.out.println("Speed limit: " + vehicle } } private static int getSpeedLimit(VehicleType veh 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); } }
  • 12. Pattern matching and null Now we can test the null in switch directly. Old code. After JDK 17 public static void main(String[] args) { testString("Java 16"); // Ok testString("Java 11"); // LTS testString(""); // Ok testString(null); // Unknown! } static void testString(String s) { if (s == null) { System.out.println("Unknown!"); return; } switch (s) { case "Java 11", "Java 17" -> System. default -> System. } }
  • 13. Further Reading JEP 406: Pattern Matching for switch (Preview) You can find the code, switches. 5- Sealed classes: Sealed classes and interfaces were the big news in Java 17. public static void main(String[] args) { testStringJava17("Java 16"); // Ok testStringJava17("Java 11"); // LTS testStringJava17(""); // Ok testStringJava17(null); // Unknown } static void testStringJava17(String s) { switch (s) { case null -> Syste case "Java 11", "Java 17" -> Syste default -> Syste } }
  • 14. Inheritance is a powerful construct. But there are very few Java syntax checkpoints that limit the potential for inheritance-based, object-oriented corruption. The sealed Java class helps reign in the overzealous and often detrimental abuse of Java inheritance. Sealed classes allow a developer to explicitly declare the names of the components that can legally inherit from a class they create. No longer is the inelegant use of an access modifier the only way to restrict the use of a superclass. In this section, you will learn: What are sealed classes and interfaces? How exactly do sealed classes and interfaces work? What do we need them for? Why should we restrict the extensibility of a class hierarchy? • • • •
  • 15. Let’s start with an example… Sealed classes are declared using sealed modifier and permits clause. permits clause specifies the sub-classes which can extend the current sealed class. • sealed class SuperClass permits SubClassOne, Sub { //Sealed Super Class } final class SubClassOne extends SuperClass { //Final Sub Class } From: https://blogs.oracle.com/javamagazine/post/java-sealed-classes-fight-ambiguity
  • 16. Permitted sub-classes must be either final or sealed or non- sealed . If you don’t declare permitted sub-classes with any one of these modifiers, you will get compile time error. final class SubClassTwo extends SuperClass { //Final Sub Class } • sealed class SuperClass permits SubClassOne, Sub { //Sealed Super Class } final class SubClassOne extends SuperClass { //Final Sub Class } sealed class SubClassTwo extends SuperClass perm { //Sealed Sub Class permitting another subcla } non-sealed class SubClassThree extends SuperClas { //non-sealed subclass
  • 17. final permitted sub-classes can not be extended further, sealed permitted sub-classes are extended further by only permitted sub-classes and non-sealed permitted sub-classes can be extended by anyone. Sealed class must and should specify its permitted subclasses using permits clause otherwise there will be a compilation error. Permitted sub-classes must and should extend their sealed superclass directly. } final class AnotherSubClass extends SubClassTwo { //Final subclass of SubClassTwo } • • sealed class AnyClass { //Compile Time Error: Sealed class must spec } •
  • 18. In the same way, you can also declare sealed interfaces with permitted sub interfaces or sub classes. sealed class SuperClass permits SubClassOne, Sub { //Sealed Super Class } final class SubClassOne { //Compile Time Error: It must extend SuperCl } non-sealed class SubClassTwo { //Compile Time Error: It must extend SuperCl } • sealed interface SealedInterface permits SubInte { //Sealed Super Interface } non-sealed interface SubInterface extends Sealed { //Non-sealed Sub Interface }
  • 19. Permitted subinterfaces must be either sealed or non-sealed but not final . non-sealed class SubClass implements SealedInter { //Non-sealed subclass } • sealed interface SealedInterface permits SubInte { //Sealed Super Interface } sealed interface SubInterfaceOne extends SealedI { //Sealed Sub Interface } non-sealed class SubClass implements SubInterfac { //non-sealed subclass implementing SubInterf } non-sealed interface SubInterfaceTwo extends Sea { //Non-sealed Sub Interface }
  • 20. Permitted sub types must have name. Hence, anonymous inner classes or local inner classes can’t be permitted sub types. A sealed super class can be abstract , and permitted sub classes can also be abstract provided they can be either sealed or non-sealed but not final . final interface SubInterfaceThree extends Sealed { //Compile time Error: Permitted subinterface } • • abstract sealed class SuperClass permits SubClas { //Super class can be abstract and Sealed } abstract final class SubClassOne extends SuperCl { //Compile Time Error : Sub class can't be fi } abstract non-sealed class SubClassTwo extends Su { //Sub class can be abstract and Non-sealed } abstract sealed class SubClassThree extends Supe
  • 21. While declaring sealed classes and sealed interfaces, permits clause must be used after extends and implements clause. With the introduction of sealed classes, two more methods are added to java.lang.Class (Reflection API). They are getPermittedSubclasses() and isSealed() . Also Read : Sealed Classes & Interfaces OpenJDK Reference 6- Enhanced Pseudo-Random Number Generators: This JEP introduced a new interface called RandomGenerator to make future pseudorandom number generator (PRNG) algorithms easier to implement or use. { //Sub class can be abstract and Sealed } final class AnotherSubClass extends SubClassThre { //Final sub class of SubClassThree } • • •
  • 22. The below example uses the new Java 17 RandomGeneratorFactory to get the famous Xoshiro256PlusPlus PRNG algorithms to generate random integers within a specific range, 0 – 5. RandomNumberGenerator.java package java.util.random; public interface RandomNumberGenerator { //... } import java.util.random.RandomGenerator; import java.util.random.RandomGeneratorFactory; public class RandomNumberGenerator { public static void main(String[] args) { // legacy // RandomGeneratorFactory.of("Random").cre // default L32X64MixRandom // RandomGenerator randomGenerator = // RandomGeneratorFactory RandomGenerator randomGenerator =
  • 23. Output: All the Java 17 PRNG algorithms. RandomGeneratorFactory.of("Xoshi System.out.println(randomGenerator.getClas int counter = 0; while(counter<=5){ // 0-5 int result = randomGenerator.nextInt(6 System.out.println(result); counter++; } } } class jdk.random.Xoshiro256PlusPlus 4 6 9 5 7 6
  • 24. Java 17 also refactored the legacy random classes like java.util.Random , SplittableRandom and SecureRandom to extend the new RandomGenerator interface. Further Reading JEP 356: Enhanced Pseudo-Random Number Generators Java 17’s Enhanced Pseudo-Random Number Generators Group ---- Name ------------------------- LXM : L128X1024MixRandom LXM : L128X128MixRandom LXM : L128X256MixRandom LXM : L32X64MixRandom LXM : L64X1024MixRandom LXM : L64X128MixRandom LXM : L64X128StarStarRandom LXM : L64X256MixRandom Legacy : Random Legacy : SecureRandom Legacy : SplittableRandom Xoroshiro : Xoroshiro128PlusPlus Xoshiro : Xoshiro256PlusPlus