Learning Java an Introduction to Real-World Programming with Java
Total Page:16
File Type:pdf, Size:1020Kb
EditionFifth Learning Java An Introduction to Real-World Programming with Java Marc Loy, Patrick Niemeyer & Daniel Leuck FIFTH EDITION Learning Java An Introduction to Real-World Programming with Java Marc Loy, Patrick Niemeyer, and Daniel Leuck Beijing Boston Farnham Sebastopol Tokyo Learning Java by Marc Loy, Patrick Niemeyer, and Daniel Leuck Copyright © 2020 Marc Loy, Patrick Niemeyer, Daniel Leuck. 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 [email protected]. Acquisitions Editor: Suzanne McQuade Indexer: Angela Howard Developmental Editor: Amelia Blevins Interior Designer: David Futato Production Editor: Beth Kelly Cover Designer: Karen Montgomery Copyeditor: Sonia Saruba Illustrator: Rebecca Demarest Proofreader: Christina Edwards May 2000: First Edition July 2002: Second Edition May 2005: Third Edition June 2013: Fourth Edition March 2020: Fifth Edition Revision History for the Fifth Edition 2020-03-27: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781492056270 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. 978-1-492-05627-0 [LSI] Table of Contents Preface. xi 1. A Modern Language. 1 Enter Java 2 Java’s Origins 2 Growing Up 3 A Virtual Machine 4 Java Compared with Other Languages 7 Safety of Design 10 Simplify, Simplify, Simplify… 11 Type Safety and Method Binding 12 Incremental Development 13 Dynamic Memory Management 13 Error Handling 14 Threads 15 Scalability 15 Safety of Implementation 16 The Verifier 17 Class Loaders 19 Security Managers 19 Application and User-Level Security 20 A Java Road Map 21 The Past: Java 1.0–Java 11 21 The Present: Java 14 23 The Future 25 Availability 25 iii 2. A First Application. 27 Java Tools and Environment 28 Installing the JDK 28 Installing OpenJDK on Linux 29 Installing OpenJDK on macOS 30 Installing OpenJDK on Windows 31 Configuring IntelliJ IDEA and Creating a Project 35 Running the Project 39 Grabbing the Learning Java Examples 39 HelloJava 41 Classes 44 The main() Method 44 Classes and Objects 46 Variables and Class Types 46 HelloComponent 47 Inheritance 48 The JComponent Class 49 Relationships and Finger-Pointing 50 Package and Imports 51 The paintComponent() Method 52 HelloJava2: The Sequel 53 Instance Variables 55 Constructors 56 Events 58 The repaint() Method 60 Interfaces 60 Goodbye and Hello Again 62 3. Tools of the Trade. 63 JDK Environment 63 The Java VM 64 Running Java Applications 64 System Properties 66 The Classpath 66 javap 68 Modules 68 The Java Compiler 69 Trying Java 70 JAR Files 77 File Compression 77 The jar Utility 77 The pack200 Utility 80 iv | Table of Contents Building Up 81 4. The Java Language. 83 Text Encoding 84 Comments 86 Javadoc Comments 87 Variables and Constants 89 Types 90 Primitive Types 91 Reference Types 95 Inferring Types 97 Passing References 97 A Word About Strings 98 Statements and Expressions 99 Statements 100 Expressions 108 Arrays 114 Array Types 115 Array Creation and Initialization 115 Using Arrays 117 Anonymous Arrays 119 Multidimensional Arrays 119 Types and Classes and Arrays, Oh My! 121 5. Objects in Java. 123 Classes 124 Declaring and Instantiating Classes 125 Accessing Fields and Methods 127 Static Members 131 Methods 134 Local Variables 135 Shadowing 135 Static Methods 137 Initializing Local Variables 139 Argument Passing and References 140 Wrappers for Primitive Types 141 Method Overloading 143 Object Creation 145 Constructors 145 Working with Overloaded Constructors 146 Object Destruction 148 Garbage Collection 148 Table of Contents | v Packages 149 Importing Classes 150 Custom Packages 151 Member Visibility and Access 153 Compiling with Packages 155 Advanced Class Design 155 Subclassing and Inheritance 156 Interfaces 161 Inner Classes 163 Anonymous Inner Classes 165 Organizing Content and Planning for Failure 167 6. Error Handling and Logging. 169 Exceptions 170 Exceptions and Error Classes 170 Exception Handling 172 Bubbling Up 175 Stack Traces 176 Checked and Unchecked Exceptions 177 Throwing Exceptions 178 try Creep 182 The finally Clause 183 try with Resources 184 Performance Issues 185 Assertions 186 Enabling and Disabling Assertions 187 Using Assertions 188 The Logging API 189 Overview 189 Logging Levels 191 A Simple Example 192 Logging Setup Properties 193 The Logger 195 Performance 195 Real-World Exceptions 196 7. Collections and Generics. 197 Collections 197 The Collection Interface 198 Collection Types 199 The Map Interface 201 Type Limitations 203 vi | Table of Contents Containers: Building a Better Mousetrap 203 Can Containers Be Fixed? 205 Enter Generics 205 Talking About Types 208 “There Is No Spoon” 209 Erasure 210 Raw Types 211 Parameterized Type Relationships 213 Why Isn’t a List<Date> a List<Object>? 214 Casts 215 Converting Between Collections and Arrays 216 Iterator 217 A Closer Look: The sort() Method 218 Application: Trees on the Field 219 Conclusion 221 8. Text and Core Utilities. 223 Strings 223 Constructing Strings 224 Strings from Things 225 Comparing Strings 226 Searching 227 String Method Summary 228 Things from Strings 229 Parsing Primitive Numbers 229 Tokenizing Text 230 Regular Expressions 232 Regex Notation 232 The java.util.regex API 238 Math Utilities 243 The java.lang.Math Class 244 Big/Precise Numbers 247 Dates and Times 248 Local Dates and Times 248 Comparing and Manipulating Dates and Times 249 Time Zones 250 Parsing and Formatting Dates and Times 251 Parsing Errors 253 Timestamps 255 Other Useful Utilities 255 Table of Contents | vii 9. Threads. 257 Introducing Threads 258 The Thread Class and the Runnable Interface 258 Controlling Threads 262 Death of a Thread 267 Synchronization 268 Serializing Access to Methods 269 Accessing Class and Instance Variables from Multiple Threads 274 Scheduling and Priority 275 Thread State 277 Time-Slicing 278 Priorities 279 Yielding 280 Thread Performance 280 The Cost of Synchronization 280 Thread Resource Consumption 281 Concurrency Utilities 282 10. Desktop Applications. 285 Buttons and Sliders and Text Fields, Oh My! 286 Component Hierarchies 286 Model View Controller Architecture 287 Labels and Buttons 288 Text Components 294 Other Components 302 Containers and Layouts 306 Frames and Windows 307 JPanel 309 Layout Managers 310 Events 318 Mouse Events 319 Action Events 322 Change Events 325 Other Events 326 Modals and Pop Ups 327 Message Dialogs 327 Confirmation Dialogs 330 Input Dialogs 332 Threading Considerations 332 SwingUtilities and Component Updates 333 Timers 336 Next Steps 339 viii | Table of Contents Menus 339 Preferences 341 Custom Components and Java2D 341 JavaFX 342 User Interface and User Experience 342 11. Networking and I/O. 343 Streams 343 Basic I/O 345 Character Streams 348 Stream Wrappers 349 The java.io.File Class 353 File Streams 358 RandomAccessFile 360 The NIO File API 361 FileSystem and Path 362 NIO File Operations 364 The NIO Package 366 Asynchronous I/O 367 Performance 367 Mapped and Locked Files 368 Channels 368 Buffers 369 Character Encoders and Decoders 372 FileChannel 374 Network Programming 377 Sockets 379 Clients and Servers 380 The DateAtHost Client 384 A Distributed Game 386 More to Explore 396 12. Programming for the Web. 397 Uniform Resource Locators 397 The URL Class 398 Stream Data 399 Getting the Content as an Object 400 Managing Connections 401 Handlers in Practice 402 Useful Handler Frameworks 403 Talking to Web Applications 403 Using the GET Method 404 Table of Contents | ix Using the POST Method 405 The HttpURLConnection 408 SSL and Secure Web Communications 409 Java Web Applications 409 The Servlet Life Cycle 411 Servlets 412 The HelloClient Servlet 413 The Servlet Response 415 Servlet Parameters 416 The ShowParameters Servlet 417 User Session Management 419 The ShowSession Servlet 420 Servlet Containers 422 Configuration with web.xml and Annotations 423 URL Pattern Mappings 426 Deploying HelloClient 427 The World Wide Web Is, Well, Wide 428 13. Expanding Java. 429 Java Releases 429 JCP and JSRs 430 Lambda Expressions 430 Retrofitting Your Code 431 Expanding Java Beyond the Core 437 Final Wrap-Up and Next Steps 437 A. Code Examples and IntelliJ IDEA. 439 Glossary. 459 Index. 473 x | Table of Contents Preface This book is about 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 introduction was one of the most exciting developments in the history of the web, and Java applications have powered much of the growth of business on the internet. Java is, arguably, the most popular program‐ ming 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.