24777
24777
com
https://textbookfull.com/product/java-a-beginners-guide-7th-
edition-herbert-schildt/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/java-a-beginners-guide-eighth-
edition-herbert-schildt/
textboxfull.com
https://textbookfull.com/product/java-the-complete-reference-eleventh-
edition-herbert-schildt/
textboxfull.com
https://textbookfull.com/product/java-for-dummies-7th-edition-barry-a-
burd/
textboxfull.com
https://textbookfull.com/product/the-shorttube-80-telescope-a-user-s-
guide-neil-t-english/
textboxfull.com
Java in a Nutshell A Desktop Quick Reference 7th Edition
Benjamin J. Evans
https://textbookfull.com/product/java-in-a-nutshell-a-desktop-quick-
reference-7th-edition-benjamin-j-evans/
textboxfull.com
https://textbookfull.com/product/outgrowing-god-a-beginner-s-guide-
richard-dawkins/
textboxfull.com
https://textbookfull.com/product/linux-administration-a-beginner-s-
guide-wale-soyinka/
textboxfull.com
https://textbookfull.com/product/becoming-a-programmer-a-beginner-s-
guide-1st-edition-paul-mabry/
textboxfull.com
https://textbookfull.com/product/beginning-c-from-beginner-to-pro-7th-
edition-gonzalez-morris/
textboxfull.com
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. 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#. Although interested in all facets of computing, his
primary focus is computer languages. Schildt holds both graduate and undergraduate
degrees from the University of Illinois. His website is www.HerbSchildt.com.
ISBN: 978-1-25-958932-4
MHID: 1-25-958932-3.
The material in this eBook also appears in the print version of this title: ISBN: 978-
1-25-958931-7, MHID: 1-25-958931-5.
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.
Oracle and Java are registered trademarks of Oracle Corporation and/or its affiliates.
All other trademarks are the property of their respective owners, and McGraw-Hill
Education makes no claim of ownership by the mention of products that contain
these marks.
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.
INTRODUCTION
1 Java Fundamentals
The Origins of Java
Java’s Lineage: C and C++
How Java Impacted the Internet
Java Simplified Web-Based Programming
Java Applets
Security
Portability
Java’s Magic: The Bytecode
Moving Beyond Applets
The Java Buzzwords
Object-Oriented Programming
Encapsulation
Polymorphism
Inheritance
Obtaining the Java Development Kit
A First Simple Program
Entering the Program
Compiling the Program
The First Sample Program Line by Line
Handling Syntax Errors
A Second Simple Program
Another Data Type
Try This 1-1: Converting Gallons to Liters
Two Control Statements
The if Statement
The for Loop
Create Blocks of Code
Semicolons and Positioning
Indentation Practices
Try This 1-2: Improving the Gallons-to-Liters Converter
The Java Keywords
Identifiers in Java
The Java Class Libraries
Chapter 1 Self Test
7 Inheritance
Inheritance Basics
Member Access and Inheritance
Constructors and Inheritance
Using super to Call Superclass Constructors
Using super to Access Superclass Members
Try This 7-1: Extending the Vehicle Class
Creating a Multilevel Hierarchy
When Are Constructors Executed?
Superclass References and Subclass Objects
Method Overriding
Overridden Methods Support Polymorphism
Why Overridden Methods?
Applying Method Overriding to TwoDShape
Using Abstract Classes
Using final
final Prevents Overriding
final Prevents Inheritance
Using final with Data Members
The Object Class
Chapter 7 Self Test
9 Exception Handling
The Exception Hierarchy
Exception Handling Fundamentals
Using try and catch
A Simple Exception Example
The Consequences of an Uncaught Exception
Exceptions Enable You to Handle Errors Gracefully
Using Multiple catch Statements
Catching Subclass Exceptions
Try Blocks Can Be Nested
Throwing an Exception
Rethrowing an Exception
A Closer Look at Throwable
Using finally
Using throws
Three Additional Exception Features
Java’s Built-in Exceptions
Creating Exception Subclasses
Try This 9-1: Adding Exceptions to the Queue Class
Chapter 9 Self Test
10 Using I/O
Java’s I/O Is Built upon Streams
Byte Streams and Character Streams
The Byte Stream Classes
The Character Stream Classes
The Predefined Streams
Using the Byte Streams
Reading Console Input
Writing Console Output
Reading and Writing Files Using Byte Streams
Inputting from a File
Writing to a File
Automatically Closing a File
Reading and Writing Binary Data
Try This 10-1: A File Comparison Utility
Random-Access Files
Using Java’s Character-Based Streams
Console Input Using Character Streams
Console Output Using Character Streams
File I/O Using Character Streams
Using a FileWriter
Using a FileReader
Using Java’s Type Wrappers to Convert Numeric Strings
Try This 10-2: Creating a Disk-Based Help System
Chapter 10 Self Test
11 Multithreaded Programming
Multithreading Fundamentals
The Thread Class and Runnable Interface
Creating a Thread
One Improvement and Two Simple Variations
Try This 11-1: Extending Thread
Creating Multiple Threads
Determining When a Thread Ends
Thread Priorities
Synchronization
Using Synchronized Methods
The synchronized Statement
Thread Communication Using notify( ), wait( ), and notifyAll( )
An Example That Uses wait( ) and notify( )
Suspending, Resuming, and Stopping Threads
Try This 11-2: Using the Main Thread
Chapter 11 Self Test
13 Generics
Generics Fundamentals
A Simple Generics Example
Generics Work Only with Reference Types
Generic Types Differ Based on Their Type Arguments
A Generic Class with Two Type Parameters
The General Form of a Generic Class
Bounded Types
Using Wildcard Arguments
Bounded Wildcards
Generic Methods
Generic Constructors
Generic Interfaces
Try This 13-1: Create a Generic Queue
Raw Types and Legacy Code
Type Inference with the Diamond Operator
Erasure
Ambiguity Errors
Some Generic Restrictions
Type Parameters Can’t Be Instantiated
Restrictions on Static Members
Generic Array Restrictions
Generic Exception Restriction
Continuing Your Study of Generics
Chapter 13 Self Test
15 Modules
Module Basics
A Simple Module Example
Compile and Run the First Module Example
A Closer Look at requires and exports
java.base and the Platform Modules
Legacy Code and the Unnamed Module
Exporting to a Specific Module
Using requires transitive
Try This 15-1: Experiment with requires transitive
Use Services
Service and Service Provider Basics
The Service-Based Keywords
A Module-Based Service Example
Additional Module Features
Open Modules
The opens Statement
requires static
Continuing Your Study of Modules
Chapter 15 Self Test
16 Introducing Swing
The Origins and Design Philosophy of Swing
Components and Containers
Components
Containers
The Top-Level Container Panes
Layout Managers
A First Simple Swing Program
The First Swing Example Line by Line
Swing Event Handling
Events
Event Sources
Event Listeners
Event Classes and Listener Interfaces
Use JButton
Work with JTextField
Create a JCheckBox
Work with JList
Try This 16-1: A Swing-Based File Comparison Utility
Use Anonymous Inner Classes or Lambda Expressions to Handle Events
Chapter 16 Self Test
17 Introducing JavaFX
JavaFX Basic Concepts
The JavaFX Packages
The Stage and Scene Classes
Nodes and Scene Graphs
Layouts
The Application Class and the Life-cycle Methods
Launching a JavaFX Application
A JavaFX Application Skeleton
Compiling and Running a JavaFX Program
The Application Thread
A Simple JavaFX Control: Label
Using Buttons and Events
Event Basics
Introducing the Button Control
Demonstrating Event Handling and the Button
Three More JavaFX Controls
CheckBox
Try This 17-1: Use the CheckBox Indeterminate State
ListView
TextField
Introducing Effects and Transforms
Effects
Transforms
Demonstrating Effects and Transforms
What Next?
Chapter 17 Self Test
D Introducing JShell
JShell Basics
List, Edit, and Rerun Code
Add a Method
Create a Class
Use an Interface
Evaluate Expressions and Use Built-in Variables
Importing Packages
Exceptions
Some More JShell Commands
Exploring JShell Further
Index
Introduction
T
he purpose of this book is to teach you the fundamentals of Java programming.
It uses a step-by-step approach complete with numerous examples, self tests,
and projects. It assumes no previous programming experience. The book starts
with the basics, such as how to compile and run a Java program. It then discusses the
keywords, features, and constructs that form the core of the Java language. You’ll
also find coverage of some of Java’s most advanced features, including
multithreaded programming, generics, lambda expressions, and modules. An
introduction to the fundamentals of Swing and JavaFX concludes the book. By the
time you finish, you will have a firm grasp of the essentials of Java programming.
It is important to state at the outset that this book is just a starting point. Java is
more than just the elements that define the language. Java also includes extensive
libraries and tools that aid in the development of programs. To be a top-notch Java
programmer implies mastery of these areas, too. After completing this book, you will
have the knowledge to pursue any and all other aspects of Java.
Generics
Autoboxing/unboxing
Enumerations
The enhanced “for-each” style for loop
Variable-length arguments (varargs)
Static import
Annotations
This is not a list of minor tweaks or incremental upgrades. Each item in the list
represents a significant addition to the Java language. Some, such as generics, the
enhanced for loop, and varargs, introduced new syntax elements. Others, such as
autoboxing and auto-unboxing, altered the semantics of the language. Annotations
added an entirely new dimension to programming.
The importance of these new features is reflected in the use of the version number
“5.” The next version number for Java would normally have been 1.5. However, the
new features were so significant that a shift from 1.4 to 1.5 just didn’t seem to
express the magnitude of the change. Instead, Sun elected to increase the version
number to 5 as a way of emphasizing that a major event was taking place. Thus, it
was named J2SE 5, and the Java Development Kit (JDK) was called JDK 5. In order
to maintain consistency, however, Sun decided to use 1.5 as its internal version
number, which is also referred to as the developer version number. The “5” in J2SE
5 is called the product version number.
The next release of Java was called Java SE 6, and Sun once again decided to
change the name of the Java platform. First, notice that the “2” has been dropped.
Thus, the platform now had the name Java SE, and the official product name was
Java Platform, Standard Edition 6, with the development kit being called JDK 6. As
with J2SE 5, the 6 in Java SE 6 is the product version number. The internal,
developer version number is 1.6.
Java SE 6 built on the base of J2SE 5, adding incremental improvements. Java SE
6 added no major features to the Java language proper, but it did enhance the API
libraries, added several new packages, and offered improvements to the run time. It
also went through several updates during its long (in Java terms) life cycle, with
several upgrades added along the way. In general, Java SE 6 served to further
solidify the advances made by J2SE 5.
The next release of Java was called Java SE 7, with the development kit being
called JDK 7. It has an internal version number of 1.7. Java SE 7 was the first major
release of Java after Sun Microsystems was acquired by Oracle. Java SE 7 added
several new features, including significant additions to the language and the API
libraries. Some of the most important features added by Java SE 7 were those
developed as part of Project Coin. The purpose of Project Coin was to identify a
number of small changes to the Java language that would be incorporated into JDK
7, including
As you can see, even though the Project Coin features were considered to be small
changes to the language, their benefits were much larger than the qualifier “small”
would suggest. In particular, the try-with-resources statement profoundly affects the
way that a substantial amount of code is written.
The next release of Java was Java SE 8, with the development kit being called
JDK 8. It has an internal version number of 1.8. JDK 8 represented a very significant
upgrade to the Java language because of the inclusion of a far-reaching new
language feature: the lambda expression. The impact of lambda expressions was, and
continues to be, quite profound, changing both the way that programming solutions
are conceptualized and how Java code is written. In the process, lambda expressions
can simplify and reduce the amount of source code needed to create certain
constructs. The addition of lambda expressions also caused a new operator (the –>)
and a new syntax element to be added to the language.
In addition to lambda expressions, JDK 8 added many other important new
features. For example, beginning with JDK 8, it is now possible to define a default
implementation for a method specified by an interface. JDK 8 also bundled support
for JavaFX, Java’s new GUI framework. JavaFX is expected to soon play an
important part in nearly all Java applications, ultimately replacing Swing for most
GUI-based projects. In the final analysis, Java SE 8 was a major release that
profoundly expanded the capabilities of the language and changed the way that Java
code is written.
Java SE 9
The newest release of Java is Java SE 9. The developer’s kit is called JDK 9. With
the release of JDK 9, the internal version number is also 9. JDK 9 represents a major
Java release, incorporating significant enhancements to both the Java language and
its libraries. The primary new feature is modules, which enable you to specify the
relationships and dependencies of the code that comprises an application. Modules
also add another dimension to Java’s access control features. The inclusion of
modules caused a new syntax element, several new keywords, and various tool
enhancements to be added to Java. Modules also have a profound effect on the API
library because, beginning with JDK 9, the library packages are now organized into
modules.
In addition to modules, JDK 9 includes several other new features. One of
particular interest is JShell, which is a tool that supports interactive program
experimentation and learning. (An introduction to JShell is found in Appendix D.)
Another interesting upgrade is support for private interface methods. Their inclusion
further enhances JDK 8’s support for default methods in interfaces. JDK 9 adds a
search feature to the javadoc tool and a new tag called @index to support it. As with
previous releases, JDK 9 contains a number of updates and enhancements to Java’s
API libraries.
As a general rule, in any Java release, it is the new features that receive the most
attention. However, there is one high-profile aspect of Java that is deprecated by
JDK 9: applets. Beginning with JDK 9, applets are no longer recommended for new
projects. As will be explained in greater detail in Chapter 1, because of waning
browser support for applets (and other factors), JDK 9 deprecates the entire applet
API. At this time, the use of Java Web Start is recommended for deploying
applications over the Internet. (An introduction to Java Web Start is found in
Appendix C.) Because applets are being phased out and not recommended for new
code, they are no longer discussed in this book. However, readers interested in
applets will find coverage of them in previous editions of this book.
In the final analysis, JDK 9 continues Java’s legacy of innovation, ensuring that
Java remains the vibrant, nimble language that the programming world has come to
expect. The material in this book has been updated to reflect Java SE 9 (JDK 9), with
many new features, updates, and additions indicated throughout.
Self Test
Each chapter concludes with a Self Test that lets you test your knowledge. The
answers are in Appendix A.
Required Software
To compile and run all of the programs in this book, you will need the latest Java
Development Kit (JDK) from Oracle, which, at the time of this writing, is JDK 9.
This is the JDK for Java SE 9. Instructions for obtaining the Java JDK are given in
Chapter 1.
If you are using an earlier version of Java, you will still be able to use this book,
but you won’t be able to compile and run the programs that use Java’s newer
features.
Special Thanks
Special thanks to Danny Coward, the technical editor for this edition of the book.
Danny has worked on several of my books, and his advice, insights, and suggestions
have always been of great value and much appreciated.
I
n computing, few technologies have had the impact of Java. Its creation in the
early days of the Web helped shape the modern form of the Internet, including
both the client and server sides. Its innovative features advanced the art and
science of programming, setting a new standard in computer language design. The
forward-thinking culture that grew up around Java ensured it would remain vibrant
and alive, adapting to the often rapid and varied changes in the computing landscape.
Simply put: not only is Java one of the world’s most important computer languages,
it is a force that revolutionized programming and, in the process, changed the world.
Although Java is a language often associated with Internet programming, it is by
no means limited in that regard. Java is a powerful, full-featured, general-purpose
programming language. Thus, if you are new to programming, Java is an excellent
language to learn. Moreover, to be a professional programmer today implies the
ability to program in Java—it is that important. In the course of this book, you will
learn the basic skills that will help you master it.
The purpose of this chapter is to introduce you to Java, beginning with its history,
its design philosophy, and several of its most important features. By far, the hardest
thing about learning a programming language is the fact that no element exists in
isolation. Instead, the components of the language work in conjunction with each
other. This interrelatedness is especially pronounced in Java. In fact, it is difficult to
discuss one aspect of Java without involving others. To help overcome this problem,
this chapter provides a brief overview of several Java features, including the general
form of a Java program, some basic control structures, and simple operators. It does
not go into too many details, but, rather, concentrates on general concepts common
to any Java program.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com