Java: A Beginner's Guide: Create, Compile, and Run Java Programs Today 9th Edition Herbert Schildt - eBook PDF 2024 scribd download
Java: A Beginner's Guide: Create, Compile, and Run Java Programs Today 9th Edition Herbert Schildt - eBook PDF 2024 scribd download
https://ebookluna.com/download/java-a-beginners-guide-ebook-pdf/
ebookluna.com
https://ebookluna.com/download/java-a-beginners-guide-eighth-edition-
ebook-pdf/
ebookluna.com
https://ebookluna.com/download/java-the-complete-reference-ebook-pdf/
ebookluna.com
https://ebookluna.com/product/ebook-pdf-building-java-programs-a-back-
to-basics-approach-5th-edition/
ebookluna.com
Building Java Programs: A Back to Basics Approach 4th
Edition (eBook PDF)
https://ebookluna.com/product/building-java-programs-a-back-to-basics-
approach-4th-edition-ebook-pdf/
ebookluna.com
https://ebookluna.com/download/building-java-programs-a-back-to-
basics-approach-ebook-pdf/
ebookluna.com
https://ebookluna.com/download/building-java-programs-a-back-to-
basics-approach-ebook-pdf-2/
ebookluna.com
https://ebookluna.com/product/ebook-pdf-building-java-programs-a-back-
to-basics-approach-4th-edition-by-stuart-reges/
ebookluna.com
https://ebookluna.com/product/ebook-pdf-java-software-solutions-9th-
global-edition/
ebookluna.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
Java ™
A Beginner’s Guide
Ninth Edition
Herbert Schildt
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.
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
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
Contents ix
Contents xi
Contents xiii
Contents xv
Index
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711
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,
records, and modules. An introduction to the fundamentals of Swing 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.
xvii
Over the years, Java has continued to grow, evolve, and otherwise redefine itself. Unlike
many other languages, which are slow to incorporate new features, Java has often been at the
forefront of computer language development. One reason for this is the culture of innovation
and change that came to surround Java. As a result, Java has gone through several upgrades—
some relatively small, others more significant.
The first major update to Java was version 1.1. The features added by Java 1.1 were
more substantial than the increase in the minor revision number would have you think.
For example, Java 1.1 added many new library elements, redefined the way events are
handled, and reconfigured many features of the original 1.0 library.
The next major release of Java was Java 2, where the 2 indicates “second generation.”
The creation of Java 2 was a watershed event, marking the beginning of Java’s “modern
age.” The first release of Java 2 carried the version number 1.2. It may seem odd that the first
release of Java 2 used the 1.2 version number. The reason is that it originally referred to the
internal version number of the Java libraries but then was generalized to refer to the entire
release itself. With Java 2, Sun repackaged the Java product as J2SE (Java 2 Platform Standard
Edition), and the version numbers began to be applied to that product.
The next upgrade of Java was J2SE 1.3. This version of Java was the first major upgrade to
the original Java 2 release. For the most part, it added to existing functionality and “tightened
up” the development environment. The release of J2SE 1.4 further enhanced Java. This release
contained several important new features, including chained exceptions, channel-based I/O,
and the assert keyword.
The release of J2SE 5 created nothing short of a second Java revolution. Unlike most of
the previous Java upgrades, which offered important but incremental improvements, J2SE 5
fundamentally expanded the scope, power, and range of the language. To give you an idea of
the magnitude of the changes caused by J2SE 5, here is a list of its major new features:
● 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
Introduction xix
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. 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.
The next release of Java was Java SE 9. The developer’s kit was called JDK 9. With the
release of JDK 9, the internal version number is also 9. JDK 9 represented a major Java release,
incorporating significant enhancements to both the Java language and its libraries. The primary
new feature was 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 had 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 included 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 enhanced JDK 8’s support for
default methods in interfaces. JDK 9 added 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 was 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 deprecated the entire applet API.
The next release of Java was Java SE 10 (JDK 10). However, prior to its release, a major
change occurred in the Java release schedule. In the past, major releases were often separated
by two or more years. However, beginning with JDK 10, the time between releases was
significantly shortened. Releases are now expected to occur on a strict time-based schedule,
with the anticipated time between major releases (now called feature releases) to be just six
months. As a result, JDK 10 was released in March 2018, which is six months after the release
of JDK 9. This more rapid release cadence enables new features and improvements to be
quickly available to Java programmers. Instead of waiting two or more years, when a new
feature is ready, it becomes part of the next scheduled release.
Another facet of the changes to the Java release schedule is the long-term support (LTS)
release. It is now anticipated that an LTS release will take place every three years. An LTS
release will be supported (and thus remain viable) for a period of time longer than six months.
The first LTS release was JDK 11. The second LTS release was JDK 17, for which this book
has been updated. Because of the stability that an LTS release offers, it is likely that its feature
set will define a baseline of functionality for a number of years. Consult Oracle for the latest
information concerning long-term support and the LTS release schedule.
The primary new language feature added by JDK 10 was support for local variable
type inference. With local variable type inference, it is now possible to let the type of a
local variable be inferred from the type of its initializer, rather than being explicitly specified.
Introduction xxi
To support this new capability, the context-sensitive keyword var was added to Java. Type
inference can streamline code by eliminating the need to redundantly specify a variable’s type
when it can be inferred from its initializer. It can also simplify declarations in cases in which
the type is difficult to discern or cannot be explicitly specified. Local variable type inference
has become a common part of the contemporary programming environment. Its inclusion in
Java helps keep Java up-to-date with evolving trends in language design. Along with a number
of other changes, JDK 10 also redefined the Java version string, changing the meaning of the
version numbers so they better align with the new time-based release schedule.
The next version of Java was Java SE 11 (JDK 11). It was released in September 2018,
which is six months after JDK 10. It was an LTS release. The primary new language feature
in JDK 11 was its support for the use of var in a lambda expression. Also, another execution
mode was added to the Java launcher that enables it to directly execute simple single-file
programs. JDK 11 also removed some features. Perhaps of greatest interest, because of its
historical significance, is the removal of support for applets. Recall that applets were first
deprecated by JDK 9. With the release of JDK 11, applet support has been removed. Support
for another deployment-related technology called Java Web Start was also removed from
JDK 11. There is one other high-profile removal in JDK 11: JavaFX. This GUI framework is
no longer part of the JDK, becoming a separate open-source project instead. Because these
features have been removed from the JDK, they are not discussed in this book.
Between the JDK 11 LTS and the next LTS release (JDK 17) were five feature releases:
JDK 12 through JDK 16. JDK 12 and JDK 13 did not add any new language features. JDK 14
added support for the switch expression, which is a switch that produces a value. Other
enhancements to switch were also included. Text blocks, which are essentially string literals
that can span more than one line, were added by JDK 15. JDK 16 enhanced instanceof with
pattern matching and added a new type of class called a record along with the new context-
sensitive keyword record. A record provides a convenient means of aggregating data. JDK 16
also supplied a new application packaging tool called jpackage.
At the time of this writing, Java SE 17 (JDK 17) is the latest version of Java. As mentioned,
it is the second LTS Java release. Thus, it is of particular importance. Its major new feature is
the ability to seal classes and interfaces. Sealing gives you control over the inheritance of a
class and the inheritance and implementation of an interface. Towards this end, it adds a new
context-sensitive keyword sealed. It also adds the context-sensitive keyword non-sealed, which
is the first hyphenated Java keyword. JDK 17 marks the applet API as deprecated for removal.
As explained, support of applets was removed several years ago. However, the applet API was
simply deprecated, which allowed vestigial code that relied on this API to still compile. With the
release of JDK 17, the applet API is now subject to removal by a future release.
One other point about the evolution of Java: Beginning in 2006, the process of open-
sourcing Java began. Today, open-source implementations of the JDK are available. Open
sourcing further contributes to the dynamic nature of Java development. In the final analysis,
Java’s legacy of innovation is secure. Java remains the vibrant, nimble language that the
programming world has come to expect.
The material in this book has been updated through JDK 17. As the preceding discussion
has highlighted, however, the history of Java programming is marked by dynamic change. As
you advance in your study of Java, you will want to watch for new features of each subsequent
Java release. Simply put: The evolution of Java continues!
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), which, at the time of this writing, is JDK 17. This is the JDK for Java SE 17. 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.
Introduction xxiii
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.
Chapter 1
Java Fundamentals
In 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.
attempting to create code for the Internet. This realization caused the focus of Java to switch
from consumer electronics to Internet programming. So, although it was the desire for an
architecture-neutral programming language that provided the initial spark, it was the Internet
that ultimately led to Java’s large-scale success.
Java Applets
At the time of Java’s creation, one of its most exciting features was the applet. An applet
is a special kind of Java program that is designed to be transmitted over the Internet and
automatically executed inside a Java-compatible web browser. If the user clicks a link that
contains an applet, the applet will download and run in the browser automatically. Applets
were intended to be small programs, typically used to display data provided by the server,
handle user input, or provide simple functions, such as a loan calculator. The key feature of
applets is that they execute locally, rather than on the server. In essence, the applet allowed
some functionality to be moved from the server to the client.
The creation of the applet was important because, at the time, it expanded the universe
of objects that could move about freely in cyberspace. In general, there are two very broad
categories of objects that are transmitted between the server and the client: passive information
and dynamic active programs. For example, when you read your e-mail, you are viewing
passive data. Even when you download a program, the program’s code is still only passive
data until you execute it. By contrast, the applet is a dynamic, self-executing program. Such a
program is an active agent on the client computer, yet it is delivered by the server.
In the early days of Java, applets were a crucial part of Java programming. They illustrated
the power and benefits of Java, added an exciting dimension to web pages, and enabled
programmers to explore the full extent of what was possible with Java. Although it is likely
that there are still applets in use today, over time they became less important, and for reasons
that will be explained shortly, JDK 9 began their phase-out process. Finally, applet support was
removed by JDK 11.
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.
ebookluna.com