100% found this document useful (9 votes)
75 views

Full Chapter Core Java Volume I Fundamentals Eleventh Edition Safari PDF

ebook

Uploaded by

jack.parrish237
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 (9 votes)
75 views

Full Chapter Core Java Volume I Fundamentals Eleventh Edition Safari PDF

ebook

Uploaded by

jack.parrish237
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/ 53

Core Java Volume I - Fundamentals,

Eleventh Edition Safari


Visit to download the full and correct content document:
https://textbookfull.com/product/core-java-volume-i-fundamentals-eleventh-edition-saf
ari/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Biota Grow 2C gather 2C cook Loucas

https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-
loucas/

Java: The Complete Reference, Eleventh Edition Herbert


Schildt

https://textbookfull.com/product/java-the-complete-reference-
eleventh-edition-herbert-schildt/

Structural Dynamics Fundamentals and Advanced


Applications, Volume I: Volume I 1st Edition Alvar M.
Kabe

https://textbookfull.com/product/structural-dynamics-
fundamentals-and-advanced-applications-volume-i-volume-i-1st-
edition-alvar-m-kabe/

Fundamentals of Technical Graphics Volume I Edward E


Osakue

https://textbookfull.com/product/fundamentals-of-technical-
graphics-volume-i-edward-e-osakue/
Beginning Swift Master the fundamentals of programming
in Swift 4 Safari

https://textbookfull.com/product/beginning-swift-master-the-
fundamentals-of-programming-in-swift-4-safari/

Horngren's Accounting, Volume 2, Eleventh Canadian


Edition Tracie Miller-Nobles

https://textbookfull.com/product/horngrens-accounting-
volume-2-eleventh-canadian-edition-tracie-miller-nobles/

A Primer on Microeconomics, Volume I: Fundamentals of


Exchange Second Edition Thomas M. Beveridge

https://textbookfull.com/product/a-primer-on-microeconomics-
volume-i-fundamentals-of-exchange-second-edition-thomas-m-
beveridge/

Media Composer Fundamentals I Avid

https://textbookfull.com/product/media-composer-fundamentals-i-
avid/

Interactive C#: Fundamentals, Core Concepts and


Patterns 1st Edition Vaskaran Sarcar

https://textbookfull.com/product/interactive-c-fundamentals-core-
concepts-and-patterns-1st-edition-vaskaran-sarcar/
About This E-Book
EPUB is an open, industry-standard format for e-books. However,
support for EPUB and its many features varies across reading
devices and applications. Use your device or app settings to
customize the presentation to your liking. Settings that you can
customize often include font, font size, single or double column,
landscape or portrait mode, and figures that you can click or tap to
enlarge. For additional information about the settings and features
on your reading device or app, visit the device manufacturer’s Web
site.
Many titles include programming code or configuration examples.
To optimize the presentation of these elements, view the e-book in
single-column, landscape mode and adjust the font size to the
smallest setting. In addition to presenting code and configurations in
the reflowable text format, we have included images of the code
that mimic the presentation found in the print book; therefore,
where the reflowable format may compromise the presentation of
the code listing, you will see a “Click here to view code image” link.
Click the link to view the print-fidelity code image. To return to the
previous page viewed, click the Back button on your device or app.
Core Java
Volume I–Fundamentals
Eleventh Edition

Cay S. Horstmann

Boston • Columbus • New York • San Francisco • Amsterdam • Cape


Town
Dubai • London • Madrid • Milan • Munich • Paris • Montreal •
Toronto • Delhi • Mexico City
São Paulo • Sydney • Hong Kong • Seoul • Singapore • Taipei •
Tokyo
The author and publisher have taken care in the preparation of this book, but make no
expressed or implied warranty of any kind and assume no responsibility for errors or
omissions. No liability is assumed for incidental or consequential damages in connection
with or arising out of the use of the information or programs contained herein.
For information about buying this title in bulk quantities, or for special sales opportunities
(which may include electronic versions; custom cover designs; and content particular to
your business, training goals, marketing focus, or branding interests), please contact our
corporate sales department at [email protected] or (800) 382-3419.
For government sales inquiries, please contact [email protected].
For questions about sales outside the United States, please contact
[email protected].
Visit us on the Web: informit.com
Library of Congress Preassigned Control Number: 2018942070
Copyright © 2019 Pearson Education Inc.
Portions copyright © 1996-2013 Oracle and/or its affiliates. All Rights Reserved.
Oracle America Inc. does not make any representations or warranties as to the accuracy,
adequacy or completeness of any information contained in this work, and is not responsible
for any errors or omissions.
Microsoft and/or its respective suppliers make no representations about the suitability of the
information contained in the documents and related graphics published as part of the
services for any purpose. All such documents and related graphics are provided "as is"
without warranty of any kind. Microsoft and/or its respective suppliers hereby disclaim all
warranties and conditions with regard to this information, including all warranties and
conditions of merchantability, whether express, implied or statutory, fitness for a particular
purpose, title and non-infringement. In no event shall Microsoft and/or its respective
suppliers be liable for any special, indirect or consequential damages or any damages
whatsoever resulting from loss of use, data or profits, whether in an action of contract,
negligence or other tortious action, arising out of or in connection with the use or
performance of information available from the services. The documents and related
graphics contained herein could include technical inaccuracies or typographical errors.
Changes are periodically added to the information herein. Microsoft and/or its respective
suppliers may make improvements and/or changes in the product(s) and/or the program(s)
described herein at any time. Partial screen shots may be viewed in full within the software
version specified.

