Java Cookbook, 5th Edition

Book description

As Java continues to evolve, this cookbook continues to grow in tandem with hundreds of hands-on recipes across a broad range of Java topics. Author Ian Darwin gets developers up to speed right away with useful techniques for everything from string handling and functional programming to network communication and AI.

If you're familiar with any release of Java, this book will bolster your knowledge of the language and its many recent changes, including how to apply them in your day-to-day development. Each recipe includes self-contained code solutions that you can freely use, along with a discussion of how and why they work.

Downloadable from GitHub, all code examples compile successfully. This updated edition covers changes up to and including Java 21. You will:

  • Learn how to apply many new and old Java APIs
  • Use the new language features in recent Java versions
  • Understand the code you're maintaining
  • Develop code using standard APIs and good practices
  • Explore the brave new world of current Java development

Ian Darwin has a lifetime of experience in the software industry, having worked with Java across many platforms and types of software, from Java's initial pre-release to the present, from desktop to enterprise to mobile.

Publisher resources

View/Submit Errata

Table of contents

  1. Preface
    1. Who This Book Is For
    2. What’s in This Book?
    3. What’s Not in this book
    4. Organization of This Book
    5. Java Books
    6. Conventions Used in This Book
    7. Code Examples
    8. O’Reilly Online Learning
    9. Comments and Questions
    10. Acknowledgments
  2. 1. Getting Started: Compiling and Running Java
    1. 1.0. Introduction
    2. 1.1. Hello World: Compiling and Running Java with the Standard JDK
    3. 1.2. Hello World of Classless Main
    4. 1.3. Downloading and Using the Code Examples
    5. 1.4. Compiling, Running, and Testing with an IDE
    6. 1.5. Exploring Java with JShell
    7. 1.6. Using CLASSPATH Effectively
    8. 1.7. Documenting Classes with Javadoc
    9. 1.8. Beyond Javadoc: Annotations/Metadata
    10. 1.9. Packaging and Running JAR Files
    11. 1.10. Creating a JAR that supports multiple versions of Java
    12. 1.11. Packaging Web Tier Components into a WAR File
    13. 1.12. Compiling and Running Java: GraalVM for Better Performance
    14. 1.13. Getting Information About the Environment, OS, and Runtime
  3. 2. Software Development, Testing, and Maintenance
    1. 2.0. Introduction
    2. 2.1. Designing Applications: Packages, Modules
    3. 2.2. Using the Java Modules System
    4. 2.3. Using JPMS to Create a Module
    5. 2.4. Automating Compilation, Testing, and Deployment with Apache Maven
    6. 2.5. Automating Compilation, Testing, and Deployment with Gradle
    7. 2.6. Automating Dependency Management With Maven and Gradle
    8. 2.7. Dealing with Deprecation Warnings
    9. 2.8. Batch Refactoring for Warnings and Migrations
    10. 2.9. Maintaining Code Correctness with Unit Testing: JUnit
    11. 2.10. Isolating the Test Target with Mock Objects and Mockito
    12. 2.11. Logging: Network or Local
    13. 2.12. Setting Up SLF4J
    14. 2.13. Network Logging with Log4j
    15. 2.14. Network Logging with java.util.logging
    16. 2.15. Maintaining Your Code with Continuous Integration
    17. 2.16. Performance Timing
    18. 2.17. Creating a Custom JDK Distribution with jlink
    19. 2.18. Creating Platform-specific Installers with jpackage
  4. 3. Strings and Things
    1. 3.0. Introduction
    2. 3.1. Taking Strings Apart with Substrings, Tokenizing, and Trimming Methods
    3. 3.2. String Formatting with Formatter and printf()
    4. 3.3. Building Strings with StringBuilder
    5. 3.4. Processing a String One Character at a Time
    6. 3.5. Aligning, Indenting, and Unindenting Strings
    7. 3.6. Converting Between Unicode Characters and Strings
    8. 3.7. Reversing a String by Word or by Character
    9. 3.8. Expanding and Compressing Tabs
    10. 3.9. Controlling Case
    11. 3.10. Adding Nonprintable Characters into a String
    12. 3.11. Creating a Message to the World with I18N Resources
    13. 3.12. Using a Particular Locale
    14. 3.13. Creating a Resource Bundle
    15. 3.14. Program: A Simple Text Formatter
  5. 4. String Matching with Regular Expressions
    1. 4.0. Introduction
    2. 4.1. Regular Expression Syntax
    3. 4.2. Checking if a String matches a Regex
    4. 4.3. Grouping: Specifying Parts of the Regex.
    5. 4.4. Finding the Matching Text
    6. 4.5. Replacing the Matched Text
    7. 4.6. Printing All Occurrences of a Pattern
    8. 4.7. Controlling Case in Regular Expressions
    9. 4.8. Matching Accented, or Composite, Characters
    10. 4.9. Matching Newlines in Text
    11. 4.10. Program: Full Grep
  6. 5. Numbers
    1. 5.0. Introduction
    2. 5.1. Checking Whether a String Is a Valid Number
    3. 5.2. Converting Numbers to Objects and Vice Versa
    4. 5.3. Taking a Fraction of an Integer Without Using Floating Point
    5. 5.4. Working with Floating-Point Numbers
    6. 5.5. Formatting Numbers
    7. 5.6. Converting Among Binary, Octal, Decimal, and Hexadecimal
    8. 5.7. Operating on a Range of Integers
    9. 5.8. Formatting with Correct Plurals
    10. 5.9. Generating Random Numbers
    11. 5.10. Multiplying Matrices
    12. 5.11. Optimizing Large Arithmetic Operations with Vector Operations
    13. 5.12. Using Complex Numbers
    14. 5.13. Handling Very Large Numbers
    15. 5.14. Program: TempConverter
  7. 6. Dates and Times
    1. 6.0. Introduction
    2. 6.1. Finding Today’s Date
    3. 6.2. Formatting Dates and Times
    4. 6.3. Converting Among Dates/Times and Epoch Seconds
    5. 6.4. Parsing Strings into Dates
    6. 6.5. Difference Between Two Dates
    7. 6.6. Adding to or Subtracting from a Date
    8. 6.7. Calculating Recurring Events
    9. 6.8. Computing Dates Involving Time Zones
    10. 6.9. Interfacing with Legacy Date and Calendar Classes
  8. 7. Structuring Data with Java
    1. 7.0. Introduction
    2. 7.1. Using Arrays for Data Structuring
    3. 7.2. Resizing an Array
    4. 7.3. Simplifying Array Handling with the Arrays class
    5. 7.4. The Collections Framework
    6. 7.5. Lists: Like an Array, but More Dynamic
    7. 7.6. Using Generic Types in Your Own Class: Stack Demo
    8. 7.7. How Shall I Iterate Thee? Let Me Enumerate the Ways
    9. 7.8. Avoiding Duplicate Values with a Set
    10. 7.9. Mapping with Hashtable and HashMap
    11. 7.10. Storing Strings in Properties and Preferences
    12. 7.11. Sorting a Collection
    13. 7.12. Finding an Object in a Collection
    14. 7.13. Converting Between Collections and Arrays
    15. 7.14. Making Your Own Data Structures Iterable
    16. 7.15. Multidimensional Structures
  9. 8. Object-Oriented Techniques
    1. 8.0. Introduction
    2. 8.1. Object Methods: Formatting Objects with toString(), Comparing with Equals
    3. 8.2. Constructor Simplification: Statements before super(…​)
    4. 8.3. Using Inner Classes
    5. 8.4. Simplifying Data Objects with Records (or Lombok)
    6. 8.5. Providing Callbacks via Interfaces
    7. 8.6. Polymorphism/Abstract Methods
    8. 8.7. Improving Interfaces with Default, Static and Private Methods
    9. 8.8. Using Typesafe Enumerations
    10. 8.9. Using Type Pattern Matching
    11. 8.10. Avoiding NPEs with Optional
    12. 8.11. Controlling Subclassing with Sealed Types
    13. 8.12. Enforcing the Singleton Pattern
    14. 8.13. Roll Your Own Exceptions
    15. 8.14. Using Dependency Injection
    16. 8.15. Combining Java Features for Data Oriented Programming (DOP)
  10. 9. Functional Programming Techniques: Functional Interfaces, Streams, and Parallel Collections
    1. 9.0. Introduction
    2. 9.1. Using Lambdas/Closures Instead of Inner Classes
    3. 9.2. Using Predefined Lambda Interfaces Or Rolling Your Own
    4. 9.3. Simplifying Processing with Streams
    5. 9.4. Simplifying Streams with Collectors
    6. 9.5. Simplifying Streams with Stream Gatherers
    7. 9.6. Simplifying Streams with Your Own Stream Gatherer
    8. 9.7. Improving Throughput with Parallel Streams and Collections
    9. 9.8. Using Existing Code as Functional with Method References
    10. 9.9. Java Mixins: Mixing in Methods
    11. 9.10. Functional Programming with Flow and Reactive Streams
  11. 10. Input and Output: Reading, Writing, and Directory Tricks
    1. 10.0. Introduction
    2. 10.1. Discovering Filesystem Paths
    3. 10.2. Getting and Setting File and Directory Information: Files and Path
    4. 10.3. Creating And Deleting Files or Directories
    5. 10.4. Changing a File’s Name or Other Attributes
    6. 10.5. About InputStreams/OutputStreams and Readers/Writers
    7. 10.6. Reading and Writing Files
    8. 10.7. Scanning Input with StreamTokenizer, Scanner, Parsers
    9. 10.8. Reading from the Standard Input or from the Console/Controlling Terminal
    10. 10.9. Copying a File
    11. 10.10. Reassigning the Standard Streams
    12. 10.11. Duplicating a Stream as It Is Written
    13. 10.12. Reading/Writing a Different Character Set
    14. 10.13. Those Pesky End-of-Line Characters
    15. 10.14. Beware Platform-Dependent File Code
    16. 10.15. Reading and Writing JAR or ZIP Archives
    17. 10.16. Reading Files in a Filesystem-Neutral Way with getResource() and getResourceAsStream()
    18. 10.17. Creating a Transient/Temporary File
    19. 10.18. Getting the Directory Roots
    20. 10.19. Using the File Watcher Service to Get Notified About File Changes
    21. 10.20. Walking a File Tree (like find)
  12. 11. Threaded Java
    1. 11.0. Introduction
    2. 11.1. Running Code in a Different Thread
    3. 11.2. Using Virtual Threads for Better Performance
    4. 11.3. Rendezvous and Timeouts
    5. 11.4. Synchronizing Threads with the synchronized Keyword
    6. 11.5. Simplifying Synchronization with Locks
    7. 11.6. Locking with One Writer, Many Readers
    8. 11.7. Sharing Data Among Threads: ThreadLocal and ScopedValue: Structuring Concurrency
    9. 11.8. Simplifying Producer/Consumer with the Queue Interface
    10. 11.9. Optimizing Parallel Processing with Fork/Join
    11. 11.10. Scheduling Tasks: Future Times, Background Saving in an Editor
  13. 12. Data Science and R
    1. 12.1. Using Data In Apache Spark
    2. 12.2. Using R Interactively
    3. 12.3. Comparing/Choosing an R Implementation
    4. 12.4. Using R from Within a Java App: Renjin
    5. 12.5. Using Java from Within an R Session
    6. 12.6. Using R in a Web App
  14. 13. Machine Learning / Artificial Intelligence
    1. 13.1. Some Major AI Software
    2. 13.2. Using ChatGPT Directly
    3. 13.3. Using ChatGPT via LangChain4J
    4. 13.4. Making an AI Service with LangChain4J
    5. 13.5. Conversing with shadows
    6. 13.6. Generating Images with LangChain4J
    7. 13.7. Mixed Media Prompts: Inferences from Images with LangChain4J
    8. 13.8. Running AI Locally with ollama
    9. 13.9. See Also
  15. 14. Network Clients
    1. 14.0. Introduction
    2. 14.1. HTTP/REST Web Client - Modern API
    3. 14.2. Contacting a Socket Server
    4. 14.3. Finding and Reporting Network Addresses
    5. 14.4. Handling Network Errors
    6. 14.5. Reading and Writing Textual Data
    7. 14.6. Reading and Writing Binary or Serialized Data
    8. 14.7. Postcards of the Internet: Using UDP Datagrams
    9. 14.8. URI, URL, or URN?
    10. 14.9. Program: Sockets-Based Chat Client
  16. 15. Server-Side Java
    1. 15.0. Introduction
    2. 15.1. Opening a Server Socket for Business
    3. 15.2. Finding Network Interfaces
    4. 15.3. Returning a Response (String or Binary)
    5. 15.4. Handling Multiple Clients
    6. 15.5. Serving the HTTP Protocol
    7. 15.6. Securing a Web Server with TLS (formerly SSL) and JSSE
    8. 15.7. Creating a REST Service/Microservice with JAX-RS
    9. 15.8. Unix Domain Sockets - even on Windows!
  17. 16. Processing JSON Data
    1. 16.0. Introduction
    2. 16.1. Generating JSON Directly
    3. 16.2. Parsing and Writing JSON with Jackson
    4. 16.3. Parsing and Writing JSON with org.json
    5. 16.4. Parsing and Writing JSON with JSON-B
    6. 16.5. Finding JSON Elements with JSON Pointer
  18. 17. Reflection, or “A Class Named Class”
    1. 17.0. Introduction
    2. 17.1. Loading and Instantiating a Class Dynamically
    3. 17.2. Printing Class Information
    4. 17.3. Getting a Class Descriptor
    5. 17.4. Finding and Using Methods and Fields
    6. 17.5. Invoking Class Members Via MethodHandles
    7. 17.6. Listing Classes in a Package
    8. 17.7. Accessing Nested Members of Same Class
    9. 17.8. Accessing Private Methods and Fields via Reflection
    10. 17.9. Constructing a Class from Scratch with a ClassLoader
    11. 17.10. Constructing a Class from Scratch with JavaCompiler
    12. 17.11. Constructing or Modifying Class Files with the java.lang.classfile API
    13. 17.12. Using and Defining Annotations
    14. 17.13. Finding Plug-In-Like Classes via Annotations
    15. 17.14. A timing program
    16. 17.15. Program: CrossRef
  19. 18. Using Java with Other Languages
    1. 18.0. Introduction
    2. 18.1. Running an External Program from Java
    3. 18.2. Running a Program and Capturing Its Output
    4. 18.3. Calling Other Languages via javax.script
    5. 18.4. Mixing Languages with GraalVM
    6. 18.5. Calling between Java and Native Code with the Foreign Function & Memory API
    7. 18.6. Calling Other Languages via Native Code (JNI)
    8. 18.7. Calling Java from Native Code with JNI
  20. Afterword
  21. Java Then and Now
    1. Introduction: Always in Motion the Java Is
    2. What Was New in Java 16
    3. What Was New in Java 17 LTS
    4. What Was New in Java 18
    5. What Was New in Java 19
    6. What Was New in Java 20
    7. What Was New in Java 21 LTS
    8. What Was New in Java 22
    9. What’s New in Java 23
    10. What’s New in Java 24
    11. Looking Ahead
  22. Index
  23. About the Author

Product information

  • Title: Java Cookbook, 5th Edition
  • Author(s): Ian F. Darwin
  • Release date: February 2025
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781098169978