Marc Loy, Patrick Niemeyer & Daniel Leuck Learning Java An Introduction to Real-World Programming with Java Sixth Edition
PROGR AMMING L ANGUAGES “Loy’s explanations of Java are surpassingly clear and startlingly useful, as well as amusing. He speaks Java like a native and makes his intimate knowledge of the nuances in that language accessible to every reader.” —Tom Berry Staff Content Engineer, ServiceNow Learning Java Twitter: @oreillymedia linkedin.com/company/oreilly-media youtube.com/oreillymedia Ideal for working programmers new to Java, this best-selling book guides you through the language features and APIs of Java 21. Through fun, compelling, and realistic examples, authors Marc Loy, Patrick Niemeyer, and Dan Leuck introduce you to Java’s fundamentals, including its class libraries, programming techniques, and idioms, with an eye toward building real applications. This updated sixth edition expands the content to continue covering lambdas and streams, and shows you how to use a functional paradigm in Java. You’ll learn about the latest Java features introduced since the book’s fifth edition, from JDK 15 through 21. You’ll also take a deep dive into virtual threads (introduced as Project Loom in Java 19). This guide helps you: • Learn the structure of the Java language and Java applications • Write, compile, and execute Java applications • Understand the basics of Java threading and concurrent programming • Learn Java I/O basics, including local files and network resources • Create compelling interfaces with an eye toward usability • Learn how functional features have been integrated in Java • Keep up with Java developments as new versions are released Marc Loy is a senior software engineer and technical trainer specializing in user experience design and full-stack development. Patrick Niemeyer is an independent developer and author working in the areas of decentralized applications and machine learning. Dan Leuck is the CEO of Ikayzo, a Tokyo and Honolulu-based interactive design and software development firm. US $79.99 CAN $99.99 ISBN: 978-1-098-14553-8
Marc Loy, Patrick Niemeyer, and Daniel Leuck Learning Java An Introduction to Real-World Programming with Java SIXTH EDITION Boston Farnham Sebastopol TokyoBeijing
978-1-098-14553-8 [LSI] Learning Java by Marc Loy, Patrick Niemeyer, and Daniel Leuck Copyright © 2023 Marc Loy. 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 Editor: Brian Guerin Development Editor: Sarah Grey Production Editor: Ashley Stussy Copyeditor: Sonia Saruba Proofreader: Piper Editorial Consulting, LLC Indexer: Potomac Indexing, LLC Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Kate Dullea May 2000: First Edition July 2002: Second Edition May 2005: Third Edition June 2013: Fourth Edition March 2020: Fifth Edition August 2023: Sixth Edition Revision History for the Sixth Edition 2023-08-16: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781098145538 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Learning Java, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. 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.
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. A Modern Language. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Enter Java 2 Java’s Origins 2 Growing Up 3 A Virtual Machine 5 Java Compared with Other Languages 8 Safety of Design 11 Simplify, Simplify, Simplify… 11 Type Safety and Method Binding 12 Incremental Development 14 Dynamic Memory Management 14 Error Handling 15 Threads 16 Scalability 16 Safety of Implementation 17 The Verifier 18 Class Loaders 19 Application and User-Level Security 20 A Java Road Map 20 The Past: Java 1.0–Java 20 21 The Present: Java 21 23 The Future 25 Exercises 26 iii
2. A First Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 Java Tools and Environment 27 Installing the JDK 28 Installing IntelliJ IDEA and Creating a Project 33 Running the Project 35 Grabbing the Examples 39 HelloJava 40 Classes 42 The main() Method 43 Classes and Objects 44 Variables and Class Types 45 HelloComponent 46 Inheritance 48 The JComponent Class 48 Relationships and Finger-Pointing 49 Packages and Imports 50 The paintComponent() Method 52 HelloJava2: The Sequel 53 Instance Variables 54 Constructors 55 Events 58 The repaint() Method 60 Interfaces 61 Goodbye and Hello Again 62 Review Questions 62 Code Exercises 63 3. Tools of the Trade. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 JDK Environment 65 The Java VM 66 Running Java Applications 67 System Properties 68 The Classpath 69 CLASSPATH on Unix and macOS 69 CLASSPATH on Windows 70 CLASSPATH Wildcards 70 Modules 71 The Java Compiler 71 Trying Java 73 JAR Files 78 iv | Table of Contents
The jar Utility 79 Tool Wrap-Up 83 Review Questions 83 Code Exercises 83 Advanced Code Exercises 84 4. The Java Language. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Text Encoding 86 Comments 88 Javadoc Comments 89 Annotations 90 Variables and Constants 91 Types 93 Primitive Types 94 Reference Types 98 A Word About Strings 101 Statements and Expressions 102 Statements 103 Expressions 114 Arrays 120 Array Types 121 Array Creation and Initialization 122 Using Arrays 124 Anonymous Arrays 126 Multidimensional Arrays 127 Types and Classes and Arrays, Oh My! 129 Review Questions 130 Code Exercises 130 Advanced Exercises 132 5. Objects in Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 Classes 134 Declaring and Instantiating Classes 135 Accessing Fields and Methods 137 Static Members 142 Methods 144 Local Variables 145 Shadowing 146 Static Methods 147 Initializing Local Variables 149 Argument Passing and References 151 Table of Contents | v
Wrappers for Primitive Types 152 Method Overloading 154 Object Creation 155 Constructors 155 Working with Overloaded Constructors 157 Object Destruction 158 Garbage Collection 159 Packages 160 Importing Classes 161 Custom Packages 163 Member Visibility and Access 164 Compiling with Packages 166 Advanced Class Design 167 Subclassing and Inheritance 167 Abstract Classes and Methods 172 Interfaces 174 Inner Classes 177 Anonymous Inner Classes 179 Organizing Content and Planning for Failure 180 Review Questions 183 Code Exercises 183 Advanced Exercises 184 6. Error Handling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 Exceptions 188 Exceptions and Error Classes 188 Exception Handling 191 Bubbling Up 194 Stack Traces 195 Checked and Unchecked Exceptions 196 Throwing Exceptions 197 try Creep 200 The finally Clause 201 try with Resources 202 Performance Issues 204 Assertions 204 Enabling and Disabling Assertions 206 Using Assertions 206 Real-World Exceptions 207 Review Questions 208 Code Exercises 208 vi | Table of Contents
Advanced Exercises 209 7. Collections and Generics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 Collections 211 The Collection Interface 212 Collection Types 213 The Map Interface 215 Type Limitations 217 Containers: Building a Better Mousetrap 217 Can Containers Be Fixed? 219 Enter Generics 219 Talking About Types 223 “There Is No Spoon” 223 Erasure 224 Raw Types 225 Parameterized Type Relationships 227 Why Isn’t a List<Date> a List<Object>? 228 Casts 229 Converting Between Collections and Arrays 230 Iterator 231 A Closer Look: The sort() Method 232 Application: Trees on the Field 233 Useful Features 235 Review Questions 235 Code Exercises 236 Advanced Exercises 236 8. Text and Core Utilities. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 Strings 237 Constructing Strings 238 Strings from Things 239 Comparing Strings 240 Searching 241 String Method Summary 242 Things from Strings 243 Parsing Primitive Numbers 244 Tokenizing Text 244 Regular Expressions 245 Regex Notation 246 The java.util.regex API 252 Math Utilities 257 Table of Contents | vii
The java.lang.Math Class 258 Big/Precise Numbers 261 Dates and Times 262 Local Dates and Times 263 Comparing and Manipulating Dates and Times 264 Time Zones 265 Parsing and Formatting Dates and Times 266 Formatting Dates and Times 269 Timestamps 270 Other Useful Utilities 270 Review Questions 271 Code Exercises 271 9. Threads. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 Introducing Threads 274 The Thread Class and the Runnable Interface 275 Controlling Threads 278 Revisiting Animation with Threads 281 Death of a Thread 284 Virtual Threads 285 Preview Feature Tangent 286 A Quick Comparison 289 Synchronization 290 Serializing Access to Methods 291 Accessing Class and Instance Variables from Multiple Threads 298 Scheduling and Priority 298 Thread State 299 Time-Slicing 300 Priorities 302 Thread Performance 302 The Cost of Synchronization 302 Thread Resource Consumption 303 Virtual Thread Performance 304 Concurrency Utilities 305 Upgrading Our Queue Demo 306 Structured Concurrency 307 So Many Threads to Pull 308 Review Questions 308 Code Exercises 309 viii | Table of Contents
10. File Input and Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 Streams 313 Basic I/O 315 Character Streams 317 Stream Wrappers 318 The java.io.File Class 322 File Streams 328 RandomAccessFile 330 The New I/O File API 331 FileSystem and Path 332 NIO File Operations 334 The NIO Package 337 Asynchronous I/O 337 Performance 338 Mapped and Locked Files 338 Channels 338 Buffers 339 Character Encoders and Decoders 343 FileChannel 345 FileChannel Example 348 wrap() Up 350 Review Questions 350 Code Exercises 351 Advanced Exercises 352 11. Functional Approaches in Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 Functions 101 353 Lambdas 354 Lambda Expressions 355 Functional Interfaces 359 Method References 361 Practical Lambdas: Sorting 362 Streams 363 Sources and Operations 363 Filtering Streams 367 Mapping Streams 368 Flatmaps 371 Reducing and Collecting 373 Using Lambdas Directly 378 Next Steps 379 Table of Contents | ix
Review Questions 379 Code Exercises 380 Advanced Exercises 380 12. Desktop Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 Buttons and Sliders and Text Fields, Oh My! 382 Component Hierarchies 382 Model View Controller Architecture 383 Labels and Buttons 384 Text Components 390 Other Components 397 Containers and Layouts 401 Frames and Windows 401 JPanel 403 Layout Managers 404 Events 413 Mouse Events 413 Action Events 416 Change Events 419 Other Events 420 Threading Considerations 421 SwingUtilities and Component Updates 422 Timers 425 But Wait, There’s More 427 Menus 428 Modals and Pop-Ups 430 User Interface and User Experience 433 Review Questions 433 Code Exercises 433 Advanced Exercises 434 13. Network Programming in Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435 Uniform Resource Locators 435 The URL Class 436 Stream Data 438 Getting the Content as an Object 438 Managing Connections 439 Talking to Web Applications 440 Using the GET Method 440 Using the POST Method 441 The HttpURLConnection 443 x | Table of Contents
SSL and Secure Web Communications 444 Network Programming 444 Sockets 446 Clients and Servers 447 The DateAtHost Client 451 A Distributed Game 453 Much More to Explore 463 Review Questions 464 Code Exercises 465 Advanced Exercises 465 A. Code Examples and IntelliJ IDEA. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467 B. Exercise Answers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509 Table of Contents | xi
(This page has no text content)
Preface This book introduces the Java programming language and environment. Whether you are a software developer or just someone who uses the internet in your daily life, you’ve undoubtedly heard about Java. Its arrival was one of the most exciting developments in the history of the web, and Java applications continue to power business on the internet. Java is, arguably, the most popular programming language in the world, used by millions of developers on almost every kind of computer imaginable. Java has surpassed languages such as C++ and Visual Basic in terms of developer demand and has become the de facto language for certain kinds of development—especially for web-based services. Most universities are now using Java in their introductory courses alongside the other important modern languages. Perhaps you’re using this text in one of your classes right now! This book gives you a thorough grounding in Java fundamentals and grammar. Learning Java, Sixth Edition, attempts to live up to its name by mapping out the Java language and its class libraries, programming techniques, and idioms. We’ll dig deep into interesting areas and at least scratch the surface of other popular topics. Other titles from O’Reilly pick up where we leave off and provide more comprehensive information on specific areas and applications of Java. Whenever possible, we provide compelling, realistic, and fun examples and avoid merely cataloging features. The examples are simple but hint at what can be done. We won’t be developing the next great “killer app” in these pages, but we hope to give you a starting point for many hours of experimentation and inspired tinkering that will lead you to develop one yourself. Who Should Read This Book This book is for computer professionals, students, technical people, and Finnish hackers. It’s for everyone who has a need for hands-on experience using Java with an eye toward building real applications. This book could also be considered a crash course in object-oriented programming, threads, and user interfaces. As you xiii
learn about Java, you’ll also learn a powerful and practical approach to software development, beginning with a deep understanding of the fundamentals of Java. Superficially, Java looks like C or C++, so you’ll have a tiny head start in using this book if you have some experience with one of these languages. If you do not, don’t worry. In many respects, Java acts like more dynamic languages such as Smalltalk and Lisp. Knowledge of another object-oriented programming language will certainly help, although you may have to change some ideas and unlearn a few habits. Java is considerably simpler than languages such as C++ and Smalltalk. If you learn well from concise examples and personal experimentation, you’ll like this book. New Developments We cover all of the important features of the latest “long-term support” release of Java, officially called Java Standard Edition (SE) 21, OpenJDK 21. Sun Microsystems (Java’s keeper before Oracle) has changed the naming scheme many times over the years. Sun coined the term Java 2 to cover the major new features introduced in Java version 1.2 and dropped the term JDK in favor of SDK. With the sixth release, Sun skipped from Java version 1.4 to Java 5.0 but revived the term JDK and kept its numbering convention. After that, we had Java 6, Java 7, and Java 8. Starting with Java 9, Oracle announced a regular (an expedited) release cadence. New versions are released twice a year, and we are at Java 21 as we write in 2023. This release of Java reflects a mature language with occasional syntactic changes and updates to packages and libraries. We’ve tried to capture these new features and update every example in this book to reflect the current Java style and best practices. New in This Edition (Java 15, 16, 17, 18, 19, 20, 21) This edition of the book continues our tradition of rework to be as up-to-date as possible. It incorporates changes from recent releases of Java, from Java 15 through Java 21 (early access). New topics in this edition include: • Virtual threads that allow for impressive performance gains in scenarios requir‐ ing many, many threads • New coverage of functional streams for data processing • Expanded coverage of lambda expressions • Updated examples and analysis throughout the book • Review questions and exercises to help reinforce topics discussed in each chapter xiv | Preface
Using This Book This book is organized as follows: • Chapters 1 and 2 provide a basic introduction to Java concepts and a tutorial to give you a jump-start on Java programming. • Chapter 3 discusses fundamental tools for developing with Java (the compiler, the interpreter, jshell, and the JAR file package). • Chapters 4 and 5 introduce programming fundamentals, then describe the Java language itself, beginning with the basic syntax and covering classes and objects, exceptions, arrays, enumerations, annotations, and much more. • Chapter 6 covers exceptions, errors, and the logging facilities native to Java. • Chapter 7 covers collections alongside generics and parameterized types in Java. • Chapter 8 covers text processing, formatting, scanning, string utilities, and many of the core API utilities. • Chapter 9 covers the language’s built-in thread facilities, including the new vir‐ tual threads. • Chapter 10 covers Java file I/O and the NIO package. • Chapter 11 covers function programming techniques in Java. • Chapter 12 covers the basics of graphical user interface (GUI) development with Swing. • Chapter 13 covers network communication for both clients and servers, as well as accessing web resources. If you’re like us, you don’t read books from front to back. If you’re really like us, you usually don’t read the preface at all. However, on the off chance that you will see this in time, here are a few suggestions: • If you are already a programmer and just need to learn Java in the next five minutes, you are probably looking for the examples. You might want to start by glancing at the tutorial in Chapter 2. If that doesn’t float your boat, you should at least look at the information in Chapter 3, which explains how to use the compiler and interpreter. This should get you started. • Chapter 12 discusses Java’s graphics features and component architecture. You should read this if you are interested in writing desktop graphical Java applications. Preface | xv
• Chapter 13 is the place to head if you are interested in writing network applica‐ tions or interacting with web-based services. Networking remains one of the more interesting and important parts of Java. Online Resources There are many online sources for information about Java. Look at Oracle’s official website for Java topics such as the software, updates, and Java releases. This is where you’ll find the reference implementation of the JDK, which includes the compiler, the interpreter, and other tools. Oracle also maintains the OpenJDK site. This is the primary open source version of Java and the associated tools. We’ll be using the OpenJDK for all the examples in this book. You should also visit O’Reilly’s site. There you’ll find information about other O’Reilly books for both Java and a growing array of other topics. You should also check out the online learning and conference options—O’Reilly is a real champion for education in all its forms. And of course, you can check the home page for Learning Java! Conventions Used in This Book The font conventions used in this book are quite simple. Italic is used for: • Pathnames, filenames, and program names • Internet addresses, such as domain names and URLs • New terms where they are defined • Program names, compilers, interpreters, utilities, and commands • Emphasis on important points Constant width is used for: • Anything that might appear in a Java program, including method names, variable names, and class names • Tags that might appear in an HTML or XML document • Keywords, objects, and environment variables xvi | Preface
Constant width bold is used for: • Text that is typed by the user on the command line or in a dialog Constant width italic is used for: • Replaceable items in code This element signifies a tip or suggestion. This element signifies a general note. This element indicates a warning or caution. In the main body of text, we always use a pair of empty parentheses after a method name to distinguish methods from variables, classes, and other creatures. In the Java source listings, we follow the coding conventions most frequently used in the Java community. Class names begin with capital letters; variable and method names begin with lowercase. All the letters in the names of constants are capitalized. We don’t use underscores to separate words in a long name; follow‐ ing common practice, we capitalize individual words (after the first) and run the words together. For example: thisIsAVariable, thisIsAMethod(), ThisIsAClass, and THIS_IS_A_CONSTANT. Also note that we differentiate between static and non‐ static methods when we refer to them. Unlike some books, we never write Foo.bar() to mean the bar() method of Foo unless bar() is a static method (paralleling the Java syntax in that case). For source listings from example programs, the listing will begin with a comment indicating the related filename (and method name, if needed): Preface | xvii
// filename: ch02/examples/HelloWorld.java public static void main(String args[]) { System.out.println("Hello, world!"); } You should feel free to look at the noted file in your editor or IDE. We encourage you to compile and run the examples. And we especially encourage tinkering! For work in jshell, we will always retain the jshell prompt: jshell> System.out.println("Hello, jshell!") Hello, jshell! Other snippets without a filename or jshell prompt are meant to illustrate valid syntax and structure, or to present a hypothetical approach to handling a programming task. These undecorated listings are not necessarily meant to be executed, although you are always encouraged to create your own classes for trying out any topic in the book. Using Code Examples 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 portion 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: “Learning Java by Marc Loy, Patrick Niemeyer, and Daniel Leuck (O’Reilly). Copyright 2023 Marc Loy, 978-1-098-14553-8.” 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. If you have a technical question or a problem using the code examples, please send email to bookquestions@oreilly.com. xviii | Preface
Comments 0
Loading comments...
Reply to Comment
Edit Comment