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
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
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
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
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
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
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
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
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
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.