Java Cookbook, 4th Edition

Book description

Java continues to grow and evolve, and this cookbook continues to evolve in tandem. With this guide, you’ll get up to speed right away with hundreds of hands-on recipes across a broad range of Java topics. You’ll learn useful techniques for everything from string handling and functional programming to network communication.

Each recipe includes self-contained code solutions that you can freely use, along with a discussion of how and why they work. If you’re familiar with Java basics, this cookbook will bolster your knowledge of the language and its many recent changes, including how to apply them in your day-to-day development. This updated edition covers changes through Java 12 and parts of 13 and 14.

Recipes include:

  • Methods for compiling, running, and debugging
  • Packaging Java classes and building applications
  • Manipulating, comparing, and rearranging text
  • Regular expressions for string and pattern matching
  • Handling numbers, dates, and times
  • Structuring data with collections, arrays, and other types
  • Object-oriented and functional programming techniques
  • Input/output, directory, and filesystem operations
  • Network programming on both client and server
  • Processing JSON for data interchange
  • Multithreading and concurrency
  • Using Java in big data applications
  • Interfacing Java with other languages

Publisher resources

View/Submit Errata

Table of contents

  1. Preface
    1. Who This Book Is For
    2. What’s in This Book?
    3. Java Books
    4. Conventions Used in This Book
    5. O’Reilly Online Learning
    6. Comments and Questions
    7. Acknowledgments
  2. 1. Getting Started: Compiling and Running Java
    1. 1.0. Introduction
    2. 1.1. Compiling and Running Java: Standard JDK
    3. 1.2. Compiling and Running Java: GraalVM for Better Performance
    4. 1.3. Compiling, Running, and Testing with an IDE
    5. 1.4. Exploring Java with JShell
    6. 1.5. Using CLASSPATH Effectively
    7. 1.6. Downloading and Using the Code Examples
    8. 1.7. Automating Dependencies, Compilation, Testing, and Deployment with Apache Maven
    9. 1.8. Automating Dependencies, Compilation, Testing, and Deployment with Gradle
    10. 1.9. Dealing with Deprecation Warnings
    11. 1.10. Maintaining Code Correctness with Unit Testing: JUnit
    12. 1.11. Maintaining Your Code with Continuous Integration
    13. 1.12. Getting Readable Stack Traces
    14. 1.13. Finding More Java Source Code
    15. 1.14. Finding Runnable Java Libraries
  3. 2. Interacting with the Environment
    1. 2.0. Introduction
    2. 2.1. Getting Environment Variables
    3. 2.2. Getting Information from System Properties
    4. 2.3. Dealing with Code That Depends on the Java Version or the Operating System
    5. 2.4. Using Extensions or Other Packaged APIs
    6. 2.5. Using the Java Modules System
  4. 3. Strings and Things
    1. 3.0. Introduction
    2. 3.1. Taking Strings Apart with Substrings or Tokenizing
    3. 3.2. Putting Strings Together with StringBuilder
    4. 3.3. Processing a String One Character at a Time
    5. 3.4. Aligning, Indenting, and Unindenting Strings
    6. 3.5. Converting Between Unicode Characters and Strings
    7. 3.6. Reversing a String by Word or by Character
    8. 3.7. Expanding and Compressing Tabs
    9. 3.8. Controlling Case
    10. 3.9. Entering Nonprintable Characters
    11. 3.10. Trimming Blanks from the End of a String
    12. 3.11. Creating a Message 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
    16. 3.15. Program: Soundex Name Comparisons
  5. 4. Pattern Matching with Regular Expressions
    1. 4.0. Introduction
    2. 4.1. Regular Expression Syntax
    3. 4.2. Using Regexes in Java: Test for a Pattern
    4. 4.3. Finding the Matching Text
    5. 4.4. Replacing the Matched Text
    6. 4.5. Printing All Occurrences of a Pattern
    7. 4.6. Printing Lines Containing 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: Apache Logfile Parsing
    12. 4.11. 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 Series of Integers
    9. 5.8. Formatting with Correct Plurals
    10. 5.9. Generating Random Numbers
    11. 5.10. Multiplying Matrices
    12. 5.11. Using Complex Numbers
    13. 5.12. Handling Very Large Numbers
    14. 5.13. Program: TempConverter
    15. 5.14. Program: Number Palindromes
  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, YMDHMS, 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. Handling 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. The Collections Framework
    5. 7.4. Like an Array, but More Dynamic
    6. 7.5. Using Generic Types in Your Own Class
    7. 7.6. How Shall I Iterate Thee? Let Me Enumerate the Ways
    8. 7.7. Eschewing Duplicates with a Set
    9. 7.8. Structuring Data in a Linked List
    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. Avoiding the Urge to Sort
    14. 7.13. Finding an Object in a Collection
    15. 7.14. Converting a Collection to an Array
    16. 7.15. Making Your Data Iterable
    17. 7.16. Using a Stack of Objects
    18. 7.17. Multidimensional Structures
    19. 7.18. Simplifying Data Objects with Lombok or Record
    20. 7.19. Program: Timing Comparisons
  9. 8. Object-Oriented Techniques
    1. 8.0. Introduction
    2. 8.1. Object Methods: Formatting Objects with toString(), Comparing with Equals
    3. 8.2. Using Inner Classes
    4. 8.3. Providing Callbacks via Interfaces
    5. 8.4. Polymorphism/Abstract Methods
    6. 8.5. Using Typesafe Enumerations
    7. 8.6. Avoiding NPEs with Optional
    8. 8.7. Enforcing the Singleton Pattern
    9. 8.8. Roll Your Own Exceptions
    10. 8.9. Using Dependency Injection
    11. 8.10. Program: Plotter
  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 Instead of Your Own
    4. 9.3. Simplifying Processing with Streams
    5. 9.4. Simplifying Streams with Collectors
    6. 9.5. Improving Throughput with Parallel Streams and Collections
    7. 9.6. Using Existing Code as Functional with Method References
    8. 9.7. Java Mixins: Mixing in Methods
  11. 10. Input and Output: Reading, Writing, and Directory Tricks
    1. 10.0. Introduction
    2. 10.1. About InputStreams/OutputStreams and Readers/Writers
    3. 10.2. Reading a Text File
    4. 10.3. Reading from the Standard Input or from the Console/Controlling Terminal
    5. 10.4. Printing with Formatter and printf
    6. 10.5. Scanning Input with StreamTokenizer
    7. 10.6. Scanning Input with the Scanner Class
    8. 10.7. Scanning Input with Grammatical Structure
    9. 10.8. Copying a File
    10. 10.9. Reassigning the Standard Streams
    11. 10.10. Duplicating a Stream as It Is Written; Reassigning Standard Streams
    12. 10.11. Reading/Writing a Different Character Set
    13. 10.12. Those Pesky End-of-Line Characters
    14. 10.13. Beware Platform-Dependent File Code
    15. 10.14. Reading/Writing Binary Data
    16. 10.15. Reading and Writing JAR or ZIP Archives
    17. 10.16. Finding Files in a Filesystem-Neutral Way with getResource() and getResourceAsStream()
    18. 10.17. Getting File Information: Files and Path
    19. 10.18. Creating a New File or Directory
    20. 10.19. Changing a File’s Name or Other Attributes
    21. 10.20. Deleting a File
    22. 10.21. Creating a Transient/Temporary File
    23. 10.22. Listing a Directory
    24. 10.23. Getting the Directory Roots
    25. 10.24. Using the FileWatcher Service to Get Notified About File Changes
    26. 10.25. Program: Save User Data to Disk
    27. 10.26. Program: Find—Walking a File Tree
  12. 11. Data Science and R
    1. 11.1. Machine Learning with Java
    2. 11.2. Using Data In Apache Spark
    3. 11.3. Using R Interactively
    4. 11.4. Comparing/Choosing an R Implementation
    5. 11.5. Using R from Within a Java App: Renjin
    6. 11.6. Using Java from Within an R Session
    7. 11.7. Using FastR, the GraalVM Implementation of R
    8. 11.8. Using R in a Web App
  13. 12. Network Clients
    1. 12.0. Introduction
    2. 12.1. HTTP/REST Web Client
    3. 12.2. Contacting a Socket Server
    4. 12.3. Finding and Reporting Network Addresses
    5. 12.4. Handling Network Errors
    6. 12.5. Reading and Writing Textual Data
    7. 12.6. Reading and Writing Binary or Serialized Data
    8. 12.7. UDP Datagrams
    9. 12.8. URI, URL, or URN?
    10. 12.9. Program: TFTP UDP Client
    11. 12.10. Program: Sockets-Based Chat Client
    12. 12.11. Program: Simple HTTP Link Checker
  14. 13. Server-Side Java
    1. 13.0. Introduction
    2. 13.1. Opening a Server Socket for Business
    3. 13.2. Finding Network Interfaces
    4. 13.3. Returning a Response (String or Binary)
    5. 13.4. Returning Object Information Across a Network Connection
    6. 13.5. Handling Multiple Clients
    7. 13.6. Serving the HTTP Protocol
    8. 13.7. Securing a Web Server with SSL and JSSE
    9. 13.8. Creating a REST Service with JAX-RS
    10. 13.9. Network Logging
    11. 13.10. Setting Up SLF4J
    12. 13.11. Network Logging with Log4j
    13. 13.12. Network Logging with java.util.logging
  15. 14. Processing JSON Data
    1. 14.0. Introduction
    2. 14.1. Generating JSON Directly
    3. 14.2. Parsing and Writing JSON with Jackson
    4. 14.3. Parsing and Writing JSON with org.json
    5. 14.4. Parsing and Writing JSON with JSON-B
    6. 14.5. Finding JSON Elements with JSON Pointer
  16. 15. Packages and Packaging
    1. 15.0. Introduction
    2. 15.1. Creating a Package
    3. 15.2. Documenting Classes with Javadoc
    4. 15.3. Beyond Javadoc: Annotations/Metadata
    5. 15.4. Preparing a Class as a JavaBean
    6. 15.5. Archiving with JAR
    7. 15.6. Running a Program from a JAR
    8. 15.7. Packaging Web Tier Components into a WAR File
    9. 15.8. Creating a Smaller Distribution with jlink
    10. 15.9. Using JPMS to Create a Module
  17. 16. Threaded Java
    1. 16.0. Introduction
    2. 16.1. Running Code in a Different Thread
    3. 16.2. Displaying a Moving Image with Animation
    4. 16.3. Stopping a Thread
    5. 16.4. Rendezvous and Timeouts
    6. 16.5. Synchronizing Threads with the synchronized Keyword
    7. 16.6. Simplifying Synchronization with Locks
    8. 16.7. Simplifying Producer/Consumer with the Queue Interface
    9. 16.8. Optimizing Parallel Processing with Fork/Join
    10. 16.9. Scheduling Tasks: Future Times, Background Saving in an Editor
  18. 17. Reflection, or “A Class Named Class”
    1. 17.0. Introduction
    2. 17.1. Getting a Class Descriptor
    3. 17.2. Finding and Using Methods and Fields
    4. 17.3. Accessing Private Methods and Fields via Reflection
    5. 17.4. Loading and Instantiating a Class Dynamically
    6. 17.5. Constructing a Class from Scratch with a ClassLoader
    7. 17.6. Constructing a Class from Scratch with JavaCompiler
    8. 17.7. Performance Timing
    9. 17.8. Printing Class Information
    10. 17.9. Listing Classes in a Package
    11. 17.10. Using and Defining Annotations
    12. 17.11. Finding Plug-In-Like Classes via Annotations
    13. 17.12. 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. Marrying Java and Perl
    7. 18.6. Calling Other Languages via Native Code
    8. 18.7. Calling Java from Native Code
  20. Afterword
  21. Java Then and Now
    1. Introduction: Always in Motion the Java Is
    2. What Was New in Java 8
    3. What Was New in Java 9
    4. What Was New in Java 10 (March 2018)
    5. What Was New in Java 11 (September 2018)
    6. What Was New in Java 12 (March 2019)
    7. What Is New in Java 13 (September 2019)
    8. Looking Ahead
  22. Index
  23. About the Author

Product information

  • Title: Java Cookbook, 4th Edition
  • Author(s): Ian F. Darwin
  • Release date: March 2020
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781492072584