Microsoft® Windows®, and Microsoft Office® are registered trademarks of the Microsoft
Corporation in the U.S.A. and other countries. This book is not sponsored or endorsed by or
affiliated with the Microsoft Corporation.
All rights reserved. This publication is protected by copyright, and permission must be
obtained from the publisher prior to any prohibited reproduction, storage in a retrieval
system, or transmission in any form or by any means, electronic, mechanical, photocopying,
recording, or likewise. For information regarding permissions, request forms and the
appropriate contacts within the Pearson Education Global Rights & Permissions Department,
please visit www.pearsoned.com/permissions/.
ISBN-13: 978-0-13-516630-7
ISBN-10: 0-13-516630-6
1 18
Contents
Preface
Acknowledgments
Chapter 1: An Introduction to Java
1.1 Java as a Programming Platform
1.2 The Java “White Paper” Buzzwords
1.2.1 Simple
1.2.2 Object-Oriented
1.2.3 Distributed
1.2.4 Robust
1.2.5 Secure
1.2.6 Architecture-Neutral
1.2.7 Portable
1.2.8 Interpreted
1.2.9 High-Performance
1.2.10 Multithreaded
1.2.11 Dynamic
1.3 Java Applets and the Internet
1.4 A Short History of Java
1.5 Common Misconceptions about Java
Chapter 2: The Java Programming Environment
2.1 Installing the Java Development Kit
2.1.1 Downloading the JDK
2.1.2 Setting up the JDK
2.1.3 Installing Source Files and Documentation
2.2 Using the Command-Line Tools
2.3 Using an Integrated Development Environment
2.4 JShell
Chapter 3: Fundamental Programming Structures in Java
3.1 A Simple Java Program
3.2 Comments
3.3 Data Types
3.3.1 Integer Types
3.3.2 Floating-Point Types
3.3.3 The char Type
3.3.4 Unicode and the char Type
3.3.5 The boolean Type
3.4 Variables and Constants
3.4.1 Declaring Variables
3.4.2 Initializing Variables
3.4.3 Constants
3.4.4 Enumerated Types
3.5 Operators
3.5.1 Arithmetic Operators
3.5.2 Mathematical Functions and Constants
3.5.3 Conversions between Numeric Types
3.5.4 Casts
3.5.5 Combining Assignment with Operators
3.5.6 Increment and Decrement Operators
3.5.7 Relational and boolean Operators
3.5.8 Bitwise Operators
3.5.9 Parentheses and Operator Hierarchy
3.6 Strings
3.6.1 Substrings
3.6.2 Concatenation
3.6.3 Strings Are Immutable
3.6.4 Testing Strings for Equality
3.6.5 Empty and Null Strings
3.6.6 Code Points and Code Units
3.6.7 The String API
3.6.8 Reading the Online API Documentation
3.6.9 Building Strings
3.7 Input and Output
3.7.1 Reading Input
3.7.2 Formatting Output
3.7.3 File Input and Output
3.8 Control Flow
3.8.1 Block Scope
3.8.2 Conditional Statements
3.8.3 Loops
3.8.4 Determinate Loops
3.8.5 Multiple Selections—The switch Statement
3.8.6 Statements That Break Control Flow
3.9 Big Numbers
3.10 Arrays
3.10.1 Declaring Arrays
3.10.2 Accessing Array Elements
3.10.3 The “for each” Loop
3.10.4 Array Copying
3.10.5 Command-Line Parameters
3.10.6 Array Sorting
3.10.7 Multidimensional Arrays
3.10.8 Ragged Arrays
Chapter 4: Objects and Classes
4.1 Introduction to Object-Oriented Programming
4.1.1 Classes
4.1.2 Objects
4.1.3 Identifying Classes
4.1.4 Relationships between Classes
4.2 Using Predefined Classes
4.2.1 Objects and Object Variables
4.2.2 The LocalDate Class of the Java Library
4.2.3 Mutator and Accessor Methods
4.3 Defining Your Own Classes
4.3.1 An Employee Class
4.3.2 Use of Multiple Source Files
4.3.3 Dissecting the Employee Class
4.3.4 First Steps with Constructors
4.3.5 Declaring Local Variables with var
4.3.6 Working with null References
4.3.7 Implicit and Explicit Parameters
4.3.8 Benefits of Encapsulation
4.3.9 Class-Based Access Privileges
4.3.10 Private Methods
4.3.11 Final Instance Fields
4.4 Static Fields and Methods
4.4.1 Static Fields
4.4.2 Static Constants
4.4.3 Static Methods
4.4.4 Factory Methods
4.4.5 The main Method
4.5 Method Parameters
4.6 Object Construction
4.6.1 Overloading
4.6.2 Default Field Initialization
4.6.3 The Constructor with No Arguments
4.6.4 Explicit Field Initialization
4.6.5 Parameter Names
4.6.6 Calling Another Constructor
4.6.7 Initialization Blocks
4.6.8 Object Destruction and the finalize Method
4.7 Packages
4.7.1 Package Names
4.7.2 Class Importation
4.7.3 Static Imports
4.7.4 Addition of a Class into a Package
4.7.5 Package Access
4.7.6 The Class Path
4.7.7 Setting the Class Path
4.8 JAR Files
4.8.1 Creating JAR files
4.8.2 The Manifest
4.8.3 Executable JAR Files
4.8.4 Multi-Release JAR Files
4.8.5 A Note about Command-Line Options
4.9 Documentation Comments
4.9.1 Comment Insertion
4.9.2 Class Comments
4.9.3 Method Comments
4.9.4 Field Comments
4.9.5 General Comments
4.9.6 Package Comments
4.9.7 Comment Extraction
4.10 Class Design Hints
Chapter 5: Inheritance
5.1 Classes, Superclasses, and Subclasses
5.1.1 Defining Subclasses
5.1.2 Overriding Methods
5.1.3 Subclass Constructors
5.1.4 Inheritance Hierarchies
5.1.5 Polymorphism
5.1.6 Understanding Method Calls
5.1.7 Preventing Inheritance: Final Classes and Methods
5.1.8 Casting
5.1.9 Abstract Classes
5.1.10 Protected Access
5.2 Object: The Cosmic Superclass
5.2.1 Variables of Type Object
5.2.2 The equals Method
5.2.3 Equality Testing and Inheritance
5.2.4 The hashCode Method
5.2.5 The toString Method
5.3 Generic Array Lists
5.3.1 Declaring Array Lists
5.3.2 Accessing Array List Elements
5.3.3 Compatibility between Typed and Raw Array Lists
5.4 Object Wrappers and Autoboxing
5.5 Methods with a Variable Number of Parameters
5.6 Enumeration Classes
5.7 Reflection
5.7.1 The Class Class
5.7.2 A Primer on Declaring Exceptions
5.7.3 Resources
5.7.4 Using Reflection to Analyze the Capabilities of Classes
5.7.5 Using Reflection to Analyze Objects at Runtime
5.7.6 Using Reflection to Write Generic Array Code
5.7.7 Invoking Arbitrary Methods and Constructors
5.8 Design Hints for Inheritance
Chapter 6: Interfaces, Lambda Expressions, and Inner
Classes
6.1 Interfaces
6.1.1 The Interface Concept
6.1.2 Properties of Interfaces
6.1.3 Interfaces and Abstract Classes
6.1.4 Static and Private Methods
6.1.5 Default Methods
6.1.6 Resolving Default Method Conflicts
6.1.7 Interfaces and Callbacks
6.1.8 The Comparator Interface
6.1.9 Object Cloning
6.2 Lambda Expressions
6.2.1 Why Lambdas?
6.2.2 The Syntax of Lambda Expressions
6.2.3 Functional Interfaces
6.2.4 Method References
6.2.5 Constructor References
6.2.6 Variable Scope
6.2.7 Processing Lambda Expressions
6.2.8 More about Comparators
6.3 Inner Classes
6.3.1 Use of an Inner Class to Access Object State
6.3.2 Special Syntax Rules for Inner Classes
6.3.3 Are Inner Classes Useful? Actually Necessary?
Secure?
6.3.4 Local Inner Classes
6.3.5 Accessing Variables from Outer Methods
6.3.6 Anonymous Inner Classes
6.3.7 Static Inner Classes
6.4 Service Loaders
6.5 Proxies
6.5.1 When to Use Proxies
6.5.2 Creating Proxy Objects
6.5.3 Properties of Proxy Classes
Chapter 7: Exceptions, Assertions, and Logging
7.1 Dealing with Errors
7.1.1 The Classification of Exceptions
7.1.2 Declaring Checked Exceptions
7.1.3 How to Throw an Exception
7.1.4 Creating Exception Classes
7.2 Catching Exceptions
7.2.1 Catching an Exception
7.2.2 Catching Multiple Exceptions
7.2.3 Rethrowing and Chaining Exceptions
7.2.4 The finally Clause
7.2.5 The try-with-Resources Statement
7.2.6 Analyzing Stack Trace Elements
7.3 Tips for Using Exceptions
7.4 Using Assertions
7.4.1 The Assertion Concept
7.4.2 Assertion Enabling and Disabling
7.4.3 Using Assertions for Parameter Checking
7.4.4 Using Assertions for Documenting Assumptions
7.5 Logging
7.5.1 Basic Logging
7.5.2 Advanced Logging
7.5.3 Changing the Log Manager Configuration
7.5.4 Localization
7.5.5 Handlers
7.5.6 Filters
7.5.7 Formatters
7.5.8 A Logging Recipe
7.6 Debugging Tips
Chapter 8: Generic Programming
8.1 Why Generic Programming?
8.1.1 The Advantage of Type Parameters
8.1.2 Who Wants to Be a Generic Programmer?
8.2 Defining a Simple Generic Class
8.3 Generic Methods
8.4 Bounds for Type Variables
8.5 Generic Code and the Virtual Machine
8.5.1 Type Erasure
8.5.2 Translating Generic Expressions
8.5.3 Translating Generic Methods
8.5.4 Calling Legacy Code
8.6 Restrictions and Limitations
8.6.1 Type Parameters Cannot Be Instantiated with
Primitive Types
8.6.2 Runtime Type Inquiry Only Works with Raw Types
8.6.3 You Cannot Create Arrays of Parameterized Types
8.6.4 Varargs Warnings
8.6.5 You Cannot Instantiate Type Variables
8.6.6 You Cannot Construct a Generic Array
8.6.7 Type Variables Are Not Valid in Static Contexts of
Generic Classes
8.6.8 You Cannot Throw or Catch Instances of a Generic
Class
8.6.9 You Can Defeat Checked Exception Checking
8.6.10 Beware of Clashes after Erasure
8.7 Inheritance Rules for Generic Types
8.8 Wildcard Types
8.8.1 The Wildcard Concept
8.8.2 Supertype Bounds for Wildcards
8.8.3 Unbounded Wildcards
8.8.4 Wildcard Capture
8.9 Reflection and Generics
8.9.1 The Generic Class Class
8.9.2 Using Class<T> Parameters for Type Matching
8.9.3 Generic Type Information in the Virtual Machine
8.9.4 Type Literals
Chapter 9: Collections
9.1 The Java Collections Framework
9.1.1 Separating Collection Interfaces and Implementation
9.1.2 The Collection Interface
9.1.3 Iterators
9.1.4 Generic Utility Methods
9.2 Interfaces in the Collections Framework
9.3 Concrete Collections
9.3.1 Linked Lists
9.3.2 Array Lists
9.3.3 Hash Sets
9.3.4 Tree Sets
9.3.5 Queues and Deques
9.3.6 Priority Queues
9.4 Maps
9.4.1 Basic Map Operations
9.4.2 Updating Map Entries
9.4.3 Map Views
9.4.4 Weak Hash Maps
9.4.5 Linked Hash Sets and Maps
9.4.6 Enumeration Sets and Maps
9.4.7 Identity Hash Maps
9.5 Views and Wrappers
9.5.1 Small Collections
9.5.2 Subranges
9.5.3 Unmodifiable Views
9.5.4 Synchronized Views
9.5.5 Checked Views
9.5.6 A Note on Optional Operations
9.6 Algorithms
9.6.1 Why Generic Algorithms?
9.6.2 Sorting and Shuffling
9.6.3 Binary Search
9.6.4 Simple Algorithms
9.6.5 Bulk Operations
9.6.6 Converting between Collections and Arrays
9.6.7 Writing Your Own Algorithms
9.7 Legacy Collections
9.7.1 The Hashtable Class
9.7.2 Enumerations
9.7.3 Property Maps
9.7.4 Stacks
9.7.5 Bit Sets
Chapter 10: Graphical User Interface Programming
10.1 A History of Java User Interface Toolkits
10.2 Displaying Frames
10.2.1 Creating a Frame
10.2.2 Frame Properties
10.3 Displaying Information in a Component
10.3.1 Working with 2D Shapes
10.3.2 Using Color
10.3.3 Using Fonts
10.3.4 Displaying Images
10.4 Event Handling
10.4.1 Basic Event Handling Concepts
10.4.2 Example: Handling a Button Click
10.4.3 Specifying Listeners Concisely
10.4.4 Adapter Classes
10.4.5 Actions
10.4.6 Mouse Events
10.4.7 The AWT Event Hierarchy
10.5 The Preferences API
Chapter 11: User Interface Components with Swing
11.1 Swing and the Model-View-Controller Design Pattern
11.2 Introduction to Layout Management
11.2.1 Layout Managers
11.2.2 Border Layout
11.2.3 Grid Layout
11.3 Text Input
11.3.1 Text Fields
11.3.2 Labels and Labeling Components
11.3.3 Password Fields
11.3.4 Text Areas
11.3.5 Scroll Panes
11.4 Choice Components
11.4.1 Checkboxes
11.4.2 Radio Buttons
11.4.3 Borders
11.4.4 Combo Boxes
11.4.5 Sliders
11.5 Menus
11.5.1 Menu Building
11.5.2 Icons in Menu Items
11.5.3 Checkbox and Radio Button Menu Items
11.5.4 Pop-Up Menus
11.5.5 Keyboard Mnemonics and Accelerators
11.5.6 Enabling and Disabling Menu Items
11.5.7 Toolbars
11.5.8 Tooltips
11.6 Sophisticated Layout Management
11.6.1 The Grid Bag Layout
11.6.1.1 The gridx, gridy, gridwidth, and
gridheight Parameters
11.6.1.2 Weight Fields
11.6.1.3 The fill and anchor Parameters
11.6.1.4 Padding
11.6.1.5 Alternative Method to Specify the gridx,
gridy, gridwidth, and gridheight
Parameters
11.6.1.6 A Grid Bag Layout Recipe
11.6.1.7 A Helper Class to Tame the Grid Bag
Constraints
11.6.2 Custom Layout Managers
11.7 Dialog Boxes
11.7.1 Option Dialogs
11.7.2 Creating Dialogs
11.7.3 Data Exchange
11.7.4 File Dialogs
Chapter 12: Concurrency
12.1 What Are Threads?
12.2 Thread States
12.2.1 New Threads
12.2.2 Runnable Threads
12.2.3 Blocked and Waiting Threads
12.2.4 Terminated Threads
12.3 Thread Properties
12.3.1 Interrupting Threads
12.3.2 Daemon Threads
12.3.3 Thread Names
12.3.4 Handlers for Uncaught Exceptions
12.3.5 Thread Priorities
12.4 Synchronization
12.4.1 An Example of a Race Condition
12.4.2 The Race Condition Explained
12.4.3 Lock Objects
12.4.4 Condition Objects
12.4.5 The synchronized Keyword
12.4.6 Synchronized Blocks
12.4.7 The Monitor Concept
12.4.8 Volatile Fields
12.4.9 Final Variables
12.4.10 Atomics
12.4.11 Deadlocks
12.4.12 Thread-Local Variables
12.4.13 Why the stop and suspend Methods Are
Deprecated
12.5 Thread-Safe Collections
12.5.1 Blocking Queues
12.5.2 Efficient Maps, Sets, and Queues
12.5.3 Atomic Update of Map Entries
12.5.4 Bulk Operations on Concurrent Hash Maps
12.5.5 Concurrent Set Views
12.5.6 Copy on Write Arrays
12.5.7 Parallel Array Algorithms
12.5.8 Older Thread-Safe Collections
12.6 Tasks and Thread Pools
12.6.1 Callables and Futures
12.6.2 Executors
12.6.3 Controlling Groups of Tasks
12.6.4 The Fork-Join Framework
12.7 Asynchronous Computations
12.7.1 Completable Futures
12.7.2 Composing Completable Futures
12.7.3 Long-Running Tasks in User Interface Callbacks
12.8 Processes
12.8.1 Building a Process
12.8.2 Running a Process
12.8.3 Process Handles
Appendix
Index
Preface
To the Reader
In late 1995, the Java programming language burst onto the
Internet scene and gained instant celebrity status. The promise of
Java technology was that it would become the universal glue that
connects users with information wherever it comes from—web
servers, databases, information providers, or any other imaginable
source. Indeed, Java is in a unique position to fulfill this promise. It
is an extremely solidly engineered language that has gained wide
acceptance. Its built-in security and safety features are reassuring
both to programmers and to the users of Java programs. Java has
built-in support for advanced programming tasks, such as network
programming, database connectivity, and concurrency.
Since 1995, eleven major revisions of the Java Development Kit have
been released. Over the course of the last 20 years, the Application
Programming Interface (API) has grown from about 200 to over
4,000 classes. The API now spans such diverse areas as user
interface construction, database management, internationalization,
security, and XML processing.
The book that you are reading right now is the first volume of the
eleventh edition of Core Java. Each edition closely followed a release
of the Java Development Kit, and each time, we rewrote the book to
take advantage of the newest Java features. This edition has been
updated to reflect the features of Java Standard Edition (SE) 9, 10,
and 11.
As with the previous editions of this book, we still target serious
programmers who want to put Java to work on real projects. We
think of you, our reader, as a programmer with a solid background in
a programming language other than Java, and we assume that you
don’t like books filled with toy examples (such as toasters, zoo
animals, or “nervous text”). You won’t find any of these in our book.
Our goal is to enable you to fully understand the Java language and
library, not to give you an illusion of understanding.
In this book you will find lots of sample code demonstrating almost
every language and library feature that we discuss. We keep the
sample programs purposefully simple to focus on the major points,
but, for the most part, they aren’t fake and they don’t cut corners.
They should make good starting points for your own code.
We assume you are willing, even eager, to learn about all the
advanced features that Java puts at your disposal. For example, we
give you a detailed treatment of
Object-oriented programming
Reflection and proxies
Interfaces and inner classes
Exception handling
Generic programming
The collections framework
The event listener model
Graphical user interface design
Concurrency
With the explosive growth of the Java class library, a one-volume
treatment of all the features of Java that serious programmers need
to know is no longer possible. Hence, we decided to break up the
book into two volumes. This first volume concentrates on the
fundamental concepts of the Java language, along with the basics of
user-interface programming. The second volume, Core Java, Volume
II—Advanced Features, goes further into the enterprise features and
advanced user-interface programming. It includes detailed
discussions of
The Stream API
File processing and regular expressions
Databases
XML processing
Annotations
Internationalization
Network programming
Advanced GUI components
Advanced graphics
Native methods
When writing a book, errors and inaccuracies are inevitable. We’d
very much like to know about them. But, of course, we’d prefer to
learn about each of them only once. We have put up a list of
frequently asked questions, bug fixes, and workarounds on a web
page at http://horstmann.com/corejava. Strategically placed
at the end of the errata page (to encourage you to read through
it first) is a form you can use to report bugs and suggest
improvements. Please don’t be disappointed if we don’t answer
every query or don’t get back to you immediately. We do read all e-
mail and appreciate your input to make future editions of this book
clearer and more informative.

