100% found this document useful (7 votes)
51 views

Full Download Java: A Beginner's Guide: Create, Compile, and Run Java Programs Today 9th Edition Herbert Schildt - Ebook PDF

Schildt

Uploaded by

muhalaintani83
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (7 votes)
51 views

Full Download Java: A Beginner's Guide: Create, Compile, and Run Java Programs Today 9th Edition Herbert Schildt - Ebook PDF

Schildt

Uploaded by

muhalaintani83
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Download the full version of the ebook now at ebooksecure.

com

Java: A Beginner's Guide: Create, Compile,


and Run Java Programs Today 9th Edition
Herbert Schildt - eBook PDF

https://ebooksecure.com/download/java-a-beginners-
guide-create-compile-and-run-java-programs-today-
ebook-pdf/

Explore and download more ebook at https://ebooksecure.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Java: A Beginner’s Guide 7th Edition Herbert Schildt -


eBook PDF

https://ebooksecure.com/download/java-a-beginners-guide-ebook-pdf/

ebooksecure.com

Java: A Beginner’s Guide, Eighth Edition Herbert Schildt -


eBook PDF

https://ebooksecure.com/download/java-a-beginners-guide-eighth-
edition-ebook-pdf/

ebooksecure.com

Java: The Complete Reference 12th Edition Herbert Schildt


- eBook PDF

https://ebooksecure.com/download/java-the-complete-reference-ebook-
pdf/

ebooksecure.com

Human Anatomy & Physiology Laboratory Manual, Main Version


12th Edition by Elaine N. Marieb (eBook PDF)

https://ebooksecure.com/product/human-anatomy-physiology-laboratory-
manual-main-version-12th-edition-by-elaine-n-marieb-ebook-pdf/

ebooksecure.com
(eBook PDF) Counseling Theory and Practice 2nd ed. Edition

https://ebooksecure.com/product/ebook-pdf-counseling-theory-and-
practice-2nd-ed-edition/

ebooksecure.com

(eBook PDF) Netter's Atlas of Neuroscience E-Book (Netter


Basic Science) 3rd Edition

https://ebooksecure.com/product/ebook-pdf-netters-atlas-of-
neuroscience-e-book-netter-basic-science-3rd-edition/

ebooksecure.com

Discrete Mathematics and Its Applications 8th Edition


(eBook PDF)

https://ebooksecure.com/product/discrete-mathematics-and-its-
applications-8th-edition-ebook-pdf/

ebooksecure.com

(eBook PDF) Professional Piano Teaching, Volume 2: A


Comprehensive Piano Pedagogy Textbook

https://ebooksecure.com/product/ebook-pdf-professional-piano-teaching-
volume-2-a-comprehensive-piano-pedagogy-textbook/

ebooksecure.com

(eBook PDF) Reconstructive Surgery of the Hand and Upper


Extremity

https://ebooksecure.com/product/ebook-pdf-reconstructive-surgery-of-
the-hand-and-upper-extremity/

ebooksecure.com
(eBook PDF) Information Systems A Manager's Guide to
Harnessing Technology Version 7.0

https://ebooksecure.com/product/ebook-pdf-information-systems-a-
managers-guide-to-harnessing-technology-version-7-0/

ebooksecure.com
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter
Blind Folio: i

Java ™

A Beginner’s Guide

Ninth Edition

00-FM.indd 1 12/11/21 9:20 PM


BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter
Blind Folio: ii

About the Author


Best-selling author Herbert Schildt has written extensively
about programming for over three decades and is a leading
authority on the Java language. Called “one of the world’s
foremost authors of books about programming” by
International Developer magazine, his books have sold millions
of copies worldwide and have been translated into all major
foreign languages. He is the author of numerous books on Java,
including Java: The Complete Reference; Herb Schildt’s Java
Programming Cookbook; Introducing JavaFX 8 Programming;
and Swing: A Beginner’s Guide. He has also written extensively
about C, C++, and C#. Featured as one of the rock star
programmers in Ed Burns’ book Secrets of the Rock Star
Programmers: Riding the IT Crest, Schildt is interested in
all facets of computing, but his primary focus is computer
languages. Schildt holds both BA and MCS degrees from the
University of Illinois. His website is www.HerbSchildt.com.

About the Technical Editor


