Statistics
78
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2025-11-19

AuthorBenjamin Evans, Jason Clark, David Flanagan

This updated edition of the Nutshell guide not only helps experienced Java programmers get the most out of versions through Java 17, it also serves as a learning path for new developers. Chock-full of examples that demonstrate how to take complete advantage of modern Java APIs and development best practices, this thoroughly revised book includes new material on recent enhancements to the Java object model that every developer should know about. The first section provides a fast-paced, no-fluff introduction to the Java programming language and the core runtime aspects of the Java platform. The second section is a reference to core concepts and APIs that explains how to perform real programming work in the Java environment. • Get up to speed on language details through Java 17 • Learn object-oriented programming using basic Java syntax • Explore generics, enumerations, annotations, and lambda expressions • Understand techniques used in object-oriented design • Examine how concurrency and memory are intertwined • Work with Java collections and handle common data formats • Delve into Java's latest I/O APIs including asynchronous channels • Become familiar with development tools in OpenJDK

Tags
No tags
ISBN: 1098131002
Publisher: O'Reilly Media
Publish Year: 2023
Language: 英文
Pages: 482
File Format: PDF
File Size: 3.3 MB
Support Statistics
¥.00 · 0times
Text Preview (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.

Benjamin J. Evans, Jason Clark & David Flanagan Java in a Nutshell A Desktop Quick Reference 8th Edition Covers Java 17
JAVA Java in a Nutshell The updated edition of this Nutshell guide helps experienced Java programmers get the most out of versions through Java 17 and serves as a learning path for new developers. Chock-full of examples that demonstrate how to take complete advantage of modern Java APIs and development best practices, this thoroughly revised book includes new material on recent enhancements to the Java object model that every developer should know. The first section provides a fast-paced, no-fluff introduction to the Java programming language and the core runtime aspects of the Java platform. The second section is a core concept and API reference that explains how to perform real programming work with Java. • Get up to speed on language and core library details through Java 17 • Learn Java’s syntax and model for object-oriented programming • Explore generics, enumerations, annotations, and lambda expressions • Examine how concurrency and memory are intertwined • Delve into Java’s latest I/O APIs, including asynchronous channels • Become familiar with development tools in OpenJDK Twitter: @oreillymedia linkedin.com/company/oreilly-media youtube.com/oreillymedia Ben Evans is a Java Champion and senior principal software engineer at Red Hat. Cofounder of jClarity, he’s also served as lead architect for instrumentation at New Relic. Jason Clark, a principal engineer and architect at New Relic, has worked on everything from petabyte-scale JVM data processing pipelines to Ruby instrumentation libraries. David Flanagan is a computer programmer who spends most of his time writing about JavaScript and Java. He’s also the author of JavaScript: The Definitive Guide. “This is a must-have book for developers to get a clear picture of how Java works and how it has evolved over the years.” —Achyut Madhusudan Software Developer at Red Hat US $65.99 CAN $82.99 ISBN: 978-1-098-13100-5
JAVA IN A NUTSHELL A Desktop Quick Reference Eighth Edition Benjamin J. Evans, Jason Clark, and David Flanagan
978-1-098-13100-5 [LSI] Java in a Nutshell, Eighth Edition by Benjamin J. Evans, Jason Clark, and David Flanagan Copyright © 2023 Benjamin J. Evans and Jason Clark. 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 (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Acquisitions Editors: Brian Guerin and Zan McQuade Development Editor: Melissa Potter Production Editor: Ashley Stussy Copyeditor: Piper Editorial Consulting, LLC Proofreader: Amnet Systems, LLC Indexer: WordCo Indexing Services, Inc. Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Kate Dullea February 2023: Eighth Edition Revision History for the Eighth Edition 2023-02-14: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781098131005 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Java in a Nutshell, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the authors, and do not represent the publisher’s views. While the publisher and the authors have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the authors 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.
This book is dedicated to all who teach peace and resist violence.
(This page has no text content)
Table of Contents Foreword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi Part I. Introducing Java 1. Introduction to the Java Environment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 The Language, the JVM, and the Ecosystem 3 Comparing Java to Other Languages 11 Answering Some Criticisms of Java 12 A Brief History of Java and the JVM 16 Summary 18 2. Java Syntax from the Ground Up. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Java Programs from the Top Down 20 Lexical Structure 20 Primitive Data Types 25 Expressions and Operators 34 Statements 52 Methods 74 Introduction to Classes and Objects 81 Arrays 86 Reference Types 94 Packages and the Java Namespace 98 Java Source File Structure 103 Defining and Running Java Programs 104 Summary 105 v
3. Object-Oriented Programming in Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Overview of Classes and Records 107 Fields and Methods 111 Creating and Initializing Objects 117 Subclasses and Inheritance 122 Data Hiding and Encapsulation 135 Abstract Classes and Methods 143 Modifier Summary 148 Summary 150 4. The Java Type System. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 Interfaces 152 Java Generics 162 Enums and Annotations 175 Lambda Expressions 180 Nested Types 187 Describing the Java Type System 198 Summary 201 5. Introduction to Object-Oriented Design in Java. . . . . . . . . . . . . . . . . . . . . . . 205 Java Values 205 Important Common Methods 207 Constants 212 Working with Fields 212 Field Inheritance and Accessors 213 Singleton 215 Factory Methods 217 Builders 218 Interfaces Versus Abstract Classes 220 Do Default Methods Change Java’s Inheritance Model? 222 OOD Using Lambdas 223 OOD Using Sealed Types 225 OOD Using Records 227 Instance Methods or Class Methods? 228 Composition Versus Inheritance 230 Exceptions and Exception Handling 232 Safe Java Programming 234 vi | Table of Contents
6. Java’s Approach to Memory and Concurrency. . . . . . . . . . . . . . . . . . . . . . . . . 237 Basic Concepts of Java Memory Management 237 How the JVM Optimizes Garbage Collection 241 The HotSpot Heap 243 Finalization 248 Java’s Support for Concurrency 249 Working with Threads 261 Summary 263 Part II. Working with the Java Platform 7. Programming and Documentation Conventions. . . . . . . . . . . . . . . . . . . . . . 267 Naming and Capitalization Conventions 267 Practical Naming 269 Java Documentation Comments 271 Doclets 279 Conventions for Portable Programs 280 Summary 282 8. Working with Java Collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 Introduction to Collections API 283 Java Streams and Lambda Expressions 306 Summary 317 9. Handling Common Data Formats. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319 Text 319 Numbers and Math 329 Date and Time 334 Summary 341 10. File Handling and I/O. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 Classic Java I/O 343 Modern Java I/O 349 NIO Channels and Buffers 353 Async I/O 356 Networking 359 Summary 365 Table of Contents | vii
11. Classloading, Reflection, and Method Handles. . . . . . . . . . . . . . . . . . . . . . . . 367 Class Files, Class Objects, and Metadata 367 Phases of Classloading 370 Secure Programming and Classloading 372 Applied Classloading 374 Reflection 377 Method Handles 384 12. Java Platform Modules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389 Why Modules? 390 Writing Your Own Modules 394 Issues with Modules 403 Summary 406 13. Platform Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 Command-Line Tools 407 Introduction to JShell 425 Introduction to Java Flight Recorder (JFR) 428 Summary 429 Appendix. Beyond Java 17. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441 viii | Table of Contents
Foreword A lot can happen in four years. This is as true of programming languages as it is of anything else. Java 11, the first post-8 Java release with long-term support, arrived in September 2018 and the seventh edition of Java in a Nutshell came out a few months later. Since then, both the wider world and the Java ecosystem have seen major upheavals that were largely unpredictable at that time. The new release cadence, of a LTS release every three years (now changed to every two years), has found favor with the Java ecosystem—very few companies have chosen to adopt the interim, feature releases, and instead everyone prefers to stay on an upgrade path where only the LTS releases are productionized. Java 11 has proved to be an excellent release and a worthy successor to the now- legacy Java 8. With the release of Java 17, the language has moved forward yet again, with new features such as switch expressions and the introduction of Java’s version of alge‐ braic data types, in the form of records and sealed types. Java performance continues to improve, and Java 17 is the fastest release yet. In all, this is a great time to be joining (or returning to) application development in Java. Looking forward, the future holds some major changes that will alter the character of Java development in fundamental ways. The next year or two will start to see these changes arrive and become part of the Java developer’s everyday experience. ix
Once again, in working on this new edition of a classic text, if we have preserved the feel of Java in a Nutshell, while updating it to bring it to the attention of a new generation of developers, then we shall be well satisfied. —Ben Evans, Barcelona, Spain, 2022 Jason Clark, Portland, Oregon (& Barcelona, Spain), 2022 x | Foreword
Preface This book is a desktop Java reference, designed to sit faithfully by your keyboard while you program. Part I, “Introducing Java” is a fast-paced, “no-fluff ” introduc‐ tion to the Java programming language and the core runtime aspects of the Java platform. Part II, “Working with the Java Platform” is a reference section that blends elucidation of core concepts with examples of important core APIs. The book covers Java 17, but we recognize that some shops may not have adopted it yet—so where possible we call out if a feature was introduced after Java 8. We use Java 17 syntax throughout, including var and lambda expressions. Changes in the Eighth Edition The seventh edition of this book covers Java 11, whereas this edition covers Java 17. However, the release process of Java changed significantly with the arrival of Java 9, and certain releases of Java are now badged as long-term support (LTS) releases. So, Java 17 is the next LTS release of Java after Java 11. With the eighth edition we have tried to update the concept of what it means to be a “Nutshell” guide. The modern Java developer needs to know more than just syntax and APIs. As the Java environment has matured, such topics as concurrency, object- oriented design, memory, and the Java type system have all grown in importance for all developers. In this edition, we have taken the approach that only the most recent versions of Java are likely to be of interest to the majority of Java developers, so we usually only call out when new features arrived after Java 8. For example, the module system (that arrived with Java 9) is still likely to be new for at least some developers, and it represents a major change. However, it is also something of an advanced topic and is in someways separate from the rest of the language, so we have restricted our treatment of it to a single chapter. xi
Contents of This Book The first six chapters document the Java language and the Java platform—they should all be considered essential reading. The book is biased toward the Ora‐ cle/OpenJDK (Open Java Development Kit) implementation of Java but not greatly so. Developers working with other Java environments will still find plenty to occupy them. Part I includes: Chapter 1, “Introduction to the Java Environment” This chapter is an overview of the Java language and the Java platform. It explains the important features and benefits of Java, including the lifecycle of a Java program. We also touch on Java security and answer some criticisms of Java. Chapter 2, “Java Syntax from the Ground Up” This chapter explains the details of the Java programming language, including the Java 8 language changes. It is a long and detailed chapter that does not assume substantial programming experience. Experienced Java programmers can use it as a language reference. Programmers with substantial experience with languages such as C and C++ should be able to pick up Java syntax quickly by reading this chapter; beginning programmers with only a modest amount of experience should be able to learn Java programming by studying this chapter carefully, although it is best read in conjunction with an introduc‐ tory text (such as O’Reilly’s Head First Java by Kathy Sierra, Bert Bates, and Trisha Gee). Chapter 3, “Object-Oriented Programming in Java” This chapter describes how the basic Java syntax documented in Chapter 2 is used to write simple object-oriented programs using classes and objects in Java. The chapter assumes no prior experience with object-oriented programming. It can be used as a tutorial by new programmers or as a reference by experienced Java programmers. Chapter 4, “The Java Type System” This chapter builds on the basic description of object-oriented programming in Java and introduces the other aspects of Java’s type system, such as generic types, enumerated types, and annotations. With this more complete picture, we can discuss the biggest change in Java 8—the arrival of lambda expressions. Chapter 5, “Introduction to Object-Oriented Design in Java” This chapter is an overview of some basic techniques used in the design of sound object-oriented programs, and it briefly touches on the topic of design patterns and their use in software engineering. Chapter 6, “Java’s Approach to Memory and Concurrency” This chapter explains how the Java Virtual Machine manages memory on behalf of the programmer, and how memory and visibility are intimately entwined with Java’s support for concurrent programming and threads. xii | Preface
These first six chapters teach you the Java language and get you up and running with the most important concepts of the Java platform. Part II is all about how to get real programming work done in the Java environment. It contains plenty of examples and is designed to complement the cookbook approach found in some other texts. This part includes: Chapter 7, “Programming and Documentation Conventions” This chapter documents important and widely adopted Java programming conventions. It also explains how you can make your Java code self- documenting by including specially formatted documentation comments. Chapter 8, “Working with Java Collections” This chapter introduces Java’s standard collections libraries. These contain data structures that are vital to the functioning of virtually every Java program— such as List, Map, and Set. The new Stream abstraction and the relationship between lambda expressions and the collections are explained in detail. Chapter 9, “Handling Common Data Formats” This chapter discusses how to use Java to work effectively with very common data formats, such as text, numbers, and temporal (date and time) information. Chapter 10, “File Handling and I/O” This chapter covers several different approaches to file access—from the more classic approach found in older versions of Java, to more modern and even asynchronous styles. The chapter concludes with a short introduction to net‐ working with the core Java platform APIs. Chapter 11, “Classloading, Reflection, and Method Handles” This chapter introduces the subtle art of metaprogramming in Java—first intro‐ ducing the concept of metadata about Java types, then turning to the subject of classloading and how Java’s security model is linked to the dynamic loading of types. The chapter concludes with some applications of classloading and the relatively new feature of method handles. Chapter 12, “Java Platform Modules” This chapter describes Java Platform Module System (JPMS), the major feature that was introduced as part of Java 9, and provides an introduction to the wide-ranging changes that it brings. Chapter 13, “Platform Tools” Oracle’s JDK (as well as OpenJDK) includes a number of useful Java devel‐ opment tools, most notably the Java interpreter and the Java compiler. This chapter documents those tools, as well as the jshell interactive environment and new tools for working with modular Java. Appendix This appendix covers Java beyond version 17, including the releases Java 18 and 19 as well as ongoing research and development projects to enhance the language and JVM. Preface | xiii
Related Books O’Reilly publishes an entire series of books on Java programming, including several companion books to this one: Learning Java by Patrick Niemeyer and Daniel Leuck This book is a comprehensive tutorial introduction to Java and includes topics such as XML and client-side Java programming. Java 8 Lambdas by Richard Warburton This book documents the new Java 8 feature of lambda expressions in detail and introduces concepts of functional programming that may be unfamiliar to Java developers coming from earlier versions. Head First Java by Kathy Sierra, Bert Bates, and Trisha Gee This book uses a unique approach to teaching Java. Developers who think visually often find it a great accompaniment to a traditional Java book. You can find a complete list of Java books from O’Reilly at http://java.oreilly.com. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program ele‐ ments such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values determined by context. This element signifies a tip or suggestion. This element signifies a general note. xiv | Preface
This element indicates a warning or caution. Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/kittylyst/javanut8. If you have a technical question or a problem using the code examples, please send an email to bookquestions@oreilly.com. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant por‐ tion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but generally do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Java in a Nutshell, Eighth Edition by Ben Evans, Jason Clark, and David Flanagan (O’Reilly). Copy‐ right 2023 Benjamin J. Evans and Jason Clark, 978-1-098-13100-5.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. O’Reilly Online Learning For more than 40 years, O’Reilly Media has pro‐ vided technology and business training, knowl‐ edge, and insight to help companies succeed. Our unique network of experts and innovators share their knowledge and expertise through books, articles, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, visit https://oreilly.com. Preface | xv
How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at https://oreil.ly/java-in-a-nutshell-8e. Email bookquestions@oreilly.com to comment or ask technical questions about this book. For news and information about our books and courses, visit https://oreilly.com. Find us on LinkedIn: https://linkedin.com/company/oreilly-media Follow us on Twitter: https://twitter.com/oreillymedia Watch us on YouTube: https://youtube.com/oreillymedia Acknowledgments Melissa Potter was the editor of the eighth edition. Her guidance and many useful contributions were a great help throughout the process. Special thanks are due to Dan Heidinga, Ashutosh Mehra, and Aleksey Shipilëv. Our technical reviewers for this edition were Mario Torre, Tony Mancill, Achyut Madhusudan, Jeff Maury, Rui Vieira, Jeff Alder, Kevin Earls, and Ashutosh Mehra. xvi | Preface
I Introducing Java Part I is an introduction to the Java language and the Java platform. These chapters provide enough information for you to get started using Java right away: Chapter 1, “Introduction to the Java Environment” Chapter 2, “Java Syntax from the Ground Up” Chapter 3, “Object-Oriented Programming in Java” Chapter 4, “The Java Type System” Chapter 5, “Introduction to Object-Oriented Design in Java” Chapter 6, “Java’s Approach to Memory and Concurrency”
(This page has no text content)