A Tour of This Book


Chapter 1 gives an overview of the capabilities of Java that set it
apart from other programming languages. We explain what the
designers of the language set out to do and to what extent they
succeeded. Then, we give a short history of how Java came into
being and how it has evolved.
In Chapter 2, we tell you how to download and install the JDK and
the program examples for this book. Then we guide you through
compiling and running three typical Java programs—a console
application, a graphical application, and an applet—using the plain
JDK, a Java-enabled text editor, and a Java IDE.
Chapter 3 starts the discussion of the Java language. In this
chapter, we cover the basics: variables, loops, and simple functions.
If you are a C or C++ programmer, this is smooth sailing because
the syntax for these language features is essentially the same as in
C. If you come from a non-C background such as Visual Basic, you
will want to read this chapter carefully.
Object-oriented programming (OOP) is now in the mainstream of
programming practice, and Java is an object-oriented programming
language. Chapter 4 introduces encapsulation, the first of two
fundamental building blocks of object orientation, and the Java
language mechanism to implement it—that is, classes and methods.
In addition to the rules of the Java language, we also give advice on
sound OOP design. Finally, we cover the marvelous
javadoc tool that formats your code comments as a set of
hyperlinked web pages. If you are familiar with C++, you can
browse through this chapter quickly. Programmers coming from a
non-object-oriented background should expect to spend some time
mastering the OOP concepts before going further with Java.
Classes and encapsulation are only one part of the OOP story, and
Chapter 5 introduces the other—namely, inheritance. Inheritance
lets you take an existing class and modify it according to your needs.
This is a fundamental technique for programming in Java. The
inheritance mechanism in Java is quite similar to that in C++. Once
again, C++ programmers can focus on the differences between the
languages.
Chapter 6 shows you how to use Java’s notion of an interface.
Interfaces let you go beyond the simple inheritance model of
Chapter 5. Mastering interfaces allows you to have full access to the
power of Java’s completely object-oriented approach to
programming. After we cover interfaces, we move on to lambda
expressions, a concise way for expressing a block of code that can
be executed at a later point in time. We then cover a useful technical
feature of Java called inner classes.
Chapter 7 discusses exception handling—Java’s robust mechanism
to deal with the fact that bad things can happen to good programs.
Exceptions give you an efficient way of separating the normal
processing code from the error handling. Of course, even after
hardening your program by handling all exceptional conditions, it still
might fail to work as expected. In the final part of this chapter, we
give you a number of useful debugging tips.
Chapter 8 gives an overview of generic programming. Generic
programming makes your programs easier to read and safer. We
show you how to use strong typing and remove unsightly and unsafe
casts, and how to deal with the complexities that arise from the
need to stay compatible with older versions of Java.
The topic of Chapter 9 is the collections framework of the Java
platform. Whenever you want to collect multiple objects and retrieve
them later, you should use a collection that is best suited for your
circumstances, instead of just tossing the elements into an array.
This chapter shows you how to take advantage of the standard
collections that are prebuilt for your use.
Chapter 10 provides an introduction into GUI programming. We
show how you can make windows, how to paint on them, how to
draw with geometric shapes, how to format text in multiple fonts,
and how to display images. Next, you’ll see how to write code that
responds to events, such as mouse clicks or key presses.
Chapter 11 discusses the Swing GUI toolkit in great detail. The
Swing toolkit allows you to build cross-platform graphical user
interfaces. You’ll learn all about the various kinds of buttons, text
components, borders, sliders, list boxes, menus, and dialog boxes.
However, some of the more advanced components are discussed in
Volume II.
Chapter 12 finishes the book with a discussion of concurrency,
which enables you to program tasks to be done in parallel. This is an
important and exciting application of Java technology in an era
where most processors have multiple cores that you want to keep
busy.
A bonus JavaFX chapter contains a rapid introduction into JavaFX,
a modern GUI toolkit for desktop applications. If you read the print
book, download the chapter from the book companion site at
http://horstmann.com/corejava.