Dr. Danny Coward has worked on all editions of the Java
platform. He led the definition of Java Servlets into the first
version of the Java EE platform and beyond, web services
into the Java ME platform, and the strategy and planning for
Java SE 7. He founded JavaFX technology and, most recently,
designed the largest addition to the Java EE 7 standard, the
Java WebSocket API. From coding in Java, to designing
APIs with industry experts, to serving for several years as an
executive to the Java Community Process, he has a uniquely
broad perspective into multiple aspects of Java technology. In
addition, he is the author of two books on Java programming:
Java WebSocket Programming and Java EE 7: The Big Picture.
Most recently, he has been applying his knowledge of Java
to helping scale massive Java-based services for one of the
world’s most successful software companies. Dr. Coward holds
a bachelor’s, master’s, and doctorate in mathematics from the
University of Oxford.

00-FM.indd 2 12/11/21 9:20 PM


BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter
Blind Folio: iii

Java ™

A Beginner’s Guide

Ninth Edition
Herbert Schildt

New York Chicago San Francisco


Athens London Madrid Mexico City
Milan New Delhi Singapore Sydney Toronto

00-FM.indd 3 12/11/21 9:20 PM


Copyright © 2022 by McGraw Hill. All rights reserved. Except as permitted under the United States Copyright Act of 1976, no
part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval sys-
tem, without the prior written permission of the publisher, with the exception that the program listings may be entered, stored,
and executed in a computer system, but they may not be reproduced for publication.

ISBN: 978-1-26-046356-9
MHID: 1-26-046356-7

The material in this eBook also appears in the print version of this title: ISBN: 978-1-26-046355-2,
MHID: 1-26-046355-9.

eBook conversion by codeMantra


Version 1.0

All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a
trademarked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of
infringement of the trademark. Where such designations appear in this book, they have been printed with initial caps.

McGraw-Hill Education eBooks are available at special quantity discounts to use as premiums and sales promotions or for
use in corporate training programs. To contact a representative, please visit the Contact Us page at www.mhprofessional.com.

Information has been obtained by McGraw Hill from sources believed to be reliable. However, because of the possibility of
human or mechanical error by our sources, McGraw Hill, or others, McGraw Hill does not guarantee the accuracy, adequacy,
or completeness of any information and is not responsible for any errors or omissions or the results obtained from the use of
such information.

Oracle Corporation does not make any representations or warranties as to the accuracy, adequacy, or completeness of any in-
formation contained in this Work, and is not responsible for any errors or omissions.

TERMS OF USE

This is a copyrighted work and McGraw-Hill Education and its licensors reserve all rights in and to the work. Use of this work
is subject to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the
work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit,
distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill Education’s prior consent.
You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited. Your
right to use the work may be terminated if you fail to comply with these terms.

THE WORK IS PROVIDED “AS IS.” McGRAW-HILL EDUCATION AND ITS LICENSORS MAKE NO GUARANTEES
OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED
FROM USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK
VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, IN-
CLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICU-
LAR PURPOSE. McGraw-Hill Education and its licensors do not warrant or guarantee that the functions contained in the
work will meet your requirements or that its operation will be uninterrupted or error free. Neither McGraw-Hill Education
nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work
or for any damages resulting therefrom. McGraw-Hill Education has no responsibility for the content of any information ac-
cessed through the work. Under no circumstances shall McGraw-Hill Education and/or its licensors be liable for any indirect,
incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even if
any of them has been advised of the possibility of such damages. This limitation of liability shall apply to any claim or cause
whatsoever whether such claim or cause arises in contract, tort or otherwise.
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter

Contents
INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii

1 Java Fundamentals ........................................................................................... 1


The History and Philosophy of Java ................................................................................ 3
The Origins of Java ................................................................................................ 3
Java’s Lineage: C and C++ .................................................................................... 4
How Java Impacted the Internet ............................................................................ 4
Java’s Magic: The Bytecode .................................................................................. 6
Moving Beyond Applets ........................................................................................ 8
A Faster Release Schedule ..................................................................................... 8
The Java Buzzwords .............................................................................................. 9
Object-Oriented Programming ........................................................................................ 10
Encapsulation ......................................................................................................... 11
Polymorphism ........................................................................................................ 11
Inheritance ............................................................................................................. 12
The Java Development Kit .............................................................................................. 12
A First Simple Program ................................................................................................... 13
Entering the Program ............................................................................................. 14
Compiling the Program .......................................................................................... 14
The First Sample Program Line by Line ............................................................... 15

