Page
1
(This page has no text content)
Page
2
Cruising Along with Java
Page
3
Modernize and Modularize with the Latest Features
Page
4
by Venkat Subramaniam Version: P1.0 (April 2025)
Page
5
Copyright © 2025 The Pragmatic Programmers, LLC. This book is licensed to the individual who purchased it. We don't copy-protect it because that would limit your ability to use it for your own purposes. Please don't break this trust—you can use this across all of your devices but please do not share this copy with other members of your team, with friends, or via file sharing services. Thanks. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and the linking g device are trademarks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. About the Pragmatic Bookshelf The Pragmatic Bookshelf is an agile publishing company. We’re here because we want to improve the lives of developers. We do this by creating timely, practical titles, written by programmers for programmers. Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at http://pragprog.com. Our ebooks do not contain any Digital Restrictions Management, and have always been DRM-free. We pioneered the beta book concept, where you can purchase and read a book while it’s still being written, and provide feedback to the author to help make a better book for everyone. Free resources for all purchasers include source code downloads (if applicable), errata and discussion forums, all available on the book's home page at pragprog.com. We’re here to make your life easier. New Book Announcements Want to keep up on our latest titles and announcements, and occasional special offers? Just create an account on pragprog.com (an email address and a password is all it takes) and select the checkbox to receive newsletters. You can also follow us on twitter as @pragprog. About Ebook Formats If you buy directly from pragprog.com, you get ebooks in all available formats for one price. You can synch your ebooks amongst all your devices (including iPhone/iPad, Android, laptops, etc.) via Dropbox. You get free updates for the life of the edition. And, of course, you can always come back and re-download your books when needed. Ebooks bought from the Amazon Kindle store are subject to Amazon's polices. Limitations in Amazon's file format may cause ebooks to display differently on different devices. For more information, please see our FAQ at pragprog.com/#about-ebooks. To learn more about this book and access the free resources, go to https://pragprog.com/book/vscajava, the book's homepage. Thanks for your continued support, The Pragmatic Bookshelf The team that produced this book includes: Dave Thomas (Publisher), Janet Furlow (COO), Susannah Davidson (Executive Editor), Jacquelyn Carter (Development Editor), Corina Lebegioara (Copy Editor), Potomac Indexing, LLC (Indexing), Gilson Graphics (Layout) For customer support, please contact support@pragprog.com. For international rights, please contact rights@pragprog.com.
Page
6
Table of Contents Acknowledgments Preface What’s in This Book? Who’s This Book For? Java Version Used in This Book How to Read the Code Examples Online Resources 1. The Evolution of Java Java Is Agile Fast-Paced Change Recent Changes to Java Moving Ahead from an LTS Cruising Along with Java Part I. Syntax Sugar 2. Using Type Inference Type Inference and Java Generics and Type Witness Diamond Operator Enhancements Lambda Expressions Parameters Type Inference Local Variable Type Inference Using Type Inference with for and try var: Not a Type nor a Keyword Targeted Intersection Types Extent of Type Inference
Page
7
Mind the Inference Wrapping Up 3. Reducing Clutter with Text Blocks From Noisy to Nice Embedding Strings Smart Indentations Trailing Spaces and Special Escapes Creating XML Documents Using Text Blocks Creating JSON Output Using Text Blocks Wrapping Up Part II. Design Aid 4. Programming with Records From Verbose to Succinct Components, Fields, Getters, and Metadata Extent of Immutability Built-in Methods Implementing Interfaces Restrictions for the Greater Good Considering a Custom Canonical Constructor? Preferring the Compact Constructor Creating a Custom Noncanonical Constructor (Local) Records as Tuples Wrapping Up 5. Designing with Sealed Classes and Interfaces Need for a Closed Hierarchy Using sealed Sealed Related Metadata Using the permits Clause Constraints on the Subclasses Wrapping Up
Page
8
Part III. Fluent Expressions 6. Switching to Switch Expression From Statements to Expressions Using Multiple Labels in a Case Cases with Non-expressions Completeness of a switch Expression Wrapping Up 7. Using Powerful Pattern Matching Pattern Matching with instanceof Using Type Matching Matching null Guarded Patterns Dominance Check Completeness Check Completeness Check and Sealed Classes/Interfaces Deciding to Use default or Not Pattern Matching Primitive Types Destructuring Records When Pattern Matching Type Inference with Destructuring Records Unnamed Variables in Pattern Matching Wrapping Up Part IV. Modularization 8. Modularizing Your Java Applications Maven, Gradle, and Modularization Modules and the Benefits of Modularization Modularized Java Starting with a Legacy Application Perils of the Existing Design
Page
9
Modularizing the Space Station Application Architectural Constraints Promoted by Modules Wrapping Up 9. Working with Modules Exploring the Module Metadata Defining APIs in a Modular Way Targeted Linking Using jlink Wrapping Up 10. Creating Plug-ins with ServiceLoader The Plug-in Architecture Defining a Specification Module Creating a Client Module Implementing a Plug-in Implementing Additional Plug-ins Reloading the Implementations Functional Style Iteration Wrapping Up Part V. Custom Functional Pipeline Steps 11. Extending Functional Pipelines with Gatherers Why Do We Need Gatherers? Creating Custom Steps Using the gather() Method Using Built-in Gatherers Wrapping Up 12. Creating Custom Gatherers The Machinery Behind the gather() Method Flavors of Gatherers Creating Sequential Stateless Gatherers Creating Sequential Stateful Gatherers Creating Parallelizable Stateless Gatherers Creating Parallelizable Stateful Gatherers
Page
10
Wrapping Up Bibliography Copyright © 2025, The Pragmatic Bookshelf.
Page
11
Early Praise for Cruising Along with Java I love talks from Venkat. You think you might know some basics about a given topic, then he appears on stage, no shoes, no slides, and you learn something completely new and cool that you couldn’t even imagine before. Every single time. This book gives you the same experience. If you enjoy Venkat’s talks, you should definitely read this book. → Jonatan Ivanov Software Engineer, Spring Team Java has come a long way over the last thirty years and it can be overwhelming to keep up with all the changes. Once again, Venkat cuts through the confusion providing an invaluable resource for those looking for a clear and concise guide to Java’s evolution. Whether you’re new to the language or you’ve used it for years, this book will help you, your team, and your applications. → Nathaniel Schutta Technical Director, Thoughtworks The development of the Java language is presented in an easy-to-read fashion with enough details that anyone can start experimenting with the new concepts. → Isak Renström System Developer As the industry is seeing a monumental breakaway from Java 8, understanding the features introduced from JDK 9 to JDK 24 is crucial. Venkat explains new syntactical enhancements, introduces type constructs,
Page
12
describes the importance of modularity, and encourages us to appreciate what’s up and coming. If you are serious about Java and want to modernize your codebase, this book is a necessary addition to your shelf. → Daniel Hinojosa Developer/Presenter/Instructor This is an excellent book for any Java developer wanting to catch up on the evolution and latest enhancements of Java. The many easy-to-understand examples will make adoption of these new features a breeze for any developer or team. → Jack Frosch
Page
13
Acknowledgments The saying "It takes a village..." applies to writing books as much as it does to raising kids. So many generously gave their time to help make this book, and I am forever sincerely thankful to each one of them. My first thanks go to the hard-working members of the Java team, for their tireless effort to improve the language in such a meaningful way. I was truly blessed with highly knowledgeable reviewers who took the time to go through multiple drafts of this book. Many thanks to Jim Bethancourt, Don Bogardus, Alex Buckley, Jack Frosch, Daniel Hinojosa, Jonatan Ivanov, Viktor Klang, Isak Renström, Brian Sletten, and Erik Weibust for their attention to detail, suggestions, corrections, and constructive criticisms. I am truly humbled and highly inspired by Alex Buckley’s passion and genuine interest in helping me get the concepts right. He literally spent hours both on Zoom calls and over email reviewing multiple times and guiding me along. The words "thank you" are simply not adequate to express my gratitude, Alex. When I learned that Viktor Klang was involved in the implementation of the Gatherers, I was keenly interested in the topic. I have admired his technical acumen over several years, and I knew this was going to be quite an interesting and useful feature. This book gave me an opportunity to learn and appreciate him even further for his thorough review of the Gatherers
Page
14
chapters, providing valuable insights and feedback. Thank you very much, Viktor. If you have ever heard me talk about writing, you would certainly have heard me praise my editor Jackie Carter. The only thing that surpasses her ability to guide is her patience. It amazes me how she spends so much time and effort to take initial ideas and help shape them. I appreciate her prowess and am privileged to be able to continue to work with her. To say that the most amazing folks at The Pragmatic Bookshelf were very understanding and accommodating in giving me the extended time I needed for development due to the nature of this book is a gross understatement. By their actions, not mere words, they reminded me again why I so much enjoy working with them to publish my books. The idea to write this book came when I was on a hike in the mountains of Colorado. I thank my wife, Kavitha, for being a continuous source of encouragement and support ever since hearing about this on that hike. I thank those who have read the earlier drafts of this book and provided feedback and words of encouragement along the way. Thank you for your patience while watching this book evolve. Copyright © 2025, The Pragmatic Bookshelf.
Page
15
Preface Do you have a new-found love for Java? If so, you’re not alone. I once complained that Java was stagnant and its days were over. The team behind Java proved the naysayers like me wrong in the most brilliant way—by making Java a highly vibrant language. Truly, the first time I did a double take at Java was when the language introduced the functional programming ability in version 8. I even wrote a book about it: Functional Programming in Java, Second Edition [Sub23]. Every release since then has only gotten better, more interesting, and more exciting. And those who know me also know that I can’t keep my excitement quiet. The result—the book you’re reading. A number of my clients were eager to get trained on modularizing Java. They were keen to learn about the developments in the language, how to make good use of records, the concept of sealed classes, the benefits of pattern matching, and so on. Ongoing discussions and the continuous demand for such content prompted me to invest my time and effort to write in detail about the amazing capabilities of Java from version 9 onward. Thank you for reading this book. Get ready to dive deep into the features that were recently added to the Java language.
Page
16
What’s in This Book? In Chapter 1, The Evolution of Java , we start with a quick introduction. Then, we’ll group the changes in Java into these categories: Syntax Sugar: Some of the features can be classified as syntax sugar; type Inference and text blocks make us productive but have no footprint in the bytecode. These are purely compiler-level features and don’t permeate into the JVM ecosystem. These are covered in Chapter 2, Using Type Inference , and Chapter 3, Reducing Clutter with Text Blocks . Design Aid: Features such as records and sealed classes/interfaces help us with designing better object-oriented code. We’ll see in Chapter 4, Programming with Records , how records can help to better model data and in Chapter 5, Designing with Sealed Classes and Interfaces , how sealed classes can be used to better model and manage inheritance hierarchies. Fluent Expressions: No one wants to write verbose code, and no one ever enjoys maintaining them. Java has upped a notch in fluency, and we can write highly expressive code that’s less error-prone using switch as an expression—see Chapter 6, Switching to Switch Expression . We can take it further and benefit from Pattern Matching, as you’ll see in Chapter 7, Using Powerful Pattern Matching . Modularization: The JDK has been finally split into manageable pieces and we can benefit from the same techniques used in Java to modularize our own applications. In Chapter 8, Modularizing Your Java Applications , we’ll discuss the need to modularize and the steps to take. In Chapter 9, Working with Modules , we’ll look at the practical considerations of working with multiple modules. Then, in Chapter 10, Creating Plug-ins with ServiceLoader , we’ll see how to use the
Page
17
powerful ServiceLoader to dynamically discover implementations when creating plug-ins. Custom Functional Pipeline Steps: The functional programming capability of Java has a significant enhancement with the gatherers facility. In Chapter 11, Extending Functional Pipelines with Gatherers , we’ll take a look at the intent of gatherers and how to make use of the built-in gatherers in the JDK. In Chapter 12, Creating Custom Gatherers , you’ll learn how to create your own custom steps in a functional pipeline using the Gatherer interface.
Page
18
Who’s This Book For? This book is for you if you develop applications with Java and want to stay abreast of changes in the language. This book assumes you’re familiar with programming in general and with both object-oriented programming (OOP) and functional programming concepts possible in Java since version 8. You’ll benefit the most from this book if you’re a programmer using the Java language on a daily basis, a team lead, a hands-on architect, or a technical manager. As a senior developer or an architect, this book will help you consider and decide features that may be the most useful for the applications you’re in charge of designing. In addition to learning the concepts you can directly use for your enterprise applications, you can also use this book to train your team members with the latest features of the Java language.
Page
19
Java Version Used in This Book The different features you’ll learn in this book were introduced over time in different versions of Java from Java 9 onward. To be able to execute all the code in this book, you’ll need at least Java 24. Take a few minutes to download the appropriate build of the JDK for your machine and operating system. This will help you follow along with the examples in this book.
Page
20
How to Read the Code Examples When writing code in Java, we place classes in packages and executable statements and expressions in methods. To reduce clutter, we’ll skip the package names and imports in the code listings. All code in this book, except where explicitly stated, has been placed in a package using the statement: package vsca ; In case you’re wondering, the package name vsca is based on the code name we use for this book’s repository and isn’t related to any tool, product, or company. Any executable code not listed within a method is part of an undisplayed main() method. When going through the code listings, if you have an urge to look at the full source code, remember it’s only a click away at the website for this book.