The Appendix lists the reserved words of the Java language.

Conventions
As is common in many computer books, we use monospace type
to represent computer code.

Note
Notes are tagged with “note” icons that look like this.

Tip

Tips are tagged with “tip” icons that look like this.

Caution
When there is danger ahead, we warn you with a “caution”
icon.

C++ Note

There are many C++ notes that explain the differences


between Java and C++. You can skip over them if you don’t
have a background in C++ or if you consider your experience
with that language a bad dream of which you’d rather not be
reminded.

Java comes with a large programming library, or Application


Programming Interface (API). When using an API call for the first
time, we add a short summary description at the end of the section.
These descriptions are a bit more informal but, we hope, also a little
more informative than those in the official online API documentation.
The names of interfaces are in italics, just like in the official
documentation. The number after a class, interface, or method
name is the JDK version in which the feature was introduced, as
shown in the following example:

Application Programming Interface 9

Programs whose source code is on the book’s companion web site


are presented as listings, for instance:

Listing 1.1 InputTest/InputTest.java

Sample Code
The web site for this book at http://horstmann.com/corejava
contains all sample code from the book. See Chapter 2 for more
information on installing the Java Development Kit and the sample
code.

Register your copy of Core Java, Volume I—Fundamentals,


Eleventh Edition, on the InformIT site for convenient access to
updates and/or corrections as they become available. To start the
registration process, go toinformit.com/register and log in
or create an account. Enter the product ISBN (9780135166307)
and click Submit. Look on the Registered Products tab for an
Access Bonus Content link next to this product, and follow that
link to access any available bonus materials. If you would like to
be notified of exclusive offers on new editions and updates,
please check the box to receive email from us.
Acknowledgments
Writing a book is always a monumental effort, and rewriting it
doesn’t seem to be much easier, especially with the continuous
change in Java technology. Making a book a reality takes many
dedicated people, and it is my great pleasure to acknowledge the
contributions of the entire Core Java team.
A large number of individuals at Pearson provided valuable
assistance but managed to stay behind the scenes. I’d like them all
to know how much I appreciate their efforts. As always, my warm
thanks go to my editor, Greg Doench, for steering the book through
the writing and production process, and for allowing me to be
blissfully unaware of the existence of all those folks behind the
scenes. I am very grateful to Julie Nahil for production support, and
to Dmitry Kirsanov and Alina Kirsanova for copyediting and type-
setting the manuscript. My thanks also to my coauthor of earlier
editions, Gary Cornell, who has since moved on to other ventures.
Thanks to the many readers of earlier editions who reported
embarrassing errors and made lots of thoughtful suggestions for
improvement. I am particularly grateful to the excellent reviewing
team who went over the manuscript with an amazing eye for detail
and saved me from many embarrassing errors.
Reviewers of this and earlier editions include Chuck Allison (Utah
Valley University), Lance Andersen (Oracle), Paul Anderson
(Anderson Software Group), Alec Beaton (IBM), Cliff Berg, Andrew
Binstock (Oracle), Joshua Bloch, David Brown, Corky Cartwright,
Frank Cohen (PushToTest), Chris Crane (devXsolution), Dr. Nicholas
J. De Lillo (Manhattan College), Rakesh Dhoopar (Oracle), David
Geary (Clarity Training), Jim Gish (Oracle), Brian Goetz (Oracle),
Angela Gordon, Dan Gordon (Electric Cloud), Rob Gordon, John Gray
(University of Hartford), Cameron Gregory (olabs.com), Marty Hall
Another random document with
no related content on Scribd:
“February 28, Wednesday.—February closes: thank God for the
lapse of its twenty-eight days! Should the thirty-one of the coming
March not drag us further downward, we may hope for a successful
close to this dreary drama. By the 10th of April we should have seal;
and when they come, if we remain to welcome them, we can call
ourselves saved.
“But a fair review of our prospects tells me that I must look the
lion in the face. The scurvy is steadily gaining on us. I do my best to
sustain the more desperate cases; but as fast as I partially build up
one, another is stricken down. The disease is perhaps less
malignant than it was, but it is more diffused throughout our party.
Except William Morton, who is disabled by a frozen heel, not one of
our eighteen is exempt. Of the six workers of our party, as I counted
them a month ago, two are unable to do out-door work, and the
remaining four divide the duties of the ship among them. Hans
musters his remaining energies to conduct the hunt. Petersen is his
disheartened, moping assistant. The other two, Bonsall and myself,
have all the daily offices of household and hospital. We chop five
large sacks of ice, cut six fathoms of eight-inch hawser into junks of
a foot each (for fuel), serve out the meat when we have it, hack at
the molasses, and hew out with crowbar and axe the pork and dried
apples, pass up the foul slops and cleansings of our dormitory; and,
in a word, cook, scullionize, and attend the sick. Added to this, for
five nights running I have kept watch from 8 p.m. to 4 a.m., catching
cat-naps as I could in the day without changing my clothes, but
carefully waking every hour to note thermometers.
“Such is the condition in which February leaves us, with forty-one
days more ahead of just the same character in prospect as the
twenty-eight which, thank God! are numbered now with the past. It is
saddening to think how much those twenty-eight days have impaired
our capacities of endurance. If Hans and myself can only hold on, we
may work our way through. All rests upon destiny, or the Power
which controls it.”
It is useless, however, to dwell longer on this melancholy record.
Kane saw that to abandon the brig was now the only resource: the
ice held it fast, there was no probability of its being released, and a
third winter in Rensselaer Bay would have been death to the whole
party. As soon, therefore, as the return of spring in some measure
recruited the health of his followers, he made the necessary
preparations for departure; and on the 20th of May the entire ship’s
company bade farewell to the Advance, and set out on their
homeward route. With considerable difficulty and arduous labour
they hauled their boats across the rough, hummocky ice, and
reached the open sea. On the 17th of June they embarked, and
steered for Upernavik, which port they calculated upon reaching in
fifty-six days. When they got fairly clear of the land, and in the course
of the great ice-drift southward, they found their boats so frail and
leaky that they could be kept afloat only by constant bailing; a labour
which told heavily on men already weakened with disease and want.
Starvation stared them in the face, when happily they fell in with and
captured a large seal, which they devoured voraciously; and this
opportune help recruited their failing energies. Thenceforth they
were in no lack of food, as seals were plentiful; and early in August,
after living for eighty-four days in the open air, they found themselves
under the comfortable roofs of Upernavik, enjoying the hospitable
welcome of the generous Danes.
Dr. Kane returned to New York on the 11th of October 1855, after
an absence of thirty months. His discoveries had been important, his
heroism worthy of the race from which he sprung, and none can
deny that he had well merited the honours he received.
Unfortunately, a frame never very robust had been broken down by
the trials of two Arctic winters; and this gallant explorer passed away
on the 16th of February 1857, in the thirty-seventh year of his age.