00-FM.indd 5 12/11/21 9:20 PM


BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter

vi Java: A Beginner’s Guide

Handling Syntax Errors ................................................................................................... 17


A Second Simple Program .............................................................................................. 18
Another Data Type .......................................................................................................... 20
Try This 1-1: Converting Gallons to Liters ..................................................................... 21
Two Control Statements .................................................................................................. 22
The if Statement ..................................................................................................... 23
The for Loop .......................................................................................................... 24
Create Blocks of Code ..................................................................................................... 26
Semicolons and Positioning ............................................................................................ 27
Indentation Practices ....................................................................................................... 28
Try This 1-2: Improving the Gallons-to-Liters Converter ............................................... 28
The Java Keywords .......................................................................................................... 29
Identifiers in Java ............................................................................................................. 30
The Java Class Libraries .................................................................................................. 31
Chapter 1 Self Test .......................................................................................................... 31
2 Introducing Data Types and Operators ......................................................... 33
Why Data Types Are Important ....................................................................................... 34
Java’s Primitive Types ..................................................................................................... 34
Integers .................................................................................................................. 35
Floating-Point Types .............................................................................................. 37
Characters .............................................................................................................. 37
The Boolean Type ............................................................................................................ 39
Try This 2-1: How Far Away Is the Lightning? ............................................................... 40
Literals ............................................................................................................................. 41
Hexadecimal, Octal, and Binary Literals ............................................................... 42
Character Escape Sequences .................................................................................. 42
String Literals ........................................................................................................ 43
A Closer Look at Variables .............................................................................................. 44
Initializing a Variable ............................................................................................. 44
Dynamic Initialization ........................................................................................... 45
The Scope and Lifetime of Variables .............................................................................. 45
Operators ......................................................................................................................... 48
Arithmetic Operators ....................................................................................................... 48
Increment and Decrement ...................................................................................... 49
Relational and Logical Operators .................................................................................... 50
Short-Circuit Logical Operators ...................................................................................... 52
The Assignment Operator ................................................................................................ 53
Shorthand Assignments ................................................................................................... 53
Type Conversion in Assignments .................................................................................... 55
Casting Incompatible Types ............................................................................................ 56
Operator Precedence ....................................................................................................... 58
Try This 2-2: Display a Truth Table for the Logical Operators ....................................... 59

00-FM.indd 6 12/11/21 9:20 PM


BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter

Contents vii

Expressions ...................................................................................................................... 60
Type Conversion in Expressions ............................................................................ 60
Spacing and Parentheses ........................................................................................ 62
Chapter 2 Self Test .......................................................................................................... 62
3 Program Control Statements .......................................................................... 65
Input Characters from the Keyboard ............................................................................... 66
The if Statement .............................................................................................................. 67
Nested ifs ......................................................................................................................... 69
The if-else-if Ladder ........................................................................................................ 70
The Traditional switch Statement .................................................................................... 71
Nested switch Statements ................................................................................................ 75
Try This 3-1: Start Building a Java Help System ............................................................ 75
The for Loop .................................................................................................................... 77
Some Variations on the for Loop ..................................................................................... 79
Missing Pieces ................................................................................................................. 80
The Infinite Loop ................................................................................................... 81
Loops with No Body ....................................................................................................... 81
Declaring Loop Control Variables Inside the for Loop ................................................... 82
The Enhanced for Loop ................................................................................................... 83
The while Loop ............................................................................................................... 83
The do-while Loop .......................................................................................................... 85
Try This 3-2: Improve the Java Help System .................................................................. 87
Use break to Exit a Loop ................................................................................................. 90
Use break as a Form of goto ............................................................................................ 91
Use continue .................................................................................................................... 96
Try This 3-3: Finish the Java Help System ..................................................................... 97
Nested Loops ................................................................................................................... 101
Chapter 3 Self Test .......................................................................................................... 102
4 Introducing Classes, Objects, and Methods ................................................... 105
Class Fundamentals ......................................................................................................... 106
The General Form of a Class ................................................................................. 107
Defining a Class ..................................................................................................... 108
How Objects Are Created ................................................................................................ 110
Reference Variables and Assignment .............................................................................. 111
Methods ........................................................................................................................... 112
Adding a Method to the Vehicle Class ................................................................... 112
Returning from a Method ................................................................................................ 114
Returning a Value ............................................................................................................ 115
Using Parameters ............................................................................................................. 117
Adding a Parameterized Method to Vehicle .......................................................... 119
Try This 4-1: Creating a Help Class ................................................................................ 121

