Code with Java 21 A practical approach for building robust and efficient applications (Ploetz, Aaron) (Z-Library)
Java
No Description
378
Views
0
Downloads
0.00
Total Donations
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
(This page has no text content)
Page
2
(This page has no text content)
Page
3
Code with Java 21 A practical approach for building robust and efficient applications Aaron Ploetz
Page
4
www.bpbonline.com
Page
5
Copyright © 2024 BPB Online All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor BPB Online or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. BPB Online has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, BPB Online cannot guarantee the accuracy of this information. First published: 2024 Published by BPB Online WeWork 119 Marylebone Road London NW1 5PU UK | UAE | INDIA | SINGAPORE ISBN 978-93-55519-993 www.bpbonline.com
Page
6
Dedicated to My children: Khadiya, Avery, Emily, and Victoria & My godson: Tim The road to success is paved with the footsteps of those who did not give up and the regrets of those who did.
Page
7
About the Author Aaron Ploetz is a developer advocate at DataStax. He has been a professional software developer since 1997 and has a successful history of leading DBA and DevOps teams for both startups and Fortune 50 enterprises. He has been named an MVP for Apache Cassandra® three times, and has presented at multiple events; including the Fintech keynote at Data Day Mexico City 2023. Aaron frequently answers StackOverflow questions from other developers, and has previously authored books on distributed databases. He earned a B.S. in Management/Computer Systems from the University of Wisconsin-Whitewater, and an M.S. in Software Engineering (Database Technology emphasis) from Regis University. When not writing or coding, Aaron enjoys fishing, retro video gaming, and skijoring. Aaron and his wife, Coriene, live with their four children in the Twin Cities area.
Page
8
About the Reviewer Otavio Santana is a passionate architect and software engineer focused on cloud and Java technologies. He has deep expertise in polyglot persistence and high- performance applications in finance, social media, and e- commerce. He has contributed to the Java and the open source ecosystem in several ways. Otavio has helped in the direction and objectives of the Java platform since Java 8 as a JCP executive member, besides being a committer and leader in several open-source products and specifications. He is recognized for his open source contributions and has received many awards, including all JCP Awards categories and the Duke’s Choice Award, to name a few. Otávio is also a distinguished Java Champions and Oracle ACE program member.
Page
9
Acknowledgement I would like to recognize my co-workers, Cédrick Lunven and Mary Grygleski, who were extremely helpful and central in influencing me to get back into Java. I would also like to recognize Otavio Santana, Sharat Chander, and countless others who made the Java community so welcoming and encouraging. I would also like to thank Ursula Kellmann, who was taken from us too soon. She was an amazing mentor who taught me much about Java and was a brilliant example of what a true expert in their craft should aspire to be. Finally, I would love to acknowledge my wife, Coriene, who continually inspires me to take on new challenges and to be a better version of myself.
Page
10
Preface Learning software development has always been a treacherous path. When I began my journey, books were the only medium available. When I started learning to program BASIC on my Tandy 1000, I was first introduced to Java during my final year at the University of Wisconsin– Whitewater (1998). I loved the code once, execute everywhere message that Java trumpeted. In the 1990s, that aspect was a really big deal. In the early 2010s, I wrote a lot of Java code while working on the Mid-Tier Cassandra team at W.W. Grainger. This was my first introduction to enterprise-level Java. The database behind our service layer (Apache Cassandra®) was also written in Java, so I was quite literally thrown into the deep end of troubleshooting the exceptions and nuances of Java 7. After spending the better part of the next decade as a Cassandra DBA, I finally returned to (near) full-time Java coding in 2021. It was a breath of fresh air. I loved how much Java had evolved up through version 17. By that time, I had written two books about NoSQL databases. The more I worked with Java, the more I wanted to write a book about it. There is so much Java code running in the world today. It runs across billions of devices and powers everything from video games to e-commerce websites that generate billions of dollars. There is no denying that knowing how to code in Java has become a valuable skill.
Page
11
Today, one of the biggest obstacles for aspiring developers (aside from choosing a language) is getting a development environment installed and configured. By contrast, many of the computers that were common in the 1980s made it very easy to get started programming. Users were often only a few key presses away from getting into a software development environment. Some early home computers (like the Tandy Color Computers and Apple II series) put the user at a BASIC programming prompt immediately after booting. These early machines were asking to be programmed by default! On the other hand, modern computers (especially phones and tablets) do not. Building a suitable programming environment on modern computers is often a struggle. This is why the first chapter of this book spends time on installing and configuring the Eclipse IDE. However, making computers programmable again is more than just navigating technical obstacles. It is a culture shift. It is about looking at your device, and instead of asking, What can it do for me, it is asking, What can I build with it? It is this mindset that leads to a lifetime of learning. Ultimately, my motivation for writing this book is to help flatten the learning curve for software developers. I believe that Java is the right language to do just that. This book is structured to gradually introduce different aspects of writing code in Java, with each chapter building on lessons previously covered. Chapter 1: Getting to Know Java – This chapter provides a simple introduction to Java. It also walks through configuring a development environment, including installing tools such as a dependency manager and an IDE. This chapter also discusses object-oriented programming (OOP) and introduces new features of Java 21.
Page
12
Chapter 2: Fundamental Programming Structures – This chapter discusses some basic building blocks of Java’s syntax. It starts with the obligatory hello world program and progresses to reading input, error handling, and controlling the flow of program logic. After covering the basics, it moves on to working with files and Java-specific ways of building methods and constructors. Chapter 3: Strings, Characters, and Regular Expressions – This chapter covers different ways to work with and process text data. While starting with a simple example using ASCII character art, it progresses into showing how to use some of the more advanced methods included with the Java String class. It finishes by introducing regular expressions and showing how to use them in practical, real-world examples. Chapter 4: Arrays, Collections, and Records – This chapter introduces the reader to different structures that can be used to store data in memory. While focusing on different concepts and use cases with arrays, lists, sets, and maps, this chapter also discusses records and introduces sequenced collections (new with Java 21). Chapter 5: Arithmetic Operations – This chapter offers insight into how computers handle arithmetic at primitive levels, including the difference between integer and floating point operations. It also uses the deterministic nature of arithmetic to make a small introduction to unit testing. Chapter 6: Common Data Structures – This chapter takes the reader through the process of using Java to build data structures like stacks, queues, and different kinds of linked lists. It also walks through building a binary tree and executing simple data searches. Chapter 7: Working with Databases – This chapter shows how to build Java applications that store data in
Page
13
databases. It also introduces the PostgreSQL and Apache Cassandra® databases, showing how to build simple data models and execute common CQL and SQL commands. Chapter 8: Web Applications – This chapter discusses building restful web services and full-stack web applications in Java. It also introduces the Spring and Vaadin frameworks, showing how to leverage them to build fully-featured web applications. Chapter 9: Graphics in Java – This chapter uses an example-led approach to display graphics and animation. It also walks through building a classic arcade game in Java. Chapter 10: Final Java Project – This chapter is a culmination of many topics covered in the previous chapters and shows how to use them to build a Movie data application. Vector search is introduced as a final new topic, giving the readers a simple way to build out a movie recommendation service.
Page
14
Code Bundle and Coloured Images Please follow the link to download the Code Bundle and the Coloured Images of the book: https://rebrand.ly/nkskce0 The code bundle for the book is also hosted on GitHub at https://github.com/bpbpublications/Code-with-Java- 21. In case there's an update to the code, it will be updated on the existing GitHub repository. We have code bundles from our rich catalogue of books and videos available at https://github.com/bpbpublications. Check them out! Errata We take immense pride in our work at BPB Publications and follow best practices to ensure the accuracy of our content to provide with an indulging reading experience to our subscribers. Our readers are our mirrors, and we use their inputs to reflect and improve upon human errors, if any, that may have occurred during the publishing processes involved. To let us maintain the quality and help us reach out to any readers who might be having difficulties due to any unforeseen errors, please write to us at : errata@bpbonline.com
Page
15
Your support, suggestions and feedbacks are highly appreciated by the BPB Publications’ Family. Did you know that BPB offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.bpbonline.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at : business@bpbonline.com for more details. At www.bpbonline.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on BPB books and eBooks. Piracy If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at business@bpbonline.com with a link to the material. If you are interested in becoming an author If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit www.bpbonline.com. We have worked with thousands of developers and tech professionals, just like you, to help them share their insights with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea. Reviews Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions. We at BPB can understand what you think about our products, and our authors can see your feedback on their book. Thank you! For more information about BPB, please visit www.bpbonline.com. Join our book’s Discord space Join the book’s Discord Workspace for Latest updates, Offers, Tech happenings around the world, New Release and Sessions with the Authors:
Page
16
https://discord.bpbonline.com
Page
17
Table of Contents 1. Getting to Know Java Introduction Structure Objectives Why code with Java? Configuring your environment Operating System Java Runtime Environment Java Development Kit JDK vendors and editions Installation Windows MacOS Linux Version management Integrated Development Environment Java dependency management Source control Git installation Object-oriented programming Encapsulation Inheritance Abstraction
Page
18
Polymorphism Static polymorphism Dynamic polymorphism Advantages of OOP What is new in Java 21? Virtual threads Sequenced Collections String templates Conclusion Points to remember 2. Fundamental Programming Structures Introduction Structure Objectives Getting started Maven HelloWorld Anonymous main classes Variables and formatting Reading input Error handling If statements Switch/case statements Loops For loops While loops Do loops Files
Page
19
Writing to a file Reading from a file Reading row properties from a file Methods and constructors Conclusion Points to remember 3. Strings, Characters, and Regular Expressions Introduction Structure Objectives Characters ASCII art Strings substring toUpperCase toLowerCase String equality Equality of string suffixes Equality of string prefixes contains Regular expressions Conclusion Points to remember 4. Arrays, Collections, and Records Introduction Structure Objectives
Page
20
Arrays Multi-dimensional arrays Collections and maps Sets HashSet LinkedHashSet TreeSet ArrayList LinkedList Maps HashMap LinkedHashMap TreeMap Sequenced collections Records Building a simple example RPGSimulation class Player class Hero class RPGSimulation class continued Conclusion Points to remember 5. Arithmetic Operations Introduction Structure Objectives Integer arithmetic Addition Testing add() with JUnit
The above is a preview of the first 20 pages. Register to read the complete e-book.
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
AI guide
【One-Line Pitch】
A hands-on, project-driven guide to Java 21 that walks you from setting up your first development environment to building database-backed and web applications, ideal for beginners who want to learn by doing and for developers upgrading to modern Java features.
【Book Arc】
- **Opening (~0%–10%)**: Starts with the cultural motivation for learning to code, then dives into practical setup—installing the JDK 21, configuring Eclipse IDE, and using Maven as a dependency manager. Covers Java fundamentals like printing, variables, and basic syntax, with OS-specific instructions for Windows, macOS, and Linux.
- **Early (~10%–24%)**: Focuses on core programming structures—reading input with Scanner, control flow (switch, for loops), file I/O with FileReader/BufferedWriter, and string manipulation including regex patterns. Introduces object-oriented concepts like method overloading and constants.
- **Early (~24%–34%)**: Expands into arrays, collections, and records, including maps and sequenced collections new to Java 21. Builds a small RPG simulation to practice inheritance, polymorphism (instanceof), and constructor chaining with this(), reinforcing OOP in a fun context.
- **Middle (~34%–45%)**: Covers arithmetic operations with Java's Math library (including cube roots), then moves to data structures—implementing stacks, queues, and linked lists from scratch, with a binary tree example that demonstrates sorting through traversal.
- **Middle (~45%–52%)**: Transitions to databases, introducing the CAP theorem, then hands-on work with PostgreSQL (via ElephantSQL) and Apache Cassandra (via Astra DB). Shows how to define schemas, load/query data, and access databases from Java using prepared statements and a custom DAL (Data Access Layer).
- **Late (~52%–end)**: Concludes with web applications, building on the database layer to create full-stack Java apps. The excerpts suggest a practical capstone that ties together everything learned, though specific web framework details are not covered in the sample.
【Key Takeaways】
- **Environment setup is the first real hurdle** (Opening): The book spends significant time on installing JDK 21, Eclipse, and Maven across all major OSes, acknowledging that modern computers don't make programming easy. This practical focus removes the biggest barrier for beginners.
- **Java 21's new features are woven throughout** (Early): Sequenced collections and updated APIs are introduced alongside classic topics, so you learn modern Java without a separate "what's new" chapter. This keeps the code relevant for current production use.
- **File I/O and string handling are foundational** (Early): Using BufferedReader/FileWriter with proper flush/close patterns, plus regex for validation (like phone numbers), teaches you to handle real-world data. The System.lineSeparator() tip shows OS-aware coding.
- **OOP is taught through a mini-game** (Early): The RPG simulation with Player/Hero classes, getters/setters, and instanceof checks makes inheritance and polymorphism tangible. This is more engaging than abstract examples.
- **Data structures are built from scratch** (Middle): Instead of just using Java's collections, you implement stacks, queues, linked lists, and binary trees manually. This deepens understanding of how they work internally, which is rare in beginner books.
- **Database access uses modern patterns** (Middle): Prepared statements with one-based bind variables (noted as a Java quirk) and a custom DAL class show production-grade database coding. The CAP theorem discussion helps you choose between SQL and NoSQL.
- **The book is project-oriented, not theory-heavy** (Overall): Each chapter ends with a practical exercise (RPG, data structures, database app) that consolidates skills, making it ideal for portfolio-building.
【Reading Tips】
- **Skim the environment setup if you're experienced**: If you already have JDK 21 and an IDE, skip to Chapter 2's syntax sections. But if you're new, follow the OS-specific instructions carefully—this is where most beginners get stuck.
- **Deep-read the data structures chapter**: The manual implementations of stacks, queues, and trees are the most valuable part for understanding computer science fundamentals. Don't rush through these code examples.
- **Pay attention to Java 21-specific notes**: The book highlights new features like sequenced collections and updated APIs. If you're upgrading from older Java, these callouts are your quick reference.
- **Practice the database chapter with real services**: Sign up for free tiers of ElephantSQL and Astra DB as suggested. The hands-on experience of connecting Java to cloud databases is directly transferable to real jobs.
- **Use the RPG and database projects as templates**: These are complete enough to extend—add new features, refactor, or turn them into larger projects. That's the best way to solidify what you've learned.
【Coverage Limits】
This guide synthesizes the first ~52% of the book (through databases). The web applications chapter is mentioned but not detailed in the excerpts, so specific web framework coverage (e.g., Spring, Jakarta EE) is not included here.
Passage locations
Excerpt 1
Databases Introduction Structure Introduction to databases Short history of databases CAP theorem Consistency Availability Partition tolerance CAP designatio...
View in text
Excerpt 2
that we define will help us convert between meters and feet. As METERS_PER_FOOT is a decimal value, we will need to put a d character at the end for it to be...
View in text
Excerpt 3
uss linked lists in further detail in a later chapter. Maps One of the more unique collection types is maps. Maps are useful for storing small amounts of key...
View in text
Excerpt 4
implement our LinkedList. To be consistent with our earlier example, in Chapter 4, Arrays, Collections, and Records, we will use the same data elements (fict...
View in text
Recommended for You
{{#thumbnailUrl}}
{{/thumbnailUrl}}
{{^thumbnailUrl}}
{{/thumbnailUrl}}
Loading recommended books...
Failed to load, please try again later
Tip the Site
Scan the WeChat Pay or Alipay code to tip. No login required.
WeChat Pay
Alipay