(This page has no text content)
About This eBook ePUB is an open, industry-standard format for eBooks. However, support of ePUB and its many features varies across reading devices and applications. Use your device or app settings to customize the presentation to your liking. Settings that you can customize often include font, font size, single or double column, landscape or portrait mode, and figures that you can click or tap to enlarge. For additional information about the settings and features on your reading device or app, visit the device manufacturer’s Web site. Many titles include programming code or configuration examples. To optimize the presentation of these elements, view the eBook in single-column, landscape mode and adjust the font size to the smallest setting.
Core Java Volume I—Fundamentals Thirteenth Edition Cay S. Horstmann Hoboken, New Jersey Cover image: Jon Chica/Shutterstock Figure 1.1: Sourceforge Figures 2.2, 3.2-3.5, 4.9, 5.4, 7.2, 10.5, 10.6, 11.1: Oracle Corporation Figures 2.3-2.6, 12.2: Eclipse Foundation, Inc. Figure 4.2: Violet UML Editor Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals.
The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. The views expressed in this book are those of the author and do not necessarily reflect the views of Oracle. For information about buying this title in bulk quantities, or for special sales opportunities (which may include electronic versions; custom cover designs; and content particular to your business, training goals, marketing focus, or branding interests), please contact our corporate sales department at corpsales@pearsoned.com or (800) 382-3419. For government sales inquiries, please contact governmentsales@pearsoned.com. For questions about sales outside the U.S., please contact intlcs@pearson.com. Please contact us with concerns about any potential bias at pearson.com/report-bias.html. Visit us on the Web: informit.com/aw
Copyright © 2024 Pearson Education, Inc. Portions copyright © 1996-2013 Oracle and/or its affiliates. All Rights Reserved. Oracle America Inc. does not make any representations or warranties as to the accuracy, adequacy or completeness of any information contained in this work, and is not responsible for any errors or omissions. Microsoft and/or its respective suppliers make no representations about the suitability of the information contained in the documents and related graphics published as part of the services for any purpose. All such documents and related graphics are provided "as is" without warranty of any kind. Microsoft and/or its respective suppliers hereby disclaim all warranties and conditions with regard to this information, including all warranties and conditions of merchantability, whether express, implied or statutory, fitness for a particular purpose, title and non-infringement. In no event shall Microsoft and/or its respective suppliers be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of information
available from the services. The documents and related graphics contained herein could include technical inaccuracies or typographical errors. Changes are periodically added to the information herein. Microsoft and/or its respective suppliers may make improvements and/or changes in the product(s) and/or the program(s) described herein at any time. Partial screen shots may be viewed in full within the software version specified. Microsoft® Windows®, and Microsoft Office® are registered trademarks of the Microsoft Corporation in the U.S.A. and other countries. This book is not sponsored or endorsed by or affiliated with the Microsoft Corporation. All rights reserved. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, request forms and the appropriate contacts within the Pearson Education Global Rights & Permissions Department, please visit www.pearson.com/permissions.
ISBN-13: 978-0-13-532837-8 ISBN-10: 0-13-532837-3
Chapter 1 ▪ Table of Contents 1. About This eBook 2. Preface 1. To the Reader 2. A Tour of This Book 3. Conventions 4. Sample Code 3. Acknowledgments 4. 1. An Introduction to Java 1. 1.1. Java as a Programming Platform 2. 1.2. The Java “White Paper” Buzzwords 3. 1.3. Java Applets and the Internet 4. 1.4. A Short History of Java 5. 1.5. Common Misconceptions about Java 5. 2. The Java Programming Environment 1. 2.1. Installing the Java Development Kit 2. 2.2. Using the Command-Line Tools 3. 2.3. Using an Integrated Development Environment 4. 2.4. JShell 6. 3. Fundamental Programming Structures in Java 1. 3.1. A Simple Java Program 2. 3.2. Comments 3. 3.3. Data Types
4. 3.4. Variables and Constants 5. 3.5. Operators 6. 3.6. Strings 7. 3.7. Input and Output 8. 3.8. Control Flow 9. 3.9. Big Numbers 10. 3.10. Arrays 7. 4. Objects and Classes 1. 4.1. Introduction to Object-Oriented Programming 2. 4.2. Using Predefined Classes 3. 4.3. Defining Your Own Classes 4. 4.4. Static Fields and Methods 5. 4.5. Method Parameters 6. 4.6. Object Construction 7. 4.7. Records 8. 4.8. Packages 9. 4.9. JAR Files 10. 4.10. Documentation Comments 11. 4.11. Class Design Hints 8. 5. Inheritance 1. 5.1. Classes, Superclasses, and Subclasses 2. 5.2. Object : The Cosmic Superclass 3. 5.3. Generic Array Lists 4. 5.4. Object Wrappers and Autoboxing
5. 5.5. Methods with a Variable Number of Arguments 6. 5.6. Abstract Classes 7. 5.7. Enumeration Classes 8. 5.8. Sealed Classes 9. 5.9. Pattern Matching 10. 5.10. Reflection 11. 5.11. Design Hints for Inheritance 9. 6. Interfaces, Lambda Expressions, and Inner Classes 1. 6.1. Interfaces 2. 6.2. Lambda Expressions 3. 6.3. Inner Classes 4. 6.4. Service Loaders 5. 6.5. Proxies 10. 7. Exceptions, Assertions, and Logging 1. 7.1. Dealing with Errors 2. 7.2. Catching Exceptions 3. 7.3. Tips for Using Exceptions 4. 7.4. Using Assertions 5. 7.5. Logging 6. 7.6. Debugging Tips 11. 8. Generic Programming 1. 8.1. Why Generic Programming? 2. 8.2. Defining a Simple Generic Class 3. 8.3. Generic Methods
4. 8.4. Bounds for Type Variables 5. 8.5. Generic Code and the Virtual Machine 6. 8.6. Inheritance Rules for Generic Types 7. 8.7. Wildcard Types 8. 8.8. Restrictions and Limitations 9. 8.9. Reflection and Generics 12. 9. Collections 1. 9.1. The Java Collections Framework 2. 9.2. Interfaces in the Collections Framework 3. 9.3. Concrete Collections 4. 9.4. Maps 5. 9.5. Copies and Views 6. 9.6. Algorithms 7. 9.7. Legacy Collections 13. 10. Concurrency 1. 10.1. Running Threads 2. 10.2. Thread States 3. 10.3. Thread Properties 4. 10.4. Coordinating Tasks 5. 10.5. Synchronization 6. 10.6. Thread-Safe Collections 7. 10.7. Asynchronous Computations 8. 10.8. Processes 14. 11. Annotations
1. 11.1. Using Annotations 2. 11.2. Defining Annotations 3. 11.3. Annotations in the Java API 4. 11.4. Processing Annotations at Runtime 5. 11.5. Source-Level Annotation Processing 6. 11.6. Bytecode Engineering 15. 12. The Java Platform Module System 1. 12.1. The Module Concept 2. 12.2. Naming Modules 3. 12.3. The Modular “Hello, World!” Program 4. 12.4. Requiring Modules 5. 12.5. Exporting Packages 6. 12.6. Modular JARs 7. 12.7. Modules and Reflective Access 8. 12.8. Automatic Modules 9. 12.9. The Unnamed Module 10. 12.10. Command-Line Flags for Migration 11. 12.11. Transitive and Static Requirements 12. 12.12. Qualified Exporting and Opening 13. 12.13. Service Loading 14. 12.14. Tools for Working with Modules 16. Appendix
Preface To the Reader In late 1995, the Java programming language burst onto the Internet scene and gained instant celebrity status. The promise of Java technology was that it would become the universal glue that connects users with information wherever it comes from— web servers, databases, information providers, or any other imaginable source. Indeed, Java is in a unique position to fulfill this promise. It is an extremely solidly engineered language that has gained wide acceptance. Its built-in security and safety features are reassuring both to programmers and to the users of Java programs. Java has built-in support for advanced programming tasks, such as network programming, database connectivity, and concurrency. Since 1995, over twenty revisions of the Java Development Kit have been released. The Application Programming Interface (API) has grown from about a hundred to over 4,000 classes. The API now spans such diverse areas as concurrent programming, collections, user interface construction, database management, internationalization, security, and XML processing.
The book that you are reading right now is the first volume of the thirteenth edition of Core Java. Each edition closely followed a release of the Java Development Kit, and each time, I rewrote the book to take advantage of the newest Java features. This edition has been updated to reflect the features of Java 21. As with the previous editions, this book still targets serious programmers who want to put Java to work on real projects. I think of you, the reader, as a programmer with a solid background in a programming language other than Java. I assume that you don't like books filled with toy examples (such as toasters, zoo animals, or "nervous text"). You won't find any of these in the book. My goal is to enable you to fully understand the Java language and library, not to give you an illusion of understanding. In this book you will find lots of sample code demonstrating almost every language and library feature. The sample programs are purposefully simple to focus on the major points, but, for the most part, they aren't fake and they don't cut corners. They should make good starting points for your own code. I assume you are willing, even eager, to learn about all the features that the Java language puts at your disposal. In this
volume, you will find a detailed treatment of Object-oriented programming Reflection and proxies Interfaces and inner classes Exception handling Generic programming The collections framework Concurrency Annotations The Java platform module system With the explosive growth of the Java class library, a one- volume treatment of all the features of Java that serious programmers need to know is simply not possible. Hence, the book is broken up into two volumes. This first volume concentrates on the fundamental concepts of the Java language. The second volume, Core Java, Volume II: Advanced Features, goes further into the most important libraries. For twelve editions, user-interface programming was considered fundamental, but the time has come to recognize that it is no more, and to move it into the second volume. That volume includes detailed discussions of these topics:
The Stream API File processing and regular expressions Databases XML processing Scripting and Compiling APIs Internationalization Network programming Graphical user interface design Graphics programming Native methods When writing a book, errors and inaccuracies are inevitable. I'd very much like to know about them. But, of course, I'd prefer to learn about each of them only once. You will find a list of frequently asked questions and bug fixes at https://horstmann.com/corejava. Strategically placed at the end of the errata page (to encourage you to read through it first) is a form you can use to report bugs and suggest improvements. Please don't be disappointed if I don't answer every query or don't get back to you immediately. I do read all e-mail and appreciate your input to make future editions of this book clearer and more informative.
A Tour of This Book Chapter 1 gives an overview of the capabilities of Java that set it apart from other programming languages. The chapter explains what the designers of the language set out to do and to what extent they succeeded. A short history of Java follows, detailing how Java came into being and how it has evolved. In Chapter 2, you will see how to download and install the JDK and the program examples for this book. Then I'll guide you through compiling and running a console application and a graphical application. You will see how to use the plain JDK, a Java IDE, and the JShell tool. Chapter 3 starts the discussion of the Java language. In this chapter, I cover the basics: variables, loops, and simple functions. If you are a C or C++ programmer, this is smooth sailing because the syntax for these language features is essentially the same as in C. If you come from a non-C background such as Visual Basic, you will want to read this chapter carefully. Object-oriented programming (OOP) is now in the mainstream of programming practice, and Java is an object-oriented programming language. Chapter 4 introduces encapsulation,
the first of two fundamental building blocks of object orientation, and the Java language mechanism to implement it —that is, classes and methods. In addition to the rules of the Java language, you will also find advice on sound OOP design. Finally, I cover the marvelous javadoc tool that formats your code comments as a set of hyperlinked web pages. If you are familiar with C++, you can browse through this chapter quickly. Programmers coming from a non-object-oriented background should expect to spend some time mastering the OOP concepts before going further with Java. Classes and encapsulation are only one part of the OOP story, and Chapter 5 introduces the other—namely, inheritance. Inheritance lets you take an existing class and modify it according to your needs. This is a fundamental technique for programming in Java. The inheritance mechanism in Java is quite similar to that in C++. Once again, C++ programmers can focus on the differences between the languages. Chapter 6 shows you how to use Java's notion of an interface. Interfaces let you go beyond the simple inheritance model of Chapter 5. Mastering interfaces allows you to have full access to the power of Java's completely object-oriented approach to programming. After covering interfaces, I move on to lambda expressions, a concise way for expressing a block of code that
can be executed at a later point in time. I then explain a useful technical feature of Java called inner classes. Chapter 7 discusses exception handling—Java's robust mechanism to deal with the fact that bad things can happen to good programs. Exceptions give you an efficient way of separating the normal processing code from the error handling. Of course, even after hardening your program by handling all exceptional conditions, it still might fail to work as expected. Then the chapter moves on to logging. In the final part of this chapter, I give you a number of useful debugging tips. Chapter 8 gives an overview of generic programming. Generic programming makes your programs easier to read and safer. I show you how to use strong typing and remove unsightly and unsafe casts, and how to deal with the complexities that arise from the need to stay compatible with older versions of Java. The topic of Chapter 9 is the collections framework of the Java platform. Whenever you want to collect multiple objects and retrieve them later, you should use a collection that is best suited for your circumstances, instead of just tossing the elements into an array. This chapter shows you how to take advantage of the standard collections that are prebuilt for your use.
Chapter 10 covers concurrency, which enables you to program tasks to be done in parallel. This is an important and exciting application of Java technology in an era where processors have multiple cores that you want to keep busy. In Chapter 11, you will learn about annotations, which allow you to add arbitrary information (sometimes called metadata) to a Java program. We show you how annotation processors can harvest these annotations at the source or class file level, and how annotations can be used to influence the behavior of classes at runtime. Annotations are only useful with tools, and we hope that our discussion will help you select useful annotation processing tools for your needs. In Chapter 12, you will learn about the Java Platform Module System that facilitates an orderly evolution of the Java platform and core libraries. This module system provides encapsulation for packages and a mechanism for describing module requirements. You will learn the properties of modules so that you can decide whether to use them in your own applications. Even if you decide not to, you need to know the new rules so that you can interact with the Java platform and other modularized libraries. The Appendix lists the reserved words of the Java language.
Comments 0
Loading comments...
Reply to Comment
Edit Comment