00-FM.indd 7 12/11/21 9:20 PM


BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter

viii Java: A Beginner’s Guide

Constructors .................................................................................................................... 126


Parameterized Constructors ............................................................................................. 128
Adding a Constructor to the Vehicle Class ...................................................................... 128
The new Operator Revisited ............................................................................................ 130
Garbage Collection .......................................................................................................... 130
The this Keyword ............................................................................................................ 131
Chapter 4 Self Test .......................................................................................................... 133
5 More Data Types and Operators .................................................................... 135
Arrays .............................................................................................................................. 136
One-Dimensional Arrays ....................................................................................... 137
Try This 5-1: Sorting an Array ........................................................................................ 140
Multidimensional Arrays ................................................................................................. 142
Two-Dimensional Arrays ....................................................................................... 142
Irregular Arrays ...................................................................................................... 143
Arrays of Three or More Dimensions .................................................................... 144
Initializing Multidimensional Arrays ..................................................................... 144
Alternative Array Declaration Syntax ............................................................................. 145
Assigning Array References ............................................................................................ 146
Using the length Member ................................................................................................ 147
Try This 5-2: A Queue Class ........................................................................................... 149
The For-Each Style for Loop ........................................................................................... 153
Iterating Over Multidimensional Arrays ................................................................ 156
Applying the Enhanced for .................................................................................... 157
Strings .............................................................................................................................. 158
Constructing Strings .............................................................................................. 159
Operating on Strings .............................................................................................. 160
Arrays of Strings .................................................................................................... 162
Strings Are Immutable ........................................................................................... 162
Using a String to Control a switch Statement ........................................................ 163
Using Command-Line Arguments ................................................................................... 166
Using Type Inference with Local Variables ..................................................................... 167
Local Variable Type Inference with Reference Types ........................................... 169
Using Local Variable Type Inference in a for Loop ............................................... 171
Some var Restrictions ............................................................................................ 171
The Bitwise Operators ..................................................................................................... 172
The Bitwise AND, OR, XOR, and NOT Operators ............................................... 173
The Shift Operators ................................................................................................ 177
Bitwise Shorthand Assignments ............................................................................ 179
Try This 5-3: A ShowBits Class ...................................................................................... 180
The ? Operator ................................................................................................................. 182
Chapter 5 Self Test .......................................................................................................... 184

00-FM.indd 8 12/11/21 9:20 PM


BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter

Contents ix

6 A Closer Look at Methods and Classes .......................................................... 187


Controlling Access to Class Members ............................................................................ 188
Java’s Access Modifiers ......................................................................................... 189
Try This 6-1: Improving the Queue Class ....................................................................... 193
Pass Objects to Methods .................................................................................................. 194
How Arguments Are Passed ................................................................................... 196
Returning Objects ............................................................................................................ 198
Method Overloading ........................................................................................................ 200
Overloading Constructors ................................................................................................ 205
Try This 6-2: Overloading the Queue Constructor .......................................................... 207
Recursion ......................................................................................................................... 210
Understanding static ........................................................................................................ 212
Static Blocks .......................................................................................................... 215
Try This 6-3: The Quicksort ............................................................................................ 216
Introducing Nested and Inner Classes ............................................................................. 219
Varargs: Variable-Length Arguments .............................................................................. 222
Varargs Basics ........................................................................................................ 223
Overloading Varargs Methods ............................................................................... 226
Varargs and Ambiguity .......................................................................................... 227
Chapter 6 Self Test .......................................................................................................... 228
7 Inheritance ........................................................................................................ 231
Inheritance Basics ........................................................................................................... 232
Member Access and Inheritance ..................................................................................... 235
Constructors and Inheritance ........................................................................................... 238
Using super to Call Superclass Constructors .................................................................. 240
Using super to Access Superclass Members ................................................................... 244
Try This 7-1: Extending the Vehicle Class ...................................................................... 245
Creating a Multilevel Hierarchy ...................................................................................... 248
When Are Constructors Executed? .................................................................................. 250
Superclass References and Subclass Objects .................................................................. 252
Method Overriding .......................................................................................................... 256
Overridden Methods Support Polymorphism .................................................................. 259
Why Overridden Methods? ............................................................................................. 261
Applying Method Overriding to TwoDShape ........................................................ 261
Using Abstract Classes .................................................................................................... 265
Using final ....................................................................................................................... 269
final Prevents Overriding ....................................................................................... 269
final Prevents Inheritance ...................................................................................... 269
Using final with Data Members ............................................................................. 270
The Object Class ............................................................................................................. 271
Chapter 7 Self Test .......................................................................................................... 272