In 1860, Dr. Hayes, the companion of Dr. Kane, took the


command of an expedition intended to complete the survey of
Kennedy Channel, and to reach, if it were possible, the North Pole.
His schooner, the United States, was brought up for the winter at
Port Foulke, about twenty miles south of Rensselaer Harbour; and
early in the following April, Dr. Hayes set out on a sledge and boat
journey across the sound, and along the shores of Grinnell Land.
From the eloquent record of his adventures, which does so much
credit to his literary skill, “An Arctic Boat Journey,” we have already
quoted some stirring passages; but the following extract we may be
allowed to repeat, on account of the clear light it throws upon the
nature of the difficulties Hayes encountered on his northward
advance:—
“The track,” he says, “was rough, past description. I can compare
it to nothing but a promiscuous accumulation of rocks closely packed
together, and piled up over a vast plain in great heaps and endless
ridges, leaving scarcely a foot of level surface. The interstices
between these closely accumulated ice-masses are filled up, to
some extent, with drifted snow. The reader will easily imagine the
rest. He will see the sledges winding through the tangled wilderness
of broken ice-tables, the men and dogs pulling and pushing up their
respective loads. He will see them clambering over the very summit
of lofty ridges, through which there is no opening, and again
descending on the other side—the sledge often plunging over a
precipice, sometimes capsizing, and frequently breaking. Again he
will see the party, baffled in their attempt to cross or find a pass,
breaking a track with shovel and handspike; or, again, unable even
with these appliances to accomplish their end, they retreat to seek a
better track: and they may be lucky enough to find a sort of gap or
gateway, upon the winding and uneven surface of which they will
make a mile or so with comparative ease. The snow-drifts are
sometimes a help and sometimes a hindrance. Their surface is
uniformly hard, but not always firm to the foot. The crust frequently
gives way, and in a most tiresome and provoking manner. It will not
quite bear the weight, and the foot sinks at the very moment when
the other is lifted. But, worse than this, the chasms between the
hummocks are frequently bridged over with snow in such a manner
as to leave a considerable space at the bottom quite unfilled; and at
the very moment when all looks promising, down sinks one man to
his middle, another to the neck, another is buried out of sight; the
sledge gives way,—and to extricate the whole from this unhappy
predicament is probably the labour of hours. It would be difficult to
imagine any kind of labour more disheartening, or which would
sooner sap the energies of both men and animals.”

After encountering difficulties like these, which wore out the


