Share E-Book

Java Cookbook Problems and Solutions for Java Developers (Ian F. Darwin) (z-library.sk, 1lib.sk, z-lib.sk)

Author

Rating No ratings yet

Log in to rate

Java
Language English

No Description

Format PDF
Size 4.1 MB
6
Views
(First 20 pages)

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
Ian F. Darwin Java Cookbook Problems and Solutions for Java Developers FIFTH EDITION
Page 3
978-1-098-16997-8 [LSI] Java Cookbook by Ian F. Darwin Copyright © 2025 RejmiNet Group, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (https://oreilly.com). For more information, contact our corporate/institu‐ tional sales department: 800-998-9938 or corporate@oreilly.com. Acquisitions Editor: Brian Guerin Development Editor: Angela Rufino Production Editor: Beth Kelly Copyeditor: Piper Editorial Consulting, LLC Proofreader: Kim Cofer Indexer: Potomac Indexing, LLC Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Kate Dullea June 2001: First Edition June 2004: Second Edition July 2014: Third Edition March 2020: Fourth Edition February 2025: Fifth Edition Revision History for the Fifth Edition 2025-02-06: First Release See https://oreilly.com/catalog/errata.csp?isbn=9781098169978 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Java Cookbook, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the author and do not represent the publisher’s views. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
Page 4
To everyone who cares about Java, one of the best programming languages. To my dear wife Betty. To our son Benjamin and daughter Margaret. In Memoriam to our son Andrej Cerar Darwin 1989–2014 Friend, writer, dreamer, gamer, volunteer.
Page 5
(This page has no text content)
Page 6
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. Getting Started: Compiling and Running Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.0 Introduction 1 1.1 Hello, World: Compiling and Running Java with the Standard JDK 2 1.2 Hello, World of Classless Main 21P 4 1.3 Downloading and Using the Code Examples 7 1.4 Compiling, Running, and Testing with an IDE 12 1.5 Exploring Java with JShell 11 19 1.6 Using CLASSPATH Effectively 21 1.7 Documenting Classes with Javadoc 23 1.8 Beyond Javadoc: Annotations/Metadata 30 1.9 Packaging and Running JAR Files 32 1.10 Creating a JAR That Supports Multiple Versions of Java 35 1.11 Packaging Web Tier Components into a WAR File 37 1.12 Compiling and Running Java: GraalVM for Better Performance 39 1.13 Getting Information About the Environment, OS, and Runtime 41 2. Software Development, Testing, and Maintenance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 2.0 Introduction 49 2.1 Designing Applications: Packages, Modules 49 2.2 Using the Java Modules System 52 2.3 Using JPMS to Create a Module 56 2.4 Automating Compilation, Testing, and Deployment with Apache Maven 61 2.5 Automating Compilation, Testing, and Deployment with Gradle 66 2.6 Automating Dependency Management with Maven and Gradle 68 2.7 Dealing with Deprecation Warnings 73 2.8 Batch Refactoring for Warnings and Migrations 75 2.9 Maintaining Code Correctness with Unit Testing: JUnit 77 v
Page 7
2.10 Isolating the Test Target with Mock Objects and Mockito 81 2.11 Logging: Network or Local 82 2.12 Setting Up SLF4J 84 2.13 Network Logging with Log4j 86 2.14 Network Logging with java.util.logging 91 2.15 Maintaining Your Code with Continuous Integration 95 2.16 Performance Timing 101 2.17 Creating a Custom JDK Distribution with jlink 104 2.18 Creating Platform-Specific Installers with jpackage 106 3. Strings and Things. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 3.0 Introduction 109 3.1 Taking Strings Apart with Substrings, Tokenizing, and Trimming Methods 112 3.2 String Formatting with Formatter and printf() 115 3.3 Building Strings with StringBuilder 121 3.4 Processing a String One Character at a Time 124 3.5 Aligning, Indenting, and Unindenting Strings 126 3.6 Converting Between Unicode Characters and Strings 129 3.7 Reversing a String by Word or by Character 132 3.8 Expanding and Compressing Tabs 133 3.9 Controlling Case 138 3.10 Adding Nonprintable Characters into a String 140 3.11 Creating a Message to the World with I18N Resources 141 3.12 Using a Particular Locale 143 3.13 Creating a Resource Bundle 145 3.14 Program: A Simple Text Formatter 146 4. String Matching with Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 4.0 Introduction 147 4.1 Regular Expression Syntax 149 4.2 Checking If a String Matches a Regex 156 4.3 Grouping: Specifying Parts of the Regex 160 4.4 Finding the Matching Text 162 4.5 Replacing the Matched Text 165 4.6 Printing All Occurrences of a Pattern 168 4.7 Controlling Case in Regular Expressions 171 4.8 Matching Accented, or Composite, Characters 172 4.9 Matching Newlines in Text 173 4.10 Program: Full Grep 175 5. Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 5.0 Introduction 177 5.1 Checking Whether a String Is a Valid Number 180 vi | Table of Contents
Page 8
5.2 Converting Numbers to Objects and Vice Versa 182 5.3 Taking a Fraction of an Integer Without Using Floating Point 183 5.4 Working with Floating-Point Numbers 184 5.5 Formatting Numbers 189 5.6 Converting Among Binary, Octal, Decimal, and Hexadecimal 194 5.7 Operating on a Range of Integers 195 5.8 Formatting with Correct Plurals 197 5.9 Generating Random Numbers 199 5.10 Multiplying Matrices 201 5.11 Optimizing Large Arithmetic Operations with Vector Operations 22C 203 5.12 Using Complex Numbers 207 5.13 Handling Very Large Numbers 210 5.14 Program: TempConverter 212 6. Dates and Times. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 6.0 Introduction 215 6.1 Finding Today’s Date 218 6.2 Formatting Dates and Times 220 6.3 Converting Among Dates/Times and Epoch Seconds 225 6.4 Parsing Strings into Dates 226 6.5 Difference Between Two Dates 229 6.6 Adding to or Subtracting from a Date 231 6.7 Calculating Recurring Events 232 6.8 Computing Dates Involving Time Zones 234 6.9 Interfacing with Legacy Date and Calendar Classes 235 7. Structuring Data with Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 7.0 Introduction 239 7.1 Using Arrays for Data Structuring 240 7.2 Resizing an Array 242 7.3 Simplifying Array Handling with the Arrays Class 243 7.4 The Collections Framework 246 7.5 Lists: Like an Array, but More Dynamic 247 7.6 Using Generic Types in Your Own Class: Stack Demo 252 7.7 How Shall I Iterate Thee? Let Me Enumerate the Ways 256 7.8 Avoiding Duplicate Values with a Set 259 7.9 Mapping with Hashtable and HashMap 261 7.10 Storing Strings in Properties and Preferences 263 7.11 Sorting a Collection 268 7.12 Finding an Object in a Collection 274 7.13 Converting Between Collections and Arrays 276 7.14 Making Your Own Data Structures Iterable 277 7.15 Multidimensional Structures 280 Table of Contents | vii
Page 9
8. Object-Oriented Techniques. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 8.0 Introduction 283 8.1 Object Methods: Formatting Objects with toString(), Comparing with Equals 286 8.2 Constructor Simplification: Statements Before super(…) 22P 294 8.3 Using Inner Classes 295 8.4 Simplifying Data Objects with Records (or Lombok) 297 8.5 Providing Callbacks via Interfaces 300 8.6 Polymorphism/Abstract Methods 304 8.7 Improving Interfaces with Default, Static, and Private Methods 305 8.8 Using Typesafe Enumerations 307 8.9 Using Type Pattern Matching 311 8.10 Avoiding NPEs with “Optional” 313 8.11 Controlling Subclassing with Sealed Types 17 315 8.12 Enforcing the Singleton Pattern 317 8.13 Roll Your Own Exceptions 320 8.14 Using Dependency Injection 321 8.15 Combining Java Features for Data-Oriented Programming 324 9. Functional Programming Techniques: Functional Interfaces, Streams, and Parallel Collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 9.0 Introduction 327 9.1 Using Lambdas/Closures Instead of Inner Classes 330 9.2 Using Predefined Lambda Interfaces or Rolling Your Own 335 9.3 Simplifying Processing with Streams 338 9.4 Simplifying Streams with Collectors 339 9.5 Simplifying Streams with Stream Gatherers 22P 343 9.6 Simplifying Streams with Your Own Stream Gatherer 22P 344 9.7 Improving Throughput with Parallel Streams and Collections 346 9.8 Using Existing Code as Functional with Method References 348 9.9 Java Mixins: Mixing in Methods 352 9.10 Functional Programming with Flow and Reactive Streams 354 10. Input and Output: Reading, Writing, and Directory Tricks. . . . . . . . . . . . . . . . . . . . . . . 357 10.0 Introduction 357 10.1 Discovering Filesystem Paths 360 10.2 Getting and Setting File and Directory Information: Files and Path 362 10.3 Creating and Deleting Files or Directories 373 10.4 Changing a File’s Name or Other Attributes 376 10.5 About InputStreams/OutputStreams and Readers/Writers 379 10.6 Reading and Writing Files 381 10.7 Scanning Input with StreamTokenizer, Scanner, Parsers 384 viii | Table of Contents
Page 10
10.8 Reading from the Standard Input or from the Console/Controlling Terminal 392 10.9 Copying a File 396 10.10 Reassigning the Standard Streams 397 10.11 Duplicating a Stream as It Is Written 398 10.12 Reading/Writing a Different Character Set 401 10.13 Those Pesky End-of-Line Characters 402 10.14 Beware Platform-Dependent File Code 403 10.15 Reading and Writing JAR or ZIP Archives 404 10.16 Reading Files in a Filesystem-Neutral Way with getResource() and getResourceAsStream() 409 10.17 Creating a Transient/Temporary File 411 10.18 Getting the Directory Roots 414 10.19 Using the File Watcher Service to Get Notified About File Changes 415 10.20 Walking a File Tree (like Find) 417 11. Threaded Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421 11.0 Introduction 421 11.1 Running Code in a Different Thread 423 11.2 Using Virtual Threads for Better Performance 429 11.3 Rendezvous and Timeouts 431 11.4 Synchronizing Threads with the synchronized Keyword 432 11.5 Simplifying Synchronization with Locks 436 11.6 Locking with One Writer, Many Readers 437 11.7 Sharing Data Among Threads—ThreadLocal and ScopedValue: Structuring Concurrency 440 11.8 Simplifying Producer/Consumer with the Queue Interface 444 11.9 Optimizing Parallel Processing with Fork/Join 447 11.10 Scheduling Tasks: Future Times, Background Saving in an Editor 451 12. Data Science and R. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455 12.0 Introduction 455 12.1 Using Data in Apache Spark 456 12.2 Using R Interactively 459 12.3 Comparing/Choosing an R Implementation 462 12.4 Using R from Within a Java App: Renjin 463 12.5 Using Java from Within an R Session 465 12.6 Using R in a Web App 467 13. Machine Learning/Artificial Intelligence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469 13.0 Introduction 469 13.1 Some Major AI Software 472 13.2 Using ChatGPT Directly 476 Table of Contents | ix
Page 11
13.3 Using ChatGPT via LangChain4j 479 13.4 Making an AI Service with LangChain4j 480 13.5 Conversing with Shadows 482 13.6 Generating Images with LangChain4j 484 13.7 Mixed Media Prompts: Inferences from Images with LangChain4j 486 13.8 Running AI Locally with ollama 488 14. Network Clients. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491 14.0 Introduction 491 14.1 HTTP/REST Web Client—Modern API 11 494 14.2 Contacting a Socket Server 496 14.3 Finding and Reporting Network Addresses 497 14.4 Handling Network Errors 500 14.5 Reading and Writing Textual Data 501 14.6 Reading and Writing Binary or Serialized Data 504 14.7 Postcards of the Internet: Using UDP Datagrams 507 14.8 URI, URL, or URN? 510 14.9 Program: Sockets-Based Chat Client 511 15. Server-Side Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513 15.0 Introduction 513 15.1 Opening a Server Socket for Business 514 15.2 Finding Network Interfaces 517 15.3 Returning a Response (String or Binary) 518 15.4 Handling Multiple Clients 522 15.5 Serving the HTTP Protocol 526 15.6 Securing a Web Server with TLS (formerly SSL) and JSSE 529 15.7 Creating a REST Service/Microservice with JAX-RS 532 15.8 Unix Domain Sockets—Even on Windows! 16 535 16. Processing JSON Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539 16.0 Introduction 539 16.1 Generating JSON Directly 541 16.2 Parsing and Writing JSON with Jackson 542 16.3 Parsing and Writing JSON with org.json 544 16.4 Parsing and Writing JSON with JSON-B 546 16.5 Finding JSON Elements with JSON Pointer 548 17. Reflection, or “A Class Named Class”. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551 17.0 Introduction 551 17.1 Loading and Instantiating a Class Dynamically 552 17.2 Printing Class Information 554 17.3 Getting a Class Descriptor 556 x | Table of Contents
Page 12
17.4 Finding and Using Methods and Fields 557 17.5 Invoking Class Members via MethodHandles 562 17.6 Listing Classes in a Package 563 17.7 Accessing Nested Members of Same Class 565 17.8 Accessing Private Methods and Fields via Reflection 567 17.9 Constructing a Class from Scratch with a ClassLoader 568 17.10 Constructing a Class from Scratch with JavaCompiler 570 17.11 Constructing or Modifying Class Files with the Class-File API 22P 573 17.12 Using and Defining Annotations 577 17.13 Finding Plug-In-Like Classes via Annotations 581 17.14 A Timing Program 583 17.15 Program: CrossRef 585 18. Using Java with Other Languages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587 18.0 Introduction 587 18.1 Running an External Program from Java 588 18.2 Running a Program and Capturing Its Output 592 18.3 Calling Other Languages via javax.script 596 18.4 Mixing Languages with GraalVM 21 599 18.5 Calling Between Java and Native Code with the Foreign Function and Memory API 22 601 18.6 Calling Other Languages via Native Code (JNI) 605 18.7 Calling Java from Native Code with JNI 611 Afterword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615 A. Java Then and Now. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627 Table of Contents | xi
Page 13
(This page has no text content)
Page 14
1 For the quirks, see the Java Puzzlers books by Joshua Bloch and Neal Gafter (Addison-Wesley). Preface Like any of the most-used programming languages, Java has its share of detractors, advocates, issues, quirks,1 and a learning curve. The Java Cookbook aims to help the Java developer get up to speed on some of the most important parts of Java develop‐ ment. I focus on the standard APIs and some third-party APIs, but I don’t hesitate to cover language issues as well. This is the fifth edition of this book, and it has been shaped by many people and by the myriad changes that Java has undergone over its two and a half decades of popu‐ larity. Readers interested in Java’s history can refer to Appendix A. Java 21 is the current long-term supported (LTS) version, and Java 24 is the latest cur‐ rent release at the time of publication of this edition. The current cadence of releases every six months may be great for the Java SE development team at Oracle, for devel‐ opers who want access to the latest-and-greatest, and for click-driven, Java-related news sites, but it “may cause some extra work” for Java book authors, since books typ‐ ically have a longer revision cycle than Java now does! Java 9, which came out after a previous edition of this book, was a sort-of-breaking release, the first release in a very long time to almost break backward compatibility, primarily the Java Platform Mod‐ ule System. Everything in this edition of the book can be assumed to work on Java 11 or later, unless specified otherwise (see “Icons” on page xxi). At this point in time, nobody should be using Java 8 (or anything before it) for anything. Certainly nobody should be doing new development in Java 8. If you are, it’s time to move on! While Java 11 is considered an LTS release, it is so old that you shouldn’t use it. Java 17 is the previous LTS and quite usable, but if you want the best start on an LTS Java release, begin with Java 21. xiii
Page 15
The goal of this revision of Java Cookbook is to keep the book up to date with all this change. I’ve included numerous new features, which meant I had to remove a signifi‐ cant amount of material. There are numerous additions throughout the chapters. In several places, a few recipes have been combined into one in the interest of simplicity and readability (and reducing page count). And of course I’ve updated a lot of other information along the way. Who This Book Is For I’m going to assume that you know the basics of Java. I won’t tell you how to println a string, nor how to write a class that extends another and/or implements an inter‐ face. I’ll assume you’ve taken a Java course such as Learning Tree’s Introduction (which I wrote the first version of, decades ago) or worked your way through an introductory book such as: • Head First Java by Kathy Sierra and Bert Bates (O’Reilly), a tutorial filled with visual metaphors and other brain-friendly learning techniques • Java in a Nutshell by David Flanagan (O’Reilly), a more concise book covering the standard APIs in more detail • Think Java by Allen Downey and Chris Mayfield (O’Reilly), a hands-on introduc‐ tion to computer science and programming via Java • Learning Java by Marc Loy, Patrick Niemeyer, and Daniel Leuck (O’Reilly), a book for practicing programmers moving to Java However, Chapter 1 covers some techniques that you might not know very well and that are necessary to understand some of the later material. Feel free to skip around! Both the printed version of the book and the electronic copy are heavily cross-referenced. Just to give an idea of how big a topic Java really is, have a look at Figure P-1. An earlier version of this diagram was online at Sun, prior to the Oracle takeover, with each box being a link to the corresponding documentation. Figure P-1 is my re- creation of it, using a simple Java Swing program written for the occasion. xiv | Preface
Page 16
Figure P-1. Java conceptual diagram What’s in This Book? In the early 2000s, Java seemed better suited to “development in the large,” or enter‐ prise application development, than to the few-line, one-off script in Perl, AWK, Python, or the Unix/Linux shells. That’s because it is a compiled, object-oriented lan‐ guage. However, Java has gotten better for ad hoc tasks that might previously have been done with a scripting language. JShell (Recipe 1.5) and the run-java-source-file mechanism (see “Discussion” on page 2) have helped move Java in this direction. I illustrate many techniques with shorter Java class examples and even code fragments; some of the simpler ones will be shown using JShell. All of the code examples over a few lines long are in one of my public GitHub repositories, so you can rest assured that all the code you see here has been compiled and run (most of them run recently). Preface | xv
Page 17
What’s Not in This Book Since some readers will have used previous editions (my thanks to you!), here’s a brief list of information that is no longer included. The fifth edition removed obsolete recipes from several chapters. The longer program listings at the end of many chapters were removed from the book, replaced by links to view them either from the code repository or online. The fourth edition removed the discussion of Swing GUI and AWT Graphics, though these are still used in some examples. The code for database access was also removed. The code for the former lives on in the desktop project within the javasrc repository on GitHub. For the latter, see my jpademo GitHub repo. The removed recipes have been migrated to my website. Organization of This Book Let’s go over the organization of this book. Each chapter consists of a handful of rec‐ ipes—short sections that describe a problem and its solution, along with a code example. The code in each recipe is intended to be largely self-contained; feel free to borrow bits and pieces of any of it for use in your own projects. The code is dis‐ tributed with a Berkeley-style “use with attribution” copyright. Most recipes provide reasonably complete coverage of their topic. Some topics, however, have more detail, more nuance, than can be covered in the recipe format; these end with references that the reader can consult for additional explanation and examples. I start off Chapter 1, “Getting Started: Compiling and Running Java”, by describing some methods of compiling your program on different platforms and running them in different environments (command line, IDE, and windowed desktop). This is fol‐ lowed by Chapter 2, “Software Development, Testing, and Maintenance”, which dis‐ cusses techniques for building real applications. Topics such as Java modules, build tools, unit testing, and continuous integration are discussed here. The next few chapters deal with basic APIs. Chapter 3, “Strings and Things”, concen‐ trates on one of the most basic but powerful data types in Java, showing you how to assemble, dissect, compare, and rearrange “strings,” what you might otherwise think of as ordinary text. This chapter also covers the topic of internationalization/localiza‐ tion so that your programs can work as well in Akbar, Afghanistan, Algiers, Amster‐ dam, and Angleterre as they do in Alberta, Arkansas, and Alabama. xvi | Preface
Page 18
Chapter 4, “String Matching with Regular Expressions”, teaches you how to use the powerful regular expressions technology from Unix on strings, in many string- matching and pattern-matching problem domains. Regex processing has been stan‐ dard in Java for years, but if you don’t know how to use it, you may be reinventing the flat tire. Chapter 5, “Numbers”, deals both with built-in numeric types such as int and double, as well as the corresponding API classes (Integer, Double, etc.) and the con‐ version and testing facilities they offer. There is also brief mention of the “big num‐ ber” classes. Because Java programmers often need to deal in dates and times, both locally and internationally, Chapter 6, “Dates and Times”, covers this important topic. The next chapter covers structuring your program’s data. As in most languages, arrays in Java are linear, indexed collections of similar objects, as discussed in Chapter 7, “Structuring Data with Java”. This chapter goes on to deal with the many Collections classes: powerful ways of storing quantities of objects in the java.util package, includ‐ ing the use of Java Generics. Despite some syntactic familial resemblance to procedural languages such as C, Java is at heart an object-oriented programming (OOP) language, with some important functional programming (FP) constructs skilfully blended in. Chapter 8, “Object- Oriented Techniques”, discusses some of the key notions of OOP as it applies to Java, including the commonly overridden methods of java.lang.Object and the important issue of design patterns. Java is not, and never will be, a pure FP language. However, it is possible to use some aspects of FP, increasingly so with Java 8 and its support of lambda expressions (a.k.a. closures). This is discussed in Chap‐ ter 9, “Functional Programming Techniques: Functional Interfaces, Streams, and Parallel Collections”. Chapter 10, “Input and Output: Reading, Writing, and Directory Tricks”, details the rules for reading and writing files (don’t skip this if you think files are boring; you’ll need some of this information in later chapters). The chapter also shows you every‐ thing else about files—such as finding their size and last-modified time—and about reading and modifying directories, creating temporary files, and renaming files on disk. Java was one of the first mainstream languages to provide language support for threads, the notion of multiple flows of control within a single process. Chapter 11, “Threaded Java”, tells you how to write classes that appear to do more than one thing at a time and let you take advantage of powerful multiprocessor hardware. Preface | xvii
Page 19
Big data and data science have become a thing, and Java is right in there. Chapter 12, “Data Science and R” covers some key data science software and the R language. Apache Hadoop, Apache Spark, and much more of the big data infrastructure is writ‐ ten in, and extensible with, Java. Spark is also introduced in this chapter. The R pro‐ gramming language is popular with data scientists, statisticians, and other scientists. R, like Bell Labs’ original S language it was copied from, was implemented in C/C++. At least two reimplementations of R have been written in Java, and Java can also be interfaced directly with the standard R implementation in both directions. Machine learning (ML) along with generative large language models (LLMs) are key parts of what is termed artificial intelligence (AI). AI has become a hot topic since the release of ChatGPT and its competitors and offspring. Chapter 13, “Machine Learn‐ ing/Artificial Intelligence”, talks about AI in general and then focuses on several Java libraries for applying AI. Because Java was originally promulgated as the programming language for the inter‐ net, it’s only fair to spend some time on networking in Java. Chapter 14, “Network Clients”, covers the basics of network programming from the client side, focusing on sockets. Today, so many applications need to access a web service, primarily RESTful web services, that this seemed necessary. I’ll then move to the server side in Chap‐ ter 15, “Server-Side Java”, wherein you’ll learn some server-side programming techniques. One simple text-based representation for data interchange is JSON, the JavaScript Object Notation. Chapter 16, “Processing JSON Data”, describes the format and some of the many APIs that have emerged to deal with it. Chapter 17, “Reflection, or “A Class Named Class””, lets you in on such secrets as how to write API cross-reference documents mechanically and how web servers are able to load any old servlet—even if they’ve never seen that particular class before—and run it. Sometimes you already have code written and working in another language that can do part of your work for you, or you want to use Java as part of a larger package. Chapter 18, “Using Java with Other Languages”, shows you how to run an external program (compiled or script) and also interact directly with native code in C/C++ or other languages. There isn’t room in a book this size for everything I’d like to tell you about Java. The brief Afterword presents some closing thoughts and a link to my online summary of Java APIs that every Java developer should know about. xviii | Preface
Page 20
Finally, Appendix A, “Java Then and Now”, gives the storied history of recent Java in a release-by-release timeline, so whatever version of Java you learned, you can jump in here and get up to date quickly. Versions prior to 16 have been relocated to my own website. So many topics, and so few pages! Many topics do not receive 100% coverage; I’ve tried to include the most important or most useful parts of each API. To go beyond, check the official Javadoc pages for each package; many of these pages have some brief tutorial information on how the package is to be used. Besides the parts of Java covered in this book, two other platform editions, Java Micro Edition (Java ME) and Java Enterprise Edition (Java EE), have been standardized. Java ME is concerned with small devices such as handhelds, tiny “feature phones” (not really smartphones), fax machines, and the like. At the other end of the size scale— large server machines—there’s Eclipse Jakarta EE. This is the follow-on to the former Java EE, which in the last century was briefly known as J2EE. Jakarta EE is concerned with building large, scalable, distributed applications. APIs that are part of Jakarta EE include Servlets, JavaServer Pages, JavaServer Faces, JavaMail, Contexts and Depend‐ ency Injection (CDI), JAX-RS for RESTful Web Services, JSON-P and JSON-B for processing JSON-format data, and Transactions. Jakarta EE package names originally began with “javax.” because they are not core packages, but have now moved to “jakarta.” This book mentions only a few of these. Jakarta EE Cookbook by Elder Mor‐ aes (Packt Publishing) covers some of the Jakarta EE APIs, as does the older Java Servlet and JSP Cookbook by Bruce Perry (O’Reilly). This book doesn’t cover Java ME at all. But speaking of cell phones and mobile devi‐ ces, you probably know that Android uses Java as its language, as well as Kotlin, which is a simplification and extension of Java. What should be comforting to Java developers is that Android also uses most of the core Java API, except for Swing and AWT, for which it provides Android-specific replacements. The Java developer who wants to learn Android may consider looking at my Android Cookbook (O’Reilly), or the book’s website. Java Books A lot of useful information is packed into this book. However, due to the breadth of topics, it is not possible to give book-length treatment to any one topic. Because of this, the book contains references to many websites and other books. In pointing out these references, I’m hoping to serve my target audience: the person who wants to learn more about Java. Preface | xix
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

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
← Back to List