00-FM.indd 9 12/11/21 9:20 PM


Visit https://testbankfan.com
now to explore a rich
collection of testbank or
solution manual and enjoy
exciting offers!
BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter

x Java: A Beginner’s Guide

8 Packages and Interfaces .................................................................................. 275


Packages .......................................................................................................................... 276
Defining a Package ................................................................................................ 277
Finding Packages and CLASSPATH ..................................................................... 278
A Short Package Example ..................................................................................... 278
Packages and Member Access ......................................................................................... 280
A Package Access Example ................................................................................... 281
Understanding Protected Members ................................................................................. 282
Importing Packages ......................................................................................................... 284
Java’s Class Library Is Contained in Packages ............................................................... 286
Interfaces ......................................................................................................................... 286
Implementing Interfaces .................................................................................................. 287
Using Interface References ............................................................................................. 291
Try This 8-1: Creating a Queue Interface ........................................................................ 293
Variables in Interfaces ..................................................................................................... 298
Interfaces Can Be Extended ............................................................................................ 299
Default Interface Methods ............................................................................................... 300
Default Method Fundamentals .............................................................................. 301
A More Practical Example of a Default Method ................................................... 303
Multiple Inheritance Issues .................................................................................... 304
Use static Methods in an Interface .................................................................................. 305
Private Interface Methods ................................................................................................ 306
Final Thoughts on Packages and Interfaces .................................................................... 307
Chapter 8 Self Test .......................................................................................................... 307
9 Exception Handling .......................................................................................... 309
The Exception Hierarchy ................................................................................................ 311
Exception Handling Fundamentals ................................................................................. 311
Using try and catch ................................................................................................ 312
A Simple Exception Example ................................................................................ 312
The Consequences of an Uncaught Exception ................................................................ 314
Exceptions Enable You to Handle Errors Gracefully ............................................. 316
Using Multiple catch Statements ..................................................................................... 317
Catching Subclass Exceptions ......................................................................................... 318
Try Blocks Can Be Nested .............................................................................................. 319
Throwing an Exception ................................................................................................... 320
Rethrowing an Exception ....................................................................................... 321
A Closer Look at Throwable ........................................................................................... 322
Using finally .................................................................................................................... 324
Using throws .................................................................................................................... 326
Three Additional Exception Features .............................................................................. 327
Java’s Built-in Exceptions ............................................................................................... 329
Creating Exception Subclasses ........................................................................................ 331
Try This 9-1: Adding Exceptions to the Queue Class ..................................................... 333
Chapter 9 Self Test .......................................................................................................... 337

00-FM.indd 10 12/11/21 9:20 PM


BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter

Contents xi

10 Using I/O ........................................................................................................... 339


Java’s I/O Is Built upon Streams ..................................................................................... 341
Byte Streams and Character Streams .............................................................................. 341
The Byte Stream Classes ................................................................................................. 341
The Character Stream Classes ......................................................................................... 342
The Predefined Streams ................................................................................................... 343
Using the Byte Streams ................................................................................................... 344
Reading Console Input .......................................................................................... 345
Writing Console Output ......................................................................................... 346
Reading and Writing Files Using Byte Streams .............................................................. 347
Inputting from a File .............................................................................................. 347
Writing to a File ..................................................................................................... 351
Automatically Closing a File ........................................................................................... 353
Reading and Writing Binary Data ................................................................................... 356
Try This 10-1: A File Comparison Utility ....................................................................... 359
Random-Access Files ...................................................................................................... 360
Using Java’s Character-Based Streams ........................................................................... 362
Console Input Using Character Streams ................................................................ 364
Console Output Using Character Streams ............................................................. 368
File I/O Using Character Streams ................................................................................... 369
Using a FileWriter ................................................................................................. 369
Using a FileReader ................................................................................................ 370
Using Java’s Type Wrappers to Convert Numeric Strings .............................................. 372
Try This 10-2: Creating a Disk-Based Help System ....................................................... 374
Chapter 10 Self Test ........................................................................................................ 381
11 Multithreaded Programming .......................................................................... 383
Multithreading Fundamentals ......................................................................................... 384
The Thread Class and Runnable Interface ...................................................................... 385
Creating a Thread ............................................................................................................ 386
One Improvement and Two Simple Variations ...................................................... 389
Try This 11-1: Extending Thread .................................................................................... 393
Creating Multiple Threads ............................................................................................... 396
Determining When a Thread Ends .................................................................................. 399
Thread Priorities .............................................................................................................. 402
Synchronization ............................................................................................................... 406
Using Synchronized Methods ......................................................................................... 406
The synchronized Statement ........................................................................................... 409
Thread Communication Using notify( ), wait( ), and notifyAll( ) .................................. 412
An Example That Uses wait( ) and notify( ) .......................................................... 413
Suspending, Resuming, and Stopping Threads ............................................................... 418
Try This 11-2: Using the Main Thread ............................................................................ 422
Chapter 11 Self Test ........................................................................................................ 424