strength of most of his party, so that they were compelled to return to
the schooner, Dr. Hayes succeeded in crossing the sound, and
began his journey along the coast. But the difficulties did not abate,
and made such demands on the powers of endurance of the
travellers, that the strongest among them broke down, and had to be
left behind in charge of another of the party. The resolute Hayes then
pushed on, accompanied by Knorr, and on the 18th of May reached
the margin of a deep gulf, where further progress was rendered
impossible by the rotten ice and broad water-ways. From this point,
however, he could see, on the other side of the channel, and
immediately opposite to him, the lofty peak of Mount Parry,
discovered in 1854 by the gallant Morton; and more to the north, a
bold conspicuous headland, which he named Cape Union, the most
northern known land upon the globe. Beyond it, he thought he saw
the open sea of the Pole, which, from Cape Union, is not distant five
hundred miles; but the voyage of the Polaris, at a later date, has
shown that what he saw was only a land-locked bay.
On the 12th of July, the schooner was set free from the ice, but
she proved to be too much damaged to continue her dangerous
voyage; and satisfied with having proved that a direct and not
impracticable route to the Pole lies up Smith Sound and Kennedy
Channel, Dr. Hayes returned to Boston.
It is the opinion, however, of some geographers, though scarcely
warranted by ascertained facts, that the Pole may more easily be
reached by what is known as the Spitzbergen route. They argue that
to the east of this snow-crowned archipelago the influence of the
Gulf Stream makes itself felt; and they conclude that this great warm
current possibly strikes as far as the Pole itself. It is known that
Parry, to the north of Spitzbergen, attained the latitude of 82° 45’;
and it is recorded that a Hull whaler, the True-Love, in 1837,
navigated an open sea in lat. 82° 30’ N., and long. 15° E.; so that
she might probably have solved the problem and have gained the
Pole, had she continued on her northerly course.
Holding this belief, the illustrious German geographer, Dr.
Petermann, succeeded in raising funds for a German expedition in
1868; and the Germania, a brig of eighty tons, under the command
of Captain Koldewey, sailed from Bergen on the 24th of May, for
Shannon Island, in lat. 75° 14’ N., the furthest point on the
Greenland coast reached by Sabine in 1823. She was accompanied
by the Hansa, Captain Hegemann; and both ships were equipped in
the most careful manner, and liberally supplied with appliances and
stores.
On the 9th of July the expedition was off the island of Jan Mayen,
and at midnight on that day was sailing direct to the northward. A
heavy fog came on, and the two ships, even when sailing side by
side, could not see one another, and communication could be
maintained only by the use of the speaking-trumpet. Their crews
might then conceive an idea of that impenetrable chaos which,
according to Pythias, terminated the world beyond Thule, and which
is neither air, nor earth, nor sea. It is impossible to imagine anything
more melancholy than this gray, uniform, infinite veil or canopy;
ocean itself, far as the eye can reach, is gray and gloomy.
For five successive days the weather remained in this condition,
the fog alone varying in intensity, and growing thicker and thicker. On
the 14th a calm prevailed, and the Germania lowered a boat to pick
up drift-wood and hunt the sea-gulls. The ice-blink on the horizon
showed that the ships were drawing near the great ice-fields of the
Polar Ocean; and another sign of their proximity was the appearance
of the ivory gull (Larus eburneus), which never wanders far from the
ice. Occasionally the ships fell in with a rorqual, or nord-caper, as the
seamen call it,—a species of whale distinguished by the presence of
a dorsal fin.
On the morning of the 15th of July a light breeze blew up from the
south, and the two ships sailed steadily on their north-western
course through a sea covered with floating ice. An accustomed ear
could already distinguish a distant murmur, which seemed to draw
nearer and yet nearer; it was the swell of the sea breaking on the far-
off ice-field. Nearer and yet nearer! Everybody gathered upon deck;
and, suddenly, as if in virtue of some spell, the mists cleared away,
and the adventurers saw before them, within a few hundred yards,
the ice! It formed a long line, like a cliff-wall of broken and rugged
rocks, whose azure-tinted precipices glittered in the sun, and
repelled, unmoved, the rush of the foamy waves. The summit was
covered with a deep layer of blinding snow.
They gazed on the splendid panorama in silence. It was a solemn
moment, and in every mind new thoughts and new impressions were
awakened, in which both hope and doubt were blended.
The point where the Germania had struck the ice was lat. 74° 47’
N. and long. 11° 50’ E., and the icy barrier stretched almost directly
from north to south. The Hansa touched the ice on the same day, but
in lat. 74° 57’ N., and long. 9° 41’ E.
The two ships, which had separated in the fog, effected a union
on the 18th, and the Germania taking the Hansa in tow, they made
towards Sabine Island. After awhile, the towing-rope was thrown off,
the Germania finding it necessary to extinguish her fires and proceed
under canvas. They then followed up, in a southerly direction, the
great icy barrier, seeking for an opening which might afford them a
chance of steering westward.
On the 20th, the Germania found the ice so thick in the south-
west that she adopted a westerly Course, and hoisted a signal for
the captain of the Hansa to come on board to a conference. The
latter, however, misinterpreted it, and instead of reading the signal as
“Come within hail,” read it as “Long stay a peak;” crowded on all sail,
and speedily disappeared in the fog, which grew wonderfully intense
before the Germania could follow her. Through this curious error the
two ships were separated, and for fourteen months the crew of the
Germania remained in ignorance of the fate of their comrades’.

Before following the Germania on her voyage of discovery, we


propose to see what befell the Hansa among the Arctic ice.
Captain Hegemann had understood the signal of his senior
officer to mean that the ships were to push on as far as possible to
the westward, and, as we have seen, he crowded on all sail. But
when the fog closed in, and he found himself out of sight of the
Germania, he lay-to, in the hope that the latter might rejoin him.
Disappointed in this, he kept on his way, and on the 28th of July
sighted the rocky and gloomy coast of East Greenland, from Cape
Bröer-Ruys to Cape James.
The weather continued fine. By the light of the midnight sun,
which illuminated the fantastic outlines of the bergs, the adventurers
engaged in a narwhal-hunt. Nothing is more extraordinary than the
effect of the rays of the midnight sun penetrating into an ocean
covered with floating ice. The warm and cold tones strike against
each other in all directions; the sea is orange, leaden-gray, or dark
green; the reefs of ice are tinged with a delicate rose-bloom; broad
shadows spread over the snow, and the most varied effects of
mirage are produced everywhere in the tranquil waters.
THE CREW OF THE “HANSA” TRYING TO LASSO A BEAR.

THE MIDNIGHT SUN, GREENLAND.


A BEAR AT ANCHOR.
On the 9th of September, the Hansa found the channel of free
water in which she had been navigating closed by a huge mass of
ice, and to protect her against the drift of the floating bergs she was
moored to it with stout hawsers. A few days later, the ice was broken
up by a gale of wind from the north-east, and the hawsers snapped.
The ice accumulating behind the ship raised it a foot and a half. On a
contiguous sheet of ice, the explorers discovered a she-bear with her
cub, and a boat was despatched in pursuit. The couple soon caught
sight of it, and began to trot along the edge of the ice beside the
boat, the mother grinding her teeth and licking her beard. Her
enemies landed, and fired, and the bear fell in the snow, mortally
wounded. While the cub was engaged in tenderly licking and
caressing her, several attempts were made to capture it with a lasso;
but it always contrived to extricate itself, and at last took to flight,
crying and moaning bitterly. Though struck with a bullet, it succeeded
in effecting its escape.

On the 12th they again saw a couple of bears coming from the
east, and returning from the sea towards the land. The mother fell a
victim to their guns, but the cub was captured, and chained to an
anchor which they had driven into the ice. It appeared exceedingly
restless and disturbed, but not the less did it greedily devour a slice
of its mother’s flesh which the sailors threw to it. A snow wigwam
was hastily constructed for its accommodation, and the floor covered
with a layer of shavings; but the cub despised these luxuries of
civilization, and preferred to encamp on the snow, like a true
inhabitant of the Polar Regions. A few days afterwards it
disappeared with its chain, which it had contrived to detach from the
anchor; and the weight of the iron, in all probability, had dragged the
poor beast to the bottom of the water.

