0% found this document useful (0 votes)
87 views11 pages

Migrate From Java 8 To Java 17 - Baeldung

Uploaded by

marc0000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views11 pages

Migrate From Java 8 To Java 17 - Baeldung

Uploaded by

marc0000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

30/09/2025 01:05 Migrate From Java 8 to Java 17 | Baeldung

(/)

Start Here (/start-here) Spring Courses ▼ Java Courses ▼ Pricing (/pricing) About ▼
(/feed) (/members/)
Migrate From Java 8 to Java 17

TOUT à -40% Hiver 2025

MiniDive Ouvrir

Last updated: January 8, 2024

Written by: Palaniappan Arunachalam ([Link]

Reviewed by: Saajan Nagendra ([Link]

Java ([Link] +
>= Java 17 ([Link] >= Java 8 ([Link]

[Link] 1/11
30/09/2025 01:05 Migrate From Java 8 to Java 17 | Baeldung

1. Overview (/)

Often we faceStart
a dilemma about whetherSpring
Here (/start-here) to migrate to a newerJava
Courses version of Java orPricing
Courses continue with the existing
(/pricing) Aboutone. In other words, we need to
▼ ▼

balance the new features and enhancements against the total efforts that would be needed to migrate.

(/feed) (/members/)
In this tutorial, we’ll walk through some extremely useful features available in the newer versions of Java. These features aren’t only easy to
learn but can also be implemented quickly without much effort when planning to migrate from Java 8 to Java 17.

2. Using String
Let’s look at some of the interesting enhancements to the String class.

2.1. Compact String


Java 9 introduced Compact String (/java-9-compact-string), a performance enhancement to optimize the memory consumption of String objects.
In simple terms, a String object will be internally represented as byte[] instead of char[]. To explain, every char is made up of 2 bytes because
Java internally uses UTF-16. In most cases, String objects are English words that can be represented with a single byte which is nothing but
LATIN-1 representation.

Java internally handles this representation based on the actual content of the String object: a byte[] for([Link]
the LATIN-1 character set and a char[] if the
utm_campaign=branding&utm_medium=display&utm_source=[Link]&utm_content=baeldung_l
content contains any special chars (UTF-16). So, it’s fully transparent to the developers using String objects.

[Link] 2/11
30/09/2025 01:05 Migrate From Java 8 to Java 17 | Baeldung

Until Java 8, the String was internally represented as char[]:


(/)
char[] value;
Start Here (/start-here) Spring Courses ▼ Java Courses ▼ Pricing (/pricing) About ▼
(/feed) (/members/)
From Java 9, it will be a byte[]:

byte[] value;

2.2. Text Block


Before Java 15, embedding multi-line code snippets will require explicit line terminators, String concatenations, and delimiters. To address this,
Java 15 introduced text blocks (/java-text-blocks) that allow us to embed code snippets and text sequences more or less as-is. This is
particularly useful when dealing with literal fragments such as HTML, JSON, and SQL.
A text block is an alternative form of String representation that can be used anywhere a normal double-quoted String literal can be used. For
instance, a multi-line String literal can be represented without explicit usage of line terminators and String concatenations:

([Link]
utm_campaign=branding&utm_medium=display&utm_source=[Link]&utm_content=baeldung_leaderboard_mid_2)

// Using a Text Block


String value = """
Multi-line
Text
""";

[Link] 3/11
30/09/2025 01:05 Migrate From Java 8 to Java 17 | Baeldung

Prior to this feature, a multi-line text was not so readable and it was complex to represent:
(/)
// Using a Literal String
String value = "Multi-line"
Start Here (/start-here) Spring Courses ▼ Java Courses Pricing (/pricing) About
+ "\n" \\ line separator
▼ ▼
(/feed) (/members/)
"Text"
+ "\n";
String str = "Multi-line\nText\n";

2.3. New String Methods


When dealing with String objects, we often tend to use third-party libraries such as Apache Commons for common String operations. Specifically,
this is the case for utility functions to check blank/empty values and other String operations such as repeat, indentation, etc.
Subsequently, Java 11 and Java 12 introduced many such convenient functions so that we can rely on inbuilt functions for such regular String
operations: isBlank(), repeat(), indent(), lines(), strip(), and transform().
Let’s see them in action:

assertThat(" ".isBlank());
assertThat("Twinkle ".repeat(2)).isEqualTo("Twinkle Twinkle ");
assertThat("Format Line".indent(4)).isEqualTo(" Format Line\n");
assertThat("Line 1 \n Line2".lines()).asList().size().isEqualTo(2);
assertThat(" Text with white spaces ".strip()).isEqualTo("Text with white spaces");
assertThat("Car, Bus, Train".transform(s1 -> [Link]([Link](","))).get(0)).isEqualTo("Car");

3. Records
Data Transfer Objects (DTO) are useful when passing data between objects. However, creating a DTO comes with a lot of boilerplate code such as
fields, constructors, getters/setters, equals(), (/java-equals-hashcode-contracts#equals) hashcode() (/java-hashcode), and toString() (/java-
tostring) methods:

[Link] 4/11
30/09/2025 01:05 Migrate From Java 8 to Java 17 | Baeldung

(/)

Start Here (/start-here) Spring Courses ▼ Java Courses ▼ Pricing (/pricing) About ▼
(/feed) (/members/)

public class StudentDTO {

private int rollNo;


private String name;
([Link]
// constructors
utm_campaign=branding&utm_medium=display&utm_source=[Link]&utm_content=baeldung_leaderboard_mid_3)
// getters & setters
// equals(), hashcode() & toString() methods
}

Enter record (/java-15-new#records-jep-384) classes, which are a special kind of class that can define immutable data objects in a much more
compact way and identical to Project Lombok (/intro-to-project-lombok). Originally introduced as a preview feature in Java 14, the record class
is a standard feature from Java 16:

public record Student(int rollNo, String name) {


}

As we can see, record classes require only the type and name of fields. Subsequently, the compiler generates the equals(), hashCode(),
and toString() methods in addition to the public constructor, private and final fields:

Student student = new Student(10, "Priya");


Student student2 = new Student(10, "Priya");

assertThat([Link]()).isEqualTo(10);
assertThat([Link]()).isEqualTo("Priya");
assertThat([Link](student2));
assertThat([Link]()).isEqualTo([Link]());

[Link] 5/11
30/09/2025 01:05 Migrate From Java 8 to Java 17 | Baeldung

4. Helpful NullPointerException
(/)
s
NullPointerException s (NPEs)
Start Here are very common
(/start-here) exceptions that
Spring Courses Javaevery developerPricing
Courses faces. In most cases,About
(/pricing) the error messages thrown by the compiler
▼ ▼ ▼
(/feed) chaining to(/members/)
aren’t useful for identifying the exact object which is null. Also, recent trends towards functional programming and method write code
expressively and compactly make it more difficult to debug NPEs.
Let’s see one such example with method chaining usage:

[Link]().getCity().toLowerCase();

Here, if the NPE is thrown in this line, pinpointing the exact location of the null object is difficult as three possible objects can be null.
Starting with Java 14, we can now instruct the compiler with an additional VM argument to get helpful NPE (/java-14-nullpointerexception)
messages:

-XX:+ShowCodeDetailsInExceptionMessages

With this option enabled, the error message is much more precise:

Cannot invoke "[Link]()" because the return value of "[Link]()" is null

Note that, starting from Java 15, this flag is enabled by default.

[Link] 6/11
30/09/2025 01:05 Migrate From Java 8 to Java 17 | Baeldung

5. Pattern Matching
(/)

Pattern matching addresses


Start Here a commonSpring
(/start-here) logic inCourses
a program, Java
namely the conditional
Courses Pricingextraction
(/pricing)of components
About from objects, to be expressed
more concisely and safely.
▼ ▼
(/feed)

(/members/)
Let’s look at the two features that support pattern matching in Java.

5.1. Enhanced instanceOf Operator


A common logic that every program has is to check a certain type or structure and cast it to the desired type to perform further processing. This
involves a lot of boilerplate code.
Let’s look at an example:

if (obj instanceof Address) {


Address address = (Address) obj;
city = [Link]();
}

Here, we can see there are three steps involved: a test (to confirm the type), a conversion (to cast to the specific type), and a new local variable (to
further process it).
Since Java 16, Pattern Matching ([Link] for instanceof operator is a standard feature to address this issue. Now, we can
directly access the target type in a much more readable way:

if (obj instanceof Address address) {


city = [Link]();
}

5.2. Switch Expressions


Switch expressions (Java 14) are like regular expressions which evaluate or return a single value and can be used in statements. In addition,
Java 17 enables us to use pattern matching (preview feature) to be used in Switch expressions (/java-switch-pattern-matching):

[Link] 7/11
30/09/2025 01:05 Migrate From Java 8 to Java 17 | Baeldung

double circumference(/)
= switch(shape) {
case Rectangle r -> 2 * [Link]() + 2 * [Link]();
case Circle c -> 2 * [Link]() * [Link];
defaultStart
-> throw
Here new IllegalArgumentException("Unknown
(/start-here) Spring Courses ▼ Javashape");
Courses ▼ Pricing (/pricing) About
};

(/feed) (/members/)

As we can notice, there’s a new kind of case label syntax. switch expressions use “case L ->” labels instead of “case L:” labels. Further, there’s no
need for explicit break statements to prevent fall through. Moreover, the switch selector expression can be of any type.

When using the traditional “case L:” labels in Switch expressions, we must use the yield keyword (instead of break statement) to return the value.

6. Sealed Classes
The primary purpose of inheritance is the reusability of code. Yet, certain business domain models may require only the predefined set of classes
to extend the base class or interface. This is specifically valuable when using Domain Driven Design.
To augment this behavior, Java 17 offers Sealed classes (/java-sealed-classes-interfaces) as a standard feature. In short, a sealed class or
interface can only be extended or implemented by those classes and interfaces which are permitted to do so.
Let’s see how to define a sealed class:

public sealed class Shape permits Circle, Square, Triangle {


}

[Link] 8/11
30/09/2025 01:05 Migrate From Java 8 to Java 17 | Baeldung

Here, the Shape class permits inheritance only to a restricted set of classes. In addition, the permitted subclasses must define one of these
modifiers: final, sealed(/)
, or non-sealed:

Start
public final Here
class (/start-here)
Circle Spring
extends Shape { Courses ▼ Java Courses ▼ Pricing (/pricing) About ▼
(/feed) (/members/)
public float radius;
}

public non-sealed class Square extends Shape {


public double side;
}

public sealed class Triangle extends Shape permits ColoredTriangle {


public double height, base;
}

7. Conclusion
Over the years, Java has introduced a bunch of new features in a phased manner from Java 8 (LTS) to Java 17 (LTS). Each of these features aims to
improve multiple aspects such as productivity, performance, readability, and extensibility.
In this article, we explored a selected set of features that are quick to learn and implement. Specifically, the improvements over the String class,
record types, and pattern matching will make life easier for developers who migrate from Java 8 to Java 17.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member (/members/), start learning and
coding on the project.

Get started with Spring Boot and with core Spring, through the Learn Spring course:
>> CHECK OUT THE COURSE (/course-ls-NPI-9-7Y5va)

[Link] 9/11
30/09/2025 01:05 Migrate From Java 8 to Java 17 | Baeldung

(/) 2 COMMENTS   Oldest 

Start Here (/start-here) Spring Courses ▼ Java Courses ▼ Pricing (/pricing) About ▼
(/feed) (/members/)
View Comments

COURSES
ALL COURSES (/COURSES/ALL-COURSES)
BAELDUNG ALL ACCESS (/COURSES/ALL-ACCESS)
BAELDUNG ALL TEAM ACCESS (/COURSES/ALL-ACCESS-TEAM)
THE COURSES PLATFORM (HTTPS://[Link]/MEMBERS/ALL-COURSES)

SERIES
JAVA “BACK TO BASICS” TUTORIAL (/JAVA-TUTORIAL)

[Link] 10/11
30/09/2025 01:05 Migrate From Java 8 to Java 17 | Baeldung
LEARN SPRING BOOT SERIES (/SPRING-BOOT)
(/)
SPRING TUTORIAL (/SPRING-TUTORIAL)
GET STARTED WITH JAVA (/GET-STARTED-WITH-JAVA-SERIES)
ALL ABOUT STRING IN JAVA (/JAVA-STRING)
Start Here (/start-here)
SECURITY WITH SPRING (/SECURITY-SPRING)
Spring Courses ▼ Java Courses ▼ Pricing (/pricing) About ▼
(/feed) (/members/)
JAVA COLLECTIONS (/JAVA-COLLECTIONS)

ABOUT
ABOUT BAELDUNG (/ABOUT)
THE FULL ARCHIVE (/FULL_ARCHIVE)
EDITORS (/EDITORS)
OUR PARTNERS (/PARTNERS/)
PARTNER WITH BAELDUNG (/PARTNERS/WORK-WITH-US)
EBOOKS (/LIBRARY/)
FAQ (/LIBRARY/FAQ)
BAELDUNG PRO (/MEMBERS/)

TERMS OF SERVICE (/TERMS-OF-SERVICE)


PRIVACY POLICY (/PRIVACY-POLICY)
COMPANY INFO (/BAELDUNG-COMPANY-INFO)
CONTACT (/CONTACT)

PRIVACY PREFERENCES

[Link] 11/11

You might also like