00-FM.indd 11 12/11/21 9:20 PM


BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter

xii Java: A Beginner’s Guide

12 Enumerations, Autoboxing, Annotations, and More ..................................... 425


Enumerations ................................................................................................................... 426
Enumeration Fundamentals ................................................................................... 427
Java Enumerations Are Class Types ................................................................................ 429
The values( ) and valueOf( ) Methods ............................................................................. 429
Constructors, Methods, Instance Variables, and Enumerations ...................................... 431
Two Important Restrictions ................................................................................... 433
Enumerations Inherit Enum ............................................................................................ 433
Try This 12-1: A Computer-Controlled Traffic Light ..................................................... 435
Autoboxing ...................................................................................................................... 440
Type Wrappers ................................................................................................................. 440
Autoboxing Fundamentals .............................................................................................. 442
Autoboxing and Methods ................................................................................................ 443
Autoboxing/Unboxing Occurs in Expressions ................................................................ 445
A Word of Warning ................................................................................................ 446
Static Import .................................................................................................................... 447
Annotations (Metadata) ................................................................................................... 450
Introducing instanceof ..................................................................................................... 453
Chapter 12 Self Test ........................................................................................................ 455
13 Generics ............................................................................................................. 457
Generics Fundamentals ................................................................................................... 458
A Simple Generics Example ........................................................................................... 459
Generics Work Only with Reference Types ........................................................... 463
Generic Types Differ Based on Their Type Arguments ......................................... 463
A Generic Class with Two Type Parameters .......................................................... 464
The General Form of a Generic Class ................................................................... 465
Bounded Types ................................................................................................................ 466
Using Wildcard Arguments ............................................................................................. 469
Bounded Wildcards ......................................................................................................... 472
Generic Methods ............................................................................................................. 475
Generic Constructors ....................................................................................................... 477
Generic Interfaces ............................................................................................................ 478
Try This 13-1: Create a Generic Queue .......................................................................... 480
Raw Types and Legacy Code .......................................................................................... 485
Type Inference with the Diamond Operator .................................................................... 488
Local Variable Type Inference and Generics ................................................................... 489
Erasure ............................................................................................................................. 489
Ambiguity Errors ............................................................................................................. 490
Some Generic Restrictions .............................................................................................. 491
Type Parameters Can’t Be Instantiated .................................................................. 491
Restrictions on Static Members ............................................................................. 491
Generic Array Restrictions .................................................................................... 492
Generic Exception Restriction ............................................................................... 493

00-FM.indd 12 12/11/21 9:20 PM


BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter

Contents xiii

Continuing Your Study of Generics ................................................................................. 493