SKATING—OFF THE COAST OF GREENLAND.


The Hansa was now set fast in the ice, and no hope was
entertained of her release until the coming of the spring. Her crew
amused themselves with skating, and, when the weather permitted,
with all kinds of gymnastic exercises. It became necessary, however,
to consider what preparations should be made for encountering the
Arctic winter, one of the bitterest enemies with which man is called
upon to contend. The Hansa was strongly built, but her commander
feared she might not be able to endure the more and more frequent
pressure of the ice. At first, it was proposed to cover the boats with
sail-cloth and convert them into winter-quarters; but it was felt that
they would not afford a sufficient protection against the rigour of the
Polar climate, its furious winds, its excess of cold, its wild whirlwinds
of snow. And therefore it was resolved to erect on the ice-floe a
suitable winter-hut, constructed of blocks of coal. Bricks made of this
material have the double advantage of absorbing humidity, and
reflecting the heat which they receive. Water and snow would serve
for mortar; and a roof could be made with the covering which
protected the deck of the Hansa from the snow.
The ground-plan of the house was designed by Captain
Hegemann; it measured twenty feet in length, and fourteen feet in
width; the ridge of the roof was eight feet and a half, and the side
walls four feet eight inches in elevation. These walls were composed
of a double row of bricks nine inches wide up to a height of two feet,
after which a single row was used. They were cemented in a
peculiarly novel fashion. The joints and fissures were filled up with
dry snow, on which water was poured, and in ten minutes it
hardened into a compact mass, from which it would have been
exceedingly difficult to extract a solitary brick. The roof consisted of
sails and mats, covered with a layer of snow. The door was two and
a half feet wide, and the floor was paved with slabs of coal. Into this
house, which was completed in seven days, provisions for two
months were carried, including four hundred pounds of bread, two
dozen boxes of preserved meat, a flitch of bacon, some coffee and
brandy, besides a supply of firing-wood, and some tons of coal.

On the 8th of October, after the completion of the house, a violent


snow-storm broke out, which would assuredly have rendered its
construction impossible, and which, in five days, completely buried
both the ship and the hut. Such immense piles of snow accumulated
on the deck of the Hansa, that it was with the greatest difficulty the
seamen could reach their berths.
From the 5th to the 14th of October the drift of the current was so
strong, that the ice-bound ship was carried no fewer than seventy-
two miles towards the south-south-east.
Meantime, the pressure of the ice continued to increase, and the
Hansa seemed held in the tightening grasp of an invincible giant.
Huge masses rose in front, and behind, and on both sides, and
underneath, until she was raised seventeen feet higher than her
original position. Affairs seemed so critical, that Captain Hegemann
hastened to disembark the stores of clothing, the scientific
instruments, charts, log-book, and diaries. It was found that through
the constant strain on her timbers the ship had begun to leak badly,
and on sounding, two feet of water were found in the pumps. All
hands to work! But after half an hour’s vigorous exertions, the water
continued to rise, slowly but surely; and the most careful search
failed to indicate the locality of the leak. It was painfully evident that
the good ship could not be saved.
“Though much affected,” says the chronicler of the expedition,
“by this sad catastrophe, we endured it with firmness. Resignation
was indispensable. The coal hut, constructed on the shifting ice-floe,
was thenceforward our sole refuge in the long nights of an Arctic
winter, and was destined, perhaps, to become our tomb.
“But we had not a minute to lose, and we set to work. At nine
o’clock p.m. the snow-fall ceased; the sky glittered with stars, the
moon illuminated with her radiance the immense wilderness of ice,
and the rays of the Aurora Borealis here and there lighted up the
firmament with their coloured coruscations. The frost was severe;
during the night the thermometer sank to -20° R. One half the crew
continued to work at the pumps; the other was actively engaged in
disembarking on the ice the most necessary articles. There could be
no thought of sleep, for in our frightful situation the mind was beset
by the most conflicting apprehensions. What would become of us at
the very outset of a season which threatened to be one of excessive
rigour? In vain we endeavoured to imagine some means of saving
ourselves. It was not possible to think seriously of an attempt to gain
the land. Perhaps we might have succeeded, in the midst of the
greatest dangers, in reaching the coast by opening up a way across
the ice-floes, but we had no means of transporting thither our
provisions; and it appeared, from the reports of Scoresby, that we
could not count on finding any Eskimo establishments,—so that our
only prospect then would have been to die of hunger.”
The sole resource remaining to the explorers was to drift to the
south on their moving ice-floe, and confine themselves, meantime, to
their coal hut. If their ice-raft proved of sufficient strength, they might
hope to reach in the spring the Eskimo settlement in the south of
Greenland, or come to gain the coast of Iceland by traversing its
cincture of ice.

It was on the 22nd of October, in lat. 70° 50’ N., and long. 21° W.,
that the Hansa sank beneath the ice. Dr. Laube writes: “We made
ourselves as snug as possible, and, once our little house was
completely embanked with snow, we had not to complain of the cold.
We enjoyed perfect health, and occupied the time with long walks
and with our books, of which we had many. We made a Christmas-
tree of birch-twigs, and embellished it with fragments of wax taper.”
To prevent attacks of disease, and to maintain the cheerfulness
of the men, the officers of the expedition stimulated them to every
kind of active employment, and laid down strict rules for the due
division of the day.
At seven in the morning, they were aroused by the watch. They
rose, attired themselves in their warm thick woollen clothing, washed
in water procured by melting snow, and then took their morning cup
of coffee, with a piece of hard bread. Various occupations
succeeded: the construction of such useful utensils as proved to be
necessary; stitching sail-cloth, mending clothes, writing up the day’s
journal, and reading. When the weather permitted, astronomical
observations and calculations were not forgotten. At noon, all hands
were summoned to dinner, at which a good rich soup formed the
principal dish; and as they had an abundance of preserved
vegetables, the bill of fare was frequently changed. In the use of
alcoholic liquors the most rigid economy was observed, and it was
on Sunday only that each person received a glass of port.
The ice-floe on which their cabin stood was assiduously and
carefully explored in all directions. It was about seven miles in circuit,
and its average diameter measured nearly two miles.
The out-of-door amusements consisted chiefly of skating, and
building up huge images of snow—Egyptian sphynxes and the like.
The borders of the ice-floe, especially to the west and south-
west, presented a curious aspect; the attrition and pressure of the
floating ice had built up about it high glittering walls, upwards of ten
feet in elevation. The snow-crystals flashed and radiated in the sun
like myriads of diamonds. The red gleam of morning and evening
cast a strange emerald tint on the white surface of the landscape.
The nights were magnificent. The glowing firmament, and the snow
which reflected its lustre, produced so intense a brightness, that it
was possible to read without fatigue the finest handwriting, and to
distinguish remote objects. The phenomenon of the Aurora Borealis
was of constant occurrence, and on one occasion was so
wonderfully luminous that it paled the radiance of the stars, and
everything upon the ice-floe cast a shadow, as if it had been the sun
shining.
Near the coal-cabin stood two small huts, one of which served for
ablutions, the other as a shed. Round this nucleus of the little
shipwrecked colony were situated at convenient points the piles of
wood for fuel, the boats, and the barrels of patent fuel and pork. To
prevent the wind and snow from entering the dwelling-hut, a
vestibule was constructed, with a winding entrance.
The greatest cold experienced was -29° 30’ F., and this was in
December. After Christmas the little settlement was visited by
several severe storms, and their ice-raft drifted close along the
shore, sometimes within eight or nine miles, amidst much ice-
crushing,—which so reduced it on all sides, that by the 4th of
January 1870 it did not measure more than one-eighth of its original
dimensions.
On the 6th of January, when they had descended as far south as
66° 45’ N. lat., the sun reappeared, and was joyfully welcomed.
On the night of the 15th of January, the colony was stricken by a
sudden and terrible alarm. The ice yawned asunder, immediately
beneath the hut, and its occupants had but just time to take refuge in
their boats. Here they lay in a miserable condition, unable to clear
out the snow, and sheltered very imperfectly from the driving, furious
tempest. But on the 17th the gale moderated, and as soon as the
weather permitted they set to work to reconstruct out of the ruins of
the old hut a new but much smaller one. It was not large enough to
accommodate more than half the colony; and the other half took up
their residence in the boats.
February was calm and fine, and the floe still continued to drift
southward along the land. The nights were gorgeous with auroral
displays. Luminous sheaves expanded themselves on the deep blue
firmament like the folds of a fan, or the petals of a flower.
March was very snowy, and mostly dull. On the 4th, the ice-raft
passed within twenty-five miles of the glacier Kolberger-Heide. A day
or two later, it nearly came into collision with a large grounded
iceberg. The portion nearest to the drifting colony formed an
immense overhanging mass; its principal body had been wrought by
the action of the sun and the waves into the most capricious forms,
and seemed an aggregate of rocks and pinnacles, towers and
gateways. The castaways could have seized its projecting angles as
they floated past. They thought their destruction certain, but the
fragments of ice which surrounded the raft served as “buffers,” and
saved it from a fatal collision.
On the 29th of March, they found themselves in the latitude of
Nukarbik, the island where Graab, the explorer, wintered, from
September 3rd, 1827, to April 5th, 1830. They had cherished the
hope that from this spot they might be able to take to their boats, and
start for Friedrichstal, a Moravian missionary station on the south
coast of Greenland. However, the ice was as yet too compact for any
such venture to be attempted.
For four weeks they were detained in the bay of Nukarbik, only
two or three miles from the shore, and yet unable to reach it. Their
raft was caught in a kind of eddy, and sometimes tacked to the
south, sometimes to the north. The rising tide carried it towards the
shore, the ebbing tide floated it out again to sea. During this
detention they were visited by small troops of birds, snow linnets and
snow buntings. The seamen threw them a small quantity of oats,
which they greedily devoured. They were so tame that they allowed
themselves to be caught by the hand.