Chapter 13 Self Test ........................................................................................................ 493
14 Lambda Expressions and Method References ................................................ 495
Introducing Lambda Expressions .................................................................................... 496
Lambda Expression Fundamentals ........................................................................ 497
Functional Interfaces ............................................................................................. 498
Lambda Expressions in Action .............................................................................. 500
Block Lambda Expressions ............................................................................................. 505
Generic Functional Interfaces ......................................................................................... 506
Try This 14-1: Pass a Lambda Expression as an Argument ............................................ 508
Lambda Expressions and Variable Capture ..................................................................... 513
Throw an Exception from Within a Lambda Expression ................................................ 514
Method References .......................................................................................................... 516
Method References to static Methods .................................................................... 516
Method References to Instance Methods ............................................................... 518
Constructor References ................................................................................................... 522
Predefined Functional Interfaces ..................................................................................... 525
Chapter 14 Self Test ........................................................................................................ 527
15 Modules ............................................................................................................. 529
Module Basics ................................................................................................................. 531
A Simple Module Example ................................................................................... 532
Compile and Run the First Module Example ........................................................ 536
A Closer Look at requires and exports ................................................................. 537
java.base and the Platform Modules ................................................................................ 538
Legacy Code and the Unnamed Module ......................................................................... 540
Exporting to a Specific Module ....................................................................................... 541
Using requires transitive .................................................................................................. 542
Try This 15-1: Experiment with requires transitive ........................................................ 543
Use Services .................................................................................................................... 546
Service and Service Provider Basics ..................................................................... 547
The Service-Based Keywords ................................................................................ 548
A Module-Based Service Example ........................................................................ 548
Additional Module Features ............................................................................................ 555
Open Modules ........................................................................................................ 555
The opens Statement .............................................................................................. 556
requires static ......................................................................................................... 556
Continuing Your Study of Modules ................................................................................. 556
Chapter 15 Self Test ........................................................................................................ 557
16 Switch Expressions, Records, and Other Recently Added Features ........... 559
Enhancements to switch .................................................................................................. 561
Use a List of case Constants .................................................................................. 563
Introducing the switch Expression and the yield Statement .................................. 563

00-FM.indd 13 12/11/21 9:20 PM


BeginNew-Tight5.5 / Java: A Beginner’s Guide, Ninth Edition / Herbert Schildt / 355-9 / Front Matter

xiv Java: A Beginner’s Guide

Introducing the Arrow in a case Statement ............................................................ 565


A Closer Look at the Arrow case ........................................................................... 567
Try This 16-1: Use a switch Expression to Obtain a City’s Time Zone .......................... 571
Records ............................................................................................................................ 573
Record Basics ........................................................................................................ 574
Create Record Constructors ................................................................................... 576
A Closer Look at Record Getter Methods ............................................................. 581
Pattern Matching with instanceof .................................................................................... 581
Sealed Classes and Interfaces .......................................................................................... 583
Sealed Classes ........................................................................................................ 583
Sealed Interfaces .................................................................................................... 586
Future Directions ............................................................................................................. 587
Chapter 16 Self Test ........................................................................................................ 588
17 Introducing Swing ............................................................................................ 591
The Origins and Design Philosophy of Swing ................................................................ 593
Components and Containers ............................................................................................ 595
Components ........................................................................................................... 595
Containers .............................................................................................................. 596
The Top-Level Container Panes ............................................................................. 596
Layout Managers ............................................................................................................. 597
A First Simple Swing Program ....................................................................................... 597
The First Swing Example Line by Line ................................................................. 599
Swing Event Handling ..................................................................................................... 602
Events .................................................................................................................... 603
Event Sources ........................................................................................................ 603
Event Listeners ...................................................................................................... 603
Event Classes and Listener Interfaces ................................................................... 604
Use JButton ..................................................................................................................... 604
Work with JTextField ...................................................................................................... 608
Create a JCheckBox ........................................................................................................ 611
Work with JList ............................................................................................................... 615
Try This 17-1: A Swing-Based File Comparison Utility ................................................. 619
Use Anonymous Inner Classes or Lambda Expressions to Handle Events ..................... 624
Chapter 17 Self Test ................................................................................................... 626
A Answers to Self Tests ........................................................................................ 627
Chapter 1: Java Fundamentals ......................................................................................... 628
Chapter 2: Introducing Data Types and Operators .......................................................... 630
Chapter 3: Program Control Statements .......................................................................... 631
Chapter 4: Introducing Classes, Objects, and Methods .................................................. 634
Chapter 5: More Data Types and Operators .................................................................... 635
Chapter 6: A Closer Look at Methods and Classes ......................................................... 640
Chapter 7: Inheritance ..................................................................................................... 645

00-FM.indd 14 12/11/21 9:20 PM


Exploring the Variety of Random
Documents with Different Content
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project
Gutenberg™ works in compliance with the terms of this
agreement for keeping the Project Gutenberg™ name
associated with the work. You can easily comply with the terms
of this agreement by keeping this work in the same format with
its attached full Project Gutenberg™ License when you share it
without charge with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:

This eBook is for the use of anyone anywhere in the United


States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it
away or re-use it under the terms of the Project Gutenberg
License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country where
you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is


derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of the
copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is


posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files
containing a part of this work or any other work associated with
Project Gutenberg™.
1.E.5. Do not copy, display, perform, distribute or redistribute
this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must, at
no additional cost, fee or expense to the user, provide a copy, a
means of exporting a copy, or a means of obtaining a copy upon
request, of the work in its original “Plain Vanilla ASCII” or other
form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt that
s/he does not agree to the terms of the full Project Gutenberg™
License. You must require such a user to return or destroy all
copies of the works possessed in a physical medium and
discontinue all use of and all access to other copies of Project
Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project


Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite
these efforts, Project Gutenberg™ electronic works, and the
medium on which they may be stored, may contain “Defects,”
such as, but not limited to, incomplete, inaccurate or corrupt
data, transcription errors, a copyright or other intellectual
property infringement, a defective or damaged disk or other
medium, a computer virus, or computer codes that damage or
cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES -


Except for the “Right of Replacement or Refund” described in
paragraph 1.F.3, the Project Gutenberg Literary Archive
Foundation, the owner of the Project Gutenberg™ trademark,
and any other party distributing a Project Gutenberg™ electronic
work under this agreement, disclaim all liability to you for
damages, costs and expenses, including legal fees. YOU
AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE,
STRICT LIABILITY, BREACH OF WARRANTY OR BREACH
OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE
TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER
THIS AGREEMENT WILL NOT BE LIABLE TO YOU FOR
ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE
OR INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF
THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If


you discover a defect in this electronic work within 90 days of
receiving it, you can receive a refund of the money (if any) you
paid for it by sending a written explanation to the person you
received the work from. If you received the work on a physical
medium, you must return the medium with your written
explanation. The person or entity that provided you with the
defective work may elect to provide a replacement copy in lieu
of a refund. If you received the work electronically, the person or
entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund.
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set


forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO
WARRANTIES OF MERCHANTABILITY OR FITNESS FOR
ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you do
or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.

Section 2. Information about the Mission of


Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new
computers. It exists because of the efforts of hundreds of
volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project
Gutenberg™’s goals and ensuring that the Project Gutenberg™
collection will remain freely available for generations to come. In
2001, the Project Gutenberg Literary Archive Foundation was
created to provide a secure and permanent future for Project
Gutenberg™ and future generations. To learn more about the
Project Gutenberg Literary Archive Foundation and how your
efforts and donations can help, see Sections 3 and 4 and the
Foundation information page at www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-
profit 501(c)(3) educational corporation organized under the
laws of the state of Mississippi and granted tax exempt status by
the Internal Revenue Service. The Foundation’s EIN or federal
tax identification number is 64-6221541. Contributions to the
Project Gutenberg Literary Archive Foundation are tax
deductible to the full extent permitted by U.S. federal laws and
your state’s laws.

The Foundation’s business office is located at 809 North 1500


West, Salt Lake City, UT 84116, (801) 596-1887. Email contact
links and up to date contact information can be found at the
Foundation’s website and official page at
www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission
of increasing the number of public domain and licensed works
that can be freely distributed in machine-readable form
accessible by the widest array of equipment including outdated
equipment. Many small donations ($1 to $5,000) are particularly
important to maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws


regulating charities and charitable donations in all 50 states of
the United States. Compliance requirements are not uniform
and it takes a considerable effort, much paperwork and many
fees to meet and keep up with these requirements. We do not
solicit donations in locations where we have not received written
confirmation of compliance. To SEND DONATIONS or
determine the status of compliance for any particular state visit
www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states


where we have not met the solicitation requirements, we know
of no prohibition against accepting unsolicited donations from
donors in such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot


make any statements concerning tax treatment of donations
received from outside the United States. U.S. laws alone swamp
our small staff.

Please check the Project Gutenberg web pages for current


donation methods and addresses. Donations are accepted in a
number of other ways including checks, online payments and
credit card donations. To donate, please visit:
www.gutenberg.org/donate.

Section 5. General Information About Project


Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could
be freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose
network of volunteer support.

Project Gutenberg™ eBooks are often created from several


printed editions, all of which are confirmed as not protected by
copyright in the U.S. unless a copyright notice is included. Thus,
we do not necessarily keep eBooks in compliance with any
particular paper edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg
Literary Archive Foundation, how to help produce our new
eBooks, and how to subscribe to our email newsletter to hear
about new eBooks.

You might also like