SNOW LINNETS AND BUNTINGS VISITING THE CREW OF THE “HANSA.”


From the end of March to the 17th of April, the voyagers
continued their dreary vacillation between Skieldunge Island and
Cape Moltke; a storm then drove them rapidly to the south. The
coast, with its bold littoral mountain-chain, its deep bays, its inlets, its
islands, and its romantic headlands, offered a succession of novel
and impressive scenes; and specially imposing was the great glacier
of Puisortok, a mighty ice-river which skirts the shore for upwards of
thirty miles.
Early in May they had reached lat. 61° 12’.
On the 7th, some water-lanes opened for them a way to the
shore; and abandoning the ice-raft, they took to their boats, with the
intention of progressing southward along the coast. At first they met
with considerable difficulty, being frequently compelled to haul up the
boats on an ice-floe, and so pass the night, or wait until the wind was
favourable. As this necessitated a continual unloading and reloading
of the boats, the work was very severe. At one time they were
detained for six days on the ice, owing to bad weather, violent gales,
and heavy snow-showers. The temperature varied from +2° during
the day to -5° R. during the night.
THE CREW OF THE “HANSA” BIVOUACKING ON THE ICE.
Their rations at this period were thus distributed:—In the morning,
a cup of coffee, with a piece of dry bread. At noon, for dinner, soup
and broth; in the evening, a few mouthfuls of cocoa, of course
without milk and sugar.
They were compelled to observe the most rigid economy in the
use of their provisions, lest, before reaching any settlement, they
should be reduced to the extremities of famine. Yet their appetite
was very keen; a circumstance easily explained, for they were
necessarily very sparing in their allowance of meat and fat, which in
the rigorous Arctic climate are indispensable as nourishment.

As no change took place in the position of the masses of ice


which surrounded them, they resolved to drag their boats towards
the island of Illiudlek, about three marine miles distant. They began
this enterprise on the evening of the 20th, making use of some stout
cables which they had manufactured during the winter, and
harnessing themselves by means of a brace passed across the
shoulders. That evening they accomplished three hundred paces.
Snow fell heavily, and melted as fast as it fell, so that during their
night-bivouac they suffered much from damp.
The next day they found before them such a labyrinth of blocks
and fragments of ice, floating ice-fields, and water-channels, that
they were constrained to give up the idea of hauling their boats
across it, and resolved to wait for the spring tide—which, they knew,
would occur in a few days. The delay was very wearisome. To
beguile the time, some of the seamen set to work at wood-carving,
while the officers and scientific gentlemen manufactured the pieces
for a game of chess. Others prepared some fishing-lines, eighty
fathoms long, in the hope of catching a desirable addition to their
scanty bill of fare.
On the 24th, the weather was splendid. The sun shone in a
cloudless sky, and wherever its genial radiance fell the thermometer
marked + 28° 5’ R. This was an excellent opportunity for drying their
clothes, which, as well as their linen, had been thoroughly soaked
innumerable times. The coverings were removed from the boats,
which, in the warm sunshine, exhaled great clouds of vapour. The
cook endeavoured to add to his stores of provisions; but the seals
churlishly refused to make their appearance, the fish disdained to
nibble at the fat-baited hooks, and the stupid guillemots were
cunning enough to escape the best directed shots.
M. Hildebrandt, with two seamen, made an attempt—in which
they succeeded—to reach the island of Illiudlek, which lay about
three miles off, and is from 450 to 500 feet in height. They found it a
desert; not a trace of vegetation; its shores very steep, and at some
points precipitous; its surface torn with crevasses and ravines. The
only accessible part seemed on the north; but as the evening was
drawing in, they had no time for exploration, and made haste to
return to the boats.
The castaways now came to a resolution to seek a temporary
refuge on this desolate isle. As the heat of the sun was sufficient to
render their labour very painful, and they suffered much from the
effects of the snow upon their eyes, they went to work at night,
dragging their boats forward with many a weary effort, and rested
during the daytime. In this way they reached the island on the 4th of
June.
Here they moored their boats in a small bay sheltered by a wall of
rocks from the north wind, which they named Hansa-Hafen. Next day
they shot two-and-twenty divers, which provided them with a couple
of good dinners. The supply was very valuable, as the stock of
provisions on hand would not last above a fortnight.
After a brief rest, the adventurers resumed their voyage, keeping
close in-shore, and struggling perseveringly amidst ice and stones—
and further checked by an inaccurate chart, which led them into a
deep fiord, instead of King Christian IV. Sound. On the 13th of June,
however, they arrived at the Moravian missionary station of
Friedrichstal, where their countrymen received them with a hearty
welcome. For two hundred days they had sojourned upon a drifting
ice-field, experiencing all the hardships of an Arctic winter,
aggravated by an insufficiency of food.
They reached Julianshaab on the 21st of June; embarked on
board the Danish brig Constance; and were landed at Copenhagen
on the 1st of September.

We must now return to the Germania.


Captain Koldewey made several bold attempts to penetrate the
pack-ice, but proved unsuccessful in all until, on the 1st of August,
he reached lat. 74°, where he contrived to effect a passage; and
though much delayed by a succession of fogs and calms, he made
his way to Sabine Island,—and dropped anchor on its southern side,
in lat. 74° 30’ N., and long. 29° W., on the 5th of August.

You might also like