Full Download Core Java For The Impatient 3rd Edition Cay Horstmann PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 64

Full download test bank at ebookmeta.

com

Core Java for the Impatient 3rd Edition Cay


Horstmann

For dowload this book click LINK or Button below

https://ebookmeta.com/product/core-java-for-the-
impatient-3rd-edition-cay-horstmann/

OR CLICK BUTTON

DOWLOAD EBOOK

Download More ebooks from https://ebookmeta.com


More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Modern JavaScript for the Impatient 1st Edition Cay S.


Horstmann

https://ebookmeta.com/product/modern-javascript-for-the-
impatient-1st-edition-cay-s-horstmann/

Core Java Volume II Advanced Features Cay S Horstmann

https://ebookmeta.com/product/core-java-volume-ii-advanced-
features-cay-s-horstmann/

Core Java, Vol. II-Advanced Feature 12th Edition Cay S.


Horstmann

https://ebookmeta.com/product/core-java-vol-ii-advanced-
feature-12th-edition-cay-s-horstmann/

Java For Everyone Late Objects Cay S Horstmann

https://ebookmeta.com/product/java-for-everyone-late-objects-cay-
s-horstmann/
Brief C Late Objects 3rd Edition Cay Horstmann

https://ebookmeta.com/product/brief-c-late-objects-3rd-edition-
cay-horstmann/

Big Java Late Objects Enhanced eText 2nd Edition Cay S.


Horstmann

https://ebookmeta.com/product/big-java-late-objects-enhanced-
etext-2nd-edition-cay-s-horstmann/

Big C late objects 3rd Edition Cay S. Horstmann

https://ebookmeta.com/product/big-c-late-objects-3rd-edition-cay-
s-horstmann/

OpenShift for Developers: A Guide for Impatient


Beginners 2nd Edition Joshua Wood

https://ebookmeta.com/product/openshift-for-developers-a-guide-
for-impatient-beginners-2nd-edition-joshua-wood/

Java Java Java Object Oriented Problem Solving 3rd


Edition Ralph Morelli Ralph Walde

https://ebookmeta.com/product/java-java-java-object-oriented-
problem-solving-3rd-edition-ralph-morelli-ralph-walde/
About This eBook
ePUB is an open, industry-standard format for eBooks.
However, support of 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 eBook 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 for the
Impatient
Third Edition
Core Java for the
Impatient
Third 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
Cover illustration by Morphart Creation / Shutterstock
Figures 1.1 and 1.3: Microsoft
Figure 1.2: Eclipse Foundation
Figures 1.4, 1.5, 11.1: Oracle Corporation

Many of the designations used by manufacturers and sellers


to distinguish their products are claimed as trademarks.
Where those designations appear in this book, and the
publisher was aware of a trademark claim, the designations
have been printed with initial capital letters or in all capitals.

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/aw


Library of Congress Control Number: 2022942895

Copyright © 2023 Pearson Education, Inc.

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.pearson.com/permissions/.

ISBN-13: 978-0-13-805210-2
ISBN-10: 0-13-805210-7

ScoutAutomatedPrintCode
Pearson’s Commitment to
Diversity, Equity, and Inclusion
Pearson is dedicated to creating bias-free content that
reflects the diversity of all learners. We embrace the many
dimensions of diversity, including but not limited to race,
ethnicity, gender, socioeconomic status, ability, age, sexual
orientation, and religious or political beliefs.
Education is a powerful force for equity and change in our
world. It has the potential to deliver opportunities that
improve lives and enable economic mobility. As we work
with authors to create content for every product and
service, we acknowledge our responsibility to demonstrate
inclusivity and incorporate diverse scholarship so that
everyone can achieve their potential through learning. As
the world’s leading learning company, we have a duty to
help drive change and live up to our purpose to help more
people create a better life for themselves and to create a
better world.
Our ambition is to purposefully contribute to a world where:
Everyone has an equitable and lifelong opportunity to
succeed through learning.
Our educational products and services are inclusive and
represent the rich diversity of learners.
Our educational content accurately reflects the histories
and experiences of the learners we serve.
Our educational content prompts deeper discussions
with learners and motivates them to expand their own
learning (and worldview).
While we work hard to present unbiased content, we want to
hear from you about any concerns or needs with this
Pearson product so that we can investigate and address
them.
Please contact us with concerns about any potential bias
at https://www.pearson.com/report-bias.xhtml.
To Chi—the most patient person in my life.
Contents
Preface
Acknowledgments
About the Author

1 FUNDAMENTAL PROGRAMMING STRUCTURES


1.1 Our First Program
1.1.1 Dissecting the “Hello, World” Program
1.1.2 Compiling and Running a Java Program
1.1.3 Method Calls
1.1.4 JShell
1.2 Primitive Types
1.2.1 Signed Integer Types
1.2.2 Floating-Point Types
1.2.3 The char Type
1.2.4 The boolean Type
1.3 Variables
1.3.1 Variable Declarations
1.3.2 Identifiers
1.3.3 Initialization
1.3.4 Constants
1.4 Arithmetic Operations
1.4.1 Assignment
1.4.2 Basic Arithmetic
1.4.3 Mathematical Methods
1.4.4 Number Type Conversions
1.4.5 Relational and Logical Operators
1.4.6 Big Numbers
1.5 Strings
1.5.1 Concatenation
1.5.2 Substrings
1.5.3 String Comparison
1.5.4 Converting Between Numbers and
Strings
1.5.5 The String API
1.5.6 Code Points and Code Units
1.5.7 Text Blocks
1.6 Input and Output
1.6.1 Reading Input
1.6.2 Formatted Output
1.7 Control Flow
1.7.1 Branches
1.7.2 Switches
1.7.3 Loops
1.7.4 Breaking and Continuing
1.7.5 Local Variable Scope
1.8 Arrays and Array Lists
1.8.1 Working with Arrays
1.8.2 Array Construction
1.8.3 Array Lists
1.8.4 Wrapper Classes for Primitive Types
1.8.5 The Enhanced for Loop
1.8.6 Copying Arrays and Array Lists
1.8.7 Array Algorithms
1.8.8 Command-Line Arguments
1.8.9 Multidimensional Arrays
1.9 Functional Decomposition
1.9.1 Declaring and Calling Static Methods
1.9.2 Array Parameters and Return Values
1.9.3 Variable Arguments
Exercises

2 OBJECT-ORIENTED PROGRAMMING
2.1 Working with Objects
2.1.1 Accessor and Mutator Methods
2.1.2 Object References
2.2 Implementing Classes
2.2.1 Instance Variables
2.2.2 Method Headers
2.2.3 Method Bodies
2.2.4 Instance Method Invocations
2.2.5 The this Reference
2.2.6 Call by Value
2.3 Object Construction
2.3.1 Implementing Constructors
2.3.2 Overloading
2.3.3 Calling One Constructor from Another
2.3.4 Default Initialization
2.3.5 Instance Variable Initialization
2.3.6 Final Instance Variables
2.3.7 The Constructor with No Arguments
2.4 Records
2.4.1 The Record Concept
2.4.2 Constructors: Canonical, Custom, and
Compact
2.5 Static Variables and Methods
2.5.1 Static Variables
2.5.2 Static Constants
2.5.3 Static Initialization Blocks
2.5.4 Static Methods
2.5.5 Factory Methods
2.6 Packages
2.6.1 Package Declarations
2.6.2 The jar Command
2.6.3 The Class Path
2.6.4 Package Access
2.6.5 Importing Classes
2.6.6 Static Imports
2.7 Nested Classes
2.7.1 Static Nested Classes
2.7.2 Inner Classes
2.7.3 Special Syntax Rules for Inner Classes
2.8 Documentation Comments
2.8.1 Comment Insertion
2.8.2 Class Comments
2.8.3 Method Comments
2.8.4 Variable Comments
2.8.5 General Comments
2.8.6 Links
2.8.7 Package, Module, and Overview
Comments
2.8.8 Comment Extraction
Exercises

3 INTERFACES AND LAMBDA EXPRESSIONS


3.1 Interfaces
3.1.1 Using Interfaces
3.1.2 Declaring an Interface
3.1.3 Implementing an Interface
3.1.4 Converting to an Interface Type
3.1.5 Casts and the instanceof Operator
3.1.6 The “Pattern-Matching” Form of
instanceof
3.1.7 Extending Interfaces
3.1.8 Implementing Multiple Interfaces
3.1.9 Constants
3.2 Static, Default, and Private Methods
3.2.1 Static Methods
3.2.2 Default Methods
3.2.3 Resolving Default Method Conflicts
3.2.4 Private Methods
3.3 Examples of Interfaces
3.3.1 The Comparable Interface
3.3.2 The Comparator Interface
3.3.3 The Runnable Interface
3.3.4 User Interface Callbacks
3.4 Lambda Expressions
3.4.1 The Syntax of Lambda Expressions
3.4.2 Functional Interfaces
3.5 Method and Constructor References
3.5.1 Method References
3.5.2 Constructor References
3.6 Processing Lambda Expressions
3.6.1 Implementing Deferred Execution
3.6.2 Choosing a Functional Interface
3.6.3 Implementing Your Own Functional
Interfaces
3.7 Lambda Expressions and Variable Scope
3.7.1 Scope of a Lambda Expression
3.7.2 Accessing Variables from the Enclosing
Scope
3.8 Higher-Order Functions
3.8.1 Methods that Return Functions
3.8.2 Methods That Modify Functions
3.8.3 Comparator Methods
3.9 Local and Anonymous Classes
3.9.1 Local Classes
3.9.2 Anonymous Classes
Exercises

4 INHERITANCE AND REFLECTION


4.1 Extending a Class
4.1.1 Super- and Subclasses
4.1.2 Defining and Inheriting Subclass
Methods
4.1.3 Method Overriding
4.1.4 Subclass Construction
4.1.5 Superclass Assignments
4.1.6 Casts
4.1.7 Anonymous Subclasses
4.1.8 Method Expressions with super
4.2 Inheritance Hierarchies
4.2.1 Final Methods and Classes
4.2.2 Abstract Methods and Classes
4.2.3 Protected Access
4.2.4 Sealed Types
4.2.5 Inheritance and Default Methods
4.3 Object: The Cosmic Superclass
4.3.1 The toString Method
4.3.2 The equals Method
4.3.3 The hashCode Method
4.3.4 Cloning Objects
4.4 Enumerations
4.4.1 Methods of Enumerations
4.4.2 Constructors, Methods, and Fields
4.4.3 Bodies of Instances
4.4.4 Static Members
4.4.5 Switching on an Enumeration
4.5 Runtime Type Information and Resources
4.5.1 The Class Class
4.5.2 Loading Resources
4.5.3 Class Loaders
4.5.4 The Context Class Loader
4.5.5 Service Loaders
4.6 Reflection
4.6.1 Enumerating Class Members
4.6.2 Inspecting Objects
4.6.3 Invoking Methods
4.6.4 Constructing Objects
4.6.5 JavaBeans
4.6.6 Working with Arrays
4.6.7 Proxies
Exercises

5 EXCEPTIONS, ASSERTIONS, AND LOGGING


5.1 Exception Handling
5.1.1 Throwing Exceptions
5.1.2 The Exception Hierarchy
5.1.3 Declaring Checked Exceptions
5.1.4 Catching Exceptions
5.1.5 The Try-with-Resources Statement
5.1.6 The finally Clause
5.1.7 Rethrowing and Chaining Exceptions
5.1.8 Uncaught Exceptions and the Stack
Trace
5.1.9 API Methods for Throwing Exceptions
5.2 Assertions
5.2.1 Using Assertions
5.2.2 Enabling and Disabling Assertions
5.3 Logging
5.3.1 Should You Use the Java Logging
Framework?
5.3.2 Logging 101
5.3.3 The Platform Logging API
5.3.4 Logging Configuration
5.3.5 Log Handlers
5.3.6 Filters and Formatters
Exercises

6 GENERIC PROGRAMMING
6.1 Generic Classes
6.2 Generic Methods
6.3 Type Bounds
6.4 Type Variance and Wildcards
6.4.1 Subtype Wildcards
6.4.2 Supertype Wildcards
6.4.3 Wildcards with Type Variables
6.4.4 Unbounded Wildcards
6.4.5 Wildcard Capture
6.5 Generics in the Java Virtual Machine
6.5.1 Type Erasure
6.5.2 Cast Insertion
6.5.3 Bridge Methods
6.6 Restrictions on Generics
6.6.1 No Primitive Type Arguments
6.6.2 At Runtime, All Types Are Raw
6.6.3 You Cannot Instantiate Type Variables
6.6.4 You Cannot Construct Arrays of
Parameterized Types
6.6.5 Class Type Variables Are Not Valid in
Static Contexts
6.6.6 Methods May Not Clash after Erasure
6.6.7 Exceptions and Generics
6.7 Reflection and Generics
6.7.1 The Class<T> Class
6.7.2 Generic Type Information in the Virtual
Machine
Exercises

7 COLLECTIONS
7.1 An Overview of the Collections Framework
7.2 Iterators
7.3 Sets
7.4 Maps
7.5 Other Collections
7.5.1 Properties
7.5.2 Bit Sets
7.5.3 Enumeration Sets and Maps
7.5.4 Stacks, Queues, Deques, and Priority
Queues
7.5.5 Weak Hash Maps
7.6 Views
7.6.1 Small Collections
7.6.2 Ranges
7.6.3 Unmodifiable Views
Exercises

8 STREAMS
8.1 From Iterating to Stream Operations
8.2 Stream Creation
8.3 The filter, map, and flatMap Methods
8.4 Extracting Substreams and Combining
Streams
8.5 Other Stream Transformations
8.6 Simple Reductions
8.7 The Optional Type
8.7.1 Producing an Alternative
8.7.2 Consuming the Value If Present
8.7.3 Pipelining Optional Values
8.7.4 How Not to Work with Optional Values
8.7.5 Creating Optional Values
8.7.6 Composing Optional Value Functions
with flatMap
8.7.7 Turning an Optional into a Stream
8.8 Collecting Results
8.9 Collecting into Maps
8.10 Grouping and Partitioning
8.11 Downstream Collectors
8.12 Reduction Operations
8.13 Primitive Type Streams
8.14 Parallel Streams
Exercises

9 PROCESSING INPUT AND OUTPUT


9.1 Input/Output Streams, Readers, and Writers
9.1.1 Obtaining Streams
9.1.2 Reading Bytes
9.1.3 Writing Bytes
9.1.4 Character Encodings
9.1.5 Text Input
9.1.6 Text Output
9.1.7 Reading and Writing Binary Data
9.1.8 Random-Access Files
9.1.9 Memory-Mapped Files
9.1.10 File Locking
9.2 Paths, Files, and Directories
9.2.1 Paths
9.2.2 Creating Files and Directories
9.2.3 Copying, Moving, and Deleting Files
9.2.4 Visiting Directory Entries
9.2.5 ZIP File Systems
9.3 HTTP Connections
9.3.1 The URLConnection and HttpURLConnection
Classes
9.3.2 The HTTP Client API
9.4 Regular Expressions
9.4.1 The Regular Expression Syntax
9.4.2 Testing a Match
9.4.3 Finding All Matches
9.4.4 Groups
9.4.5 Splitting along Delimiters
9.4.6 Replacing Matches
9.4.7 Flags
9.5 Serialization
9.5.1 The Serializable Interface
9.5.2 Transient Instance Variables
9.5.3 The readObject and writeObject Methods
9.5.4 The readExternal and writeExternal
Methods
9.5.5 The readResolve and writeReplace
Methods
9.5.6 Versioning
9.5.7 Deserialization and Security
Exercises
10 CONCURRENT PROGRAMMING
10.1 Concurrent Tasks
10.1.1 Running Tasks
10.1.2 Futures
10.2 Asynchronous Computations
10.2.1 Completable Futures
10.2.2 Composing Completable Futures
10.2.3 Long-Running Tasks in User-Interface
Callbacks
10.3 Thread Safety
10.3.1 Visibility
10.3.2 Race Conditions
10.3.3 Strategies for Safe Concurrency
10.3.4 Immutable Classes
10.4 Parallel Algorithms
10.4.1 Parallel Streams
10.4.2 Parallel Array Operations
10.5 Threadsafe Data Structures
10.5.1 Concurrent Hash Maps
10.5.2 Blocking Queues
10.5.3 Other Threadsafe Data Structures
10.6 Atomic Counters and Accumulators
10.7 Locks and Conditions
10.7.1 Locks
10.7.2 The synchronized Keyword
10.7.3 Waiting on Conditions
10.8 Threads
10.8.1 Starting a Thread
10.8.2 Thread Interruption
10.8.3 Thread-Local Variables
10.8.4 Miscellaneous Thread Properties
10.9 Processes
10.9.1 Building a Process
10.9.2 Running a Process
10.9.3 Process Handles
Exercises
11 ANNOTATIONS
11.1 Using Annotations
11.1.1 Annotation Elements
11.1.2 Multiple and Repeated Annotations
11.1.3 Annotating Declarations
11.1.4 Annotating Type Uses
11.1.5 Making Receivers Explicit
11.2 Defining Annotations
11.3 Standard Annotations
11.3.1 Annotations for Compilation
11.3.2 Meta-Annotations
11.4 Processing Annotations at Runtime
11.5 Source-Level Annotation Processing
11.5.1 Annotation Processors
11.5.2 The Language Model API
11.5.3 Using Annotations to Generate
Source Code
Exercises
12 THE DATE AND TIME API
12.1 The Time Line
12.2 Local Dates
12.3 Date Adjusters
12.4 Local Time
12.5 Zoned Time
12.6 Formatting and Parsing
12.7 Interoperating with Legacy Code
Exercises
13 INTERNATIONALIZATION
13.1 Locales
13.1.1 Specifying a Locale
13.1.2 The Default Locale
13.1.3 Display Names
13.2 Number Formats
13.3 Currencies
13.4 Date and Time Formatting
13.5 Collation and Normalization
13.6 Message Formatting
13.7 Resource Bundles
13.7.1 Organizing Resource Bundles
13.7.2 Bundle Classes
13.8 Character Encodings
13.9 Preferences
Exercises
14 COMPILING AND SCRIPTING
14.1 The Compiler API
14.1.1 Invoking the Compiler
14.1.2 Launching a Compilation Task
14.1.3 Capturing Diagnostics
14.1.4 Reading Source Files from Memory
14.1.5 Writing Byte Codes to Memory
14.2 The Scripting API
14.2.1 Getting a Scripting Engine
14.2.2 Evaluating Scripts
14.2.3 Bindings
14.2.4 Redirecting Input and Output
14.2.5 Calling Scripting Functions and
Methods
14.2.6 Compiling a Script
Exercises
15 THE JAVA PLATFORM MODULE SYSTEM
15.1 The Module Concept
15.2 Naming Modules
15.3 The Modular “Hello, World!” Program
15.4 Requiring Modules
15.5 Exporting Packages
15.6 Modules and Reflective Access
15.7 Modular JARs
15.8 Automatic Modules
15.9 The Unnamed Module
15.10 Command-Line Flags for Migration
15.11 Transitive and Static Requirements
15.12 Qualified Exporting and Opening
15.13 Service Loading
15.14 Tools for Working with Modules
Exercises

Index
Preface
Java has seen many changes since its initial release in 1996.
The classic book, Core Java, covers, in meticulous detail, not
just the language but all core libraries and a multitude of
changes between versions, spanning two volumes and over
2,000 pages. However, if you just want to be productive
with modern Java, there is a much faster, easier pathway for
learning the language and core libraries. In this book, I don’t
retrace history and don’t dwell on features of past versions.
I show you the good parts of Java as it exists today, so you
can put your knowledge to work quickly.
As with my previous “Impatient” books, I quickly cut to the
chase, showing you what you need to know to solve a
programming problem without lecturing about the
superiority of one paradigm over another. I also present the
information in small chunks, organized so that you can
quickly retrieve it when needed.
Assuming you are proficient in some other programming
language, such as C++, JavaScript, Swift, PHP, or Ruby, with
this book you will learn how to become a competent Java
programmer. I cover all aspects of Java that a developer
needs to know today, including the powerful concepts of
lambda expressions and streams, as well as modern
constructs such as records and sealed classes.
A key reason to use Java is to tackle concurrent
programming. With parallel algorithms and threadsafe data
structures readily available in the Java library, the way
application programmers should handle concurrent
programming has completely changed. I provide fresh
coverage, showing you how to use the powerful library
features instead of error-prone low-level constructs.
Traditionally, books on Java have focused on user interface
programming, but nowadays, few developers produce user
interfaces on desktop computers. If you intend to use Java
for server-side programming or Android programming, you
will be able to use this book effectively without being
distracted by desktop GUI code.
Finally, this book is written for application programmers, not
for a college course and not for systems wizards. The book
covers issues that application programmers need to wrestle
with, such as logging and working with files, but you won’t
learn how to implement a linked list by hand or how to write
a web server.
I hope you enjoy this rapid-fire introduction into modern
Java, and I hope it will make your work with Java productive
and enjoyable.
If you find errors or have suggestions for improvement,
please visit http://horstmann.com/javaimpatient, head for the
errata page, and leave a comment. Be sure to visit that site
to download the runnable code examples that complement
this book.

Register your copy of Core Java for the Impatient, Third


Edition, on the InformIT site for convenient access to
updates and/or corrections as they become available. To
start the registration process, go to
informit.com/register and log in or create an account.
Enter the product ISBN (9780138052102) 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
My thanks go, as always, to my editor Greg Doench, who
enthusiastically supported the vision of a short book that
gives a fresh introduction to Java. Dmitry Kirsanov and Alina
Kirsanova once again turned an XHTML manuscript into an
attractive book with amazing speed and attention to detail.
My special gratitude goes to the excellent team of reviewers
for all editions who spotted many errors and gave thoughtful
suggestions for improvement. They are: Andres Almiray,
Gail Anderson, Paul Anderson, Marcus Biel, Brian Goetz,
Mark Lawrence, Doug Lea, Simon Ritter, Yoshiki Shibata, and
Christian Ullenboom.

Cay Horstmann
Berlin
August 2022
About the Author
Cay S. Horstmann is the author of JavaScript for the
Impatient and Scala for the Impatient (both from Addison-
Wesley), is principal author of Core Java, Volumes I and II,
Twelfth Edition (Pearson, 2022), and has written a dozen
other books for professional programmers and computer
science students. He is professor emeritus of computer
science at San Jose State University and is a Java Champion.
Chapter 1

Fundamental
Programming Structures

Topics in This Chapter

1.1 Our First Program


1.2 Primitive Types
1.3 Variables
1.4 Arithmetic Operations
1.5 Strings
1.6 Input and Output
1.7 Control Flow
1.8 Arrays and Array Lists
1.9 Functional Decomposition
Exercises

In this chapter, you will learn about the basic data types and
control structures of the Java language. I assume that you
are an experienced programmer in some other language
and that you are familiar with concepts such as variables,
loops, function calls, and arrays, but perhaps with a different
syntax. This chapter will get you up to speed on the Java
way. I will also give you some tips on the most useful parts
of the Java API for manipulating common data types.
The key points of this chapter are:

1. In Java, all methods are declared in a class. You invoke a


non-static method on an object of the class to which the
method belongs.
2. Static methods are not invoked on objects. Program
execution starts with the static main method.
3. Java has eight primitive types: four signed integral types,
two floating-point types, char, and boolean.
4. The Java operators and control structures are very similar
to those of C or JavaScript.
5. There are four forms of switch: expressions and
statements with and without fall-through.
6. The Math class provides common mathematical functions.
7. String objects are sequences of characters or, more
precisely, Unicode code points in the UTF-16 encoding.
8. Use the “text box” syntax to declare multiline string
literals.
9. With the System.out object, you can display output in a
terminal window. A Scanner tied to System.in lets you read
terminal input.
10. Arrays and collections can be used to collect elements of
the same type.

1.1 Our First Program


When learning any new programming language, it is
traditional to start with a program that displays the
message “Hello, World!”. That is what we will do in the
following sections.

1.1.1 Dissecting the “Hello, World”


Program
Without further ado, here is the “Hello, World” program in
Java:
Click here to view code image
package ch01.sec01;

// Our first Java program

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Let’s examine this program:


Java is an object-oriented language. In your program,
you manipulate (mostly) objects by having them do
work. Each object that you manipulate belongs to a
specific class, and we say that the object is an instance
of that class. A class defines what an object’s state can
be and what it can do. In Java, all code is defined inside
classes. We will look at objects and classes in detail in
Chapter 2. This program is made up of a single class
HelloWorld.

main is a method, that is, a function declared inside a


class. The main method is the first method that is called
when the program runs. It is declared as static to
indicate that the method does not operate on any
objects. (When main gets called, there are only a handful
of predefined objects, and none of them are instances of
the HelloWorld class.) The method is declared as void to
indicate that it does not return any value. See Section
1.8.8, “Command-Line Arguments” (page 52) for the
meaning of the parameter declaration String[] args.
In Java, you can declare many features as public or
private, and there are a couple of other visibility levels
as well. Here, we declare the HelloWorld class and the
main method as public, which is the most common
arrangement for classes and methods.
A package is a set of related classes. It is a good idea to
place each class in a package so you can group related
classes together and avoid conflicts when multiple
classes have the same name. In this book, we’ll use
chapter and section numbers as package names. The full
name of our class is ch01.sec01.HelloWorld. Chapter 2 has
more to say about packages and package naming
conventions.
The line starting with // is a comment. All characters
between // and the end of the line are ignored by the
compiler and are meant for human readers only.
Finally, we come to the body of the main method. In our
example, it consists of a single line with a command to
print a message to System.out, an object representing
the “standard output” of the Java program.
As you can see, Java is not a scripting language that can be
used to quickly dash off a few commands. It is squarely
intended as a language for larger programs that benefit
from being organized into classes, packages, and modules.
(Modules are introduced in Chapter 15.)
Java is also quite simple and uniform. Some languages have
global variables and functions as well as variables and
methods inside classes. In Java, everything is declared
inside a class. This uniformity can lead to somewhat
verbose code, but it makes it easy to understand the
meaning of a program.

Note
You have just seen a // comment that extends to the
end of the line. You can also have multiline comments
between /* and */ delimiters, such as
Click here to view code image
/*
This is the first sample program in Core Java
for the Impatient.
The program displays the traditional greeting
"Hello, World!".
*/

There is a third comment style, called documentation


comment, with /** and */ as delimiters, that you will
see in the next chapter.

1.1.2 Compiling and Running a Java


Program
To compile and run this program, you need to install the
Java Development Kit (JDK) and, optionally, an integrated
development environment (IDE). You should also download
the sample code, which you will find at the companion
website for this book, http://horstmann.com/javaimpatient.
Since instructions for installing software don’t make for
interesting reading, I put them on the companion website as
well.
Once you have installed the JDK, open a terminal window,
change to the directory containing the ch01 directory, and
run the commands
Click here to view code image
javac ch01/sec01/HelloWorld.java
java ch01.sec01.HelloWorld

The familiar greeting will appear in the terminal window


(see Figure 1-1).
Note that two steps were involved to execute the program.
The javac command compiles the Java source code into an
intermediate machine-independent representation, called
byte codes, and saves them in class files. The java
command launches a virtual machine that loads the class
files and executes the byte codes.
Once compiled, byte codes can run on any Java virtual
machine, whether on your desktop computer or on a device
in a galaxy far, far away. The promise of “write once, run
anywhere” was an important design criterion for Java.
Figure 1-1 Running a Java program in a terminal window

Note
The javac compiler is invoked with the name of a file,
with slashes separating the path segments, and an
extension .java. The java virtual machine launcher is
invoked with the name of a class, with dots separating
the package segments, and no extension.
Note
If your program consists of a single source file, then
you can skip the compilation step and run the program
with the command
Click here to view code image
java ch01/sec01/HelloWorld.java

Behind the scenes, the program is compiled before it


runs, but no class files are produced.

Note
On Unix-like operating systems, you can turn a Java
file into an executable program by following these
steps:

1. Rename the file so that it doesn’t have extension


.java:
mv HelloWorld.java hello

2. Make the file executable:


chmod +x hello

3. Add a “shebang” line at the top of the file:


Click here to view code image
#!/path/to/jdk/bin/java --source 17

Now you can run the program as


./hello
Another random document with
no related content on Scribd:
women standing together near the center of the floor. All, except one,
were in the variously colored and marked uniforms of the Soviet
Republics. The exception was a tall man in the silver dress uniform of
Argentine. His right arm hung limp and bloody; his skin was grey.
"Colonel Lorentz," said Scone. "We've one prisoner, at least."
After shouting to those within the dome not to fire, the two walked in.
Major Panchurin, the highest-ranking Russian survivor, lifted a hand
to acknowledge their salute. He was too busy talking over the
bonephone to say anything to them.
The two examined the dome. The visiting delegation of Axis officers
was dead except for Lorentz. The Russians left standing numbered
six; the Chinese, four; the Europeans, one; the Arabic, two; the
Indian-East Asiatic, none. There were four Americans alive. Broward.
Scone. Captain Nashdoi. And a badly wounded woman, Major
Hoebel.
Broward walked towards Hoebel to examine her. Before he could do
anything the Russian doctor, Titiev, rose from her side. He said, "I'm
sorry, captain. She isn't going to make it."
Broward looked around the dome and made a remark which must, at
the time, have seemed irrelevant to Titiev. "Only three women left. If
the ratio is the same on the rest of the Moon, we've a real problem."
Scone had followed Broward. After Titiev had left, and after making
sure their bonephones were not on, Scone said in a low voice, "There
were seventy-five Russians stationed here. I doubt if there are over
forty left in the entire base. I wonder how many in Pushkin?"
Pushkin was the base on the other side of the Moon.
They walked back to the group around Panchurin and turned on their
phones so they could listen in.
Panchurin's skin paled, his eyes widened, his hands raised
protestingly.
"No, no," he moaned out loud.
"What is it?" said Scone, who had heard only the last three words
coming in through the device implanted in his skull.
Panchurin turned a suddenly old face to him. "The commander of the
Zemlya said that the Argentineans have set off an undetermined
number of cobalt bombs. More than twenty, at the very least."
He added, "The Zemlya is leaving its orbit. It intends to establish a
new one around the Moon. It won't leave until we evaluate our
situation. If then."
Every Soviet in the room looked at Lorentz.

The Argentinean straightened up from his weary slump and


summoned all the strength left in his bleeding body. He spoke in
Russian so all would understand.
"We told you pigs we would take the whole world with us before we'd
bend our necks to the Communist yoke!" he shouted.
At that moment, his gaunt high-cheekboned face with its long upper
lip, thin lipline mustache, and fanatical blue eyes made him resemble
the dictator of his country, Félipé Howards, El Macho (The
Sledgehammer).
Panchurin ordered two soldiers and the doctor to take him to the jail.
"I would like to kill the beast now," he said. "But he may have valuable
information. Make sure he lives ... for the time being."
Then, Panchurin looked upwards again to Earth, hanging only a little
distance above the horizon. The others also stared.
Earth, dark now, except for steady glares here and there, forest fires
and cities, probably, which would burn for days. Perhaps weeks.
Then, when the fires died out, the embers cooled, no more fire. No
more vegetation, no more animals, no more human beings. Not for
centuries.
Suddenly, Panchurin's face crumpled, tears flowed, and he began
sobbing loudly, rackingly.
The others could not withstand this show of grief. They understood
now. The shock had worn off enough to allow sorrow to have its way.
Grief ran through them like fire through the forests of their native
homes.
Broward, also weeping, looked at Scone and could not understand.
Scone, alone among the men and women under the dome and the
Earth, was not crying. His face was as impassive as the slope of a
Moon mountain.
Scone did not wait for Panchurin to master himself, to think clearly.
He said, "I request permission to return to Clavius, sir."
Panchurin could not speak; he could only nod his head.
"Do you know what the situation is at Clavius?" said Scone
relentlessly.
Panchurin managed a few words. "Some missiles ... Axis base ...
came close ... but no damage ... intercepted."
Scone saluted, turned, and beckoned to Broward and Nashdoi. They
followed him to the exit to the field. Here Scone made sure that the
air-retaining and gamma-ray and sun-deflecting force field outside the
dome was on. Then the North Americans stepped outside onto the
field without their spacesuits. They had done this so many times they
no longer felt the fear and helplessness first experienced upon
venturing from the protecting walls into what seemed empty space.
They entered their craft, and Scone took over the controls.
After identifying himself to the control tower, Scone lifted the dish and
brought it to the very edge of the force field. He put the controls on
automatic, the field disappeared for the two seconds necessary for
the craft to pass the boundary, and the dish, impelled by its own
power and by the push of escaping air, shot forward.
Behind them, the faint flicker indicating the presence of the field
returned. And the escaped air formed brief and bright streamers that
melted under the full impact of the sun.
"That's something that will have to be rectified in the future," said
Scone. "It's an inefficient, air-wasting method. We're not so long on
power we can use it to make more air every time a dish enters or
leaves a field."
He returned on the r-t, contacted Clavius, told them they were coming
in. To the operator, he said, "Pei, how're things going?"
"We're still at battle stations, sir. Though we doubt if there will be any
more attacks. Both the Argentinean and South African bases were
wrecked. They don't have any retaliatory capabilities, but survivors
may be left deep underground. We've received no orders from
Eratosthenes to dispatch searchers to look for survivors. The base at
Pushkin doesn't answer. It must...."

There was a crackling and a roar. When the noise died down, a voice
in Russian said, "This is Eratosthenes. You will refrain from further
radio communication until permission is received to resume.
Acknowledge."
"Colonel Scone on the United Soviet Americas Force destroyer
Broun. Order acknowledged."
He flipped the switch off. To Broward, he said, "Damn Russkies are
starting to clamp down already. But they're rattled. Did you notice I
was talking to Pei in English, and they didn't say a thing about that? I
don't think they'll take much effective action or start any witch-hunts
until they recover fully from the shock and have a chance to evaluate.
"Tell me, is Nashdoi one of you Athenians?"
Broward looked at Nashdoi, who was slumped on a seat at the other
end of the bridge. She was not within earshot of a low voice.
"No," said Broward. "I don't think she's anything but a lukewarm
Marxist. She's a member of the Party, of course. Who on the Moon
isn't? But like so many scientists here, she takes a minimum interest
in ideology, just enough not to be turned down when she applied for
psychological research here.
"She was married, you know. Her husband was called back to Earth
only a little while ago. No one knew if it was for the reasons given or if
he'd done something to displease the Russkies or arouse their
suspicions. You know how it is. You're called back, and maybe you're
never heard of again."
"What other way is there?" said Scone. "Although I don't like the
Russky dictating the fate of any American."
"Yes?" said Broward. He looked curiously at Scone, thinking of what a
mass of contradictions, from his viewpoint, existed inside that
massive head. Scone believed thoroughly in the Soviet system
except for one thing. He was a Nationalist; he wanted an absolutely
independent North American republic, one which would reassert its
place as the strongest in the world.
And that made him dangerous to the Russians and the Chinese.

America had fallen, prey more to its own softness and confusion than
to the machinations of the Soviets. Then, in the turbulent bloody
starving years that followed the fall with their purges, uprisings,
savage repressions, mass transportations to Siberia and other areas,
importation of other nationalities to create division, and bludgeoning
propaganda and reeducation, only the strong and the intelligent
survived.
Scone, Broward, and Nashdoi were of the second generation born
after the fall of Canada and the United States. They had been born
and had lived because their parents were flexible, hardy, and quick.
And because they had inherited and improved these qualities.
The Americans had become a problem to the Russians. And to the
Chinese. Those Americans transported to Siberia had, together with
other nationalities brought to that area, performed miracles with the
harsh climate and soil, had made a garden. But they had become
Siberians, not too friendly with the Russians.
China, to the south, looking for an area in which to dump their excess
population, had protested at the bringing in of other nationalities.
Russia's refusal to permit Chinese entry had been one more added to
the long list of grievances felt by China towards her elder brother in
the Marx family.
And on the North American continent, the American Communists had
become another trial to Moscow. Russia, rich with loot from the U.S.,
had become fat. The lean underfed hungry Americans, using the
Party to work within, had alarmed the Russians with their increasing
power and influence. Moreover, America had recovered, was again a
great industrial empire. Ostensibly under Russian control, the
Americans were pushing and pressuring subtly, and not so subtly, to
get their own way. Moscow had to resist being Uncle Samified.
To complicate the world picture, thousands of North Americans had
taken refuge during the fall of their country in Argentine. And there
the energetic and tough-minded Yanks (the soft and foolish died on
the way or after reaching Argentine) followed the paths of thousands
of Italians and Germans who had fled there long ago. They became
rich and powerful; Félipé Howards, El Macho, was part-Argentinean
Spanish, part-German, part-American.
The South African (sub-Saharan) peoples had ousted their
Communist and Fascist rulers because they were white or white-
influenced. Pan-Africanism was their motto. Recently, the South
African Confederation had formed an alliance with Argentine. And the
Axis had warned the Soviets that they must cease all underground
activity in Axis countries, cease at once the terrible economic
pressures and discriminations against them, and treat them as full
partners in the nations of the world.
If this were not done, and if a war started, and the Argentineans saw
their country was about to-be crushed, they would explode cobalt
bombs. Rather death than dishonor.
The Soviets knew the temper of the proud and arrogant
Argentineans. They had seemed to capitulate. There was a
conference among the heads of the leading Soviets and Axes.
Peaceful coexistence was being talked about.
But, apparently, the Axis had not swallowed this phrase as others had
once swallowed it. And they had decided on a desperate move.
Having cheap lithium bombs and photon compressors and the means
to deliver them with gravitomagnetic drives, the Axis was as well
armed as their foes. Perhaps, their thought must have been, if they
delivered the first blow, their anti-missiles could intercept enough
Soviet missiles so that the few that did get through would do a
minimum of damage. Perhaps. No one really knew what caused the
Axis to start the war.
Whatever the decision of the Axis, the Axis had put on a good show.
One of its features was the visit by their Moon officers to the base at
Eratosthenes, the first presumably, in a series of reciprocal visits and
parties to toast the new amiable relations.
Result: a dying Earth and a torn Moon.

Broward belonged to that small underground which neither believed


in the old Soviet nor the old capitalist system. It wanted a form of
government based on the ancient Athenian method of democracy on
the local level and a loose confederation on the world level. All
national boundaries would be abolished.
Such considerations, thought Broward, must be put aside for the time
being. Getting independence of the Russians, getting rid of the hellish
bonephones, was the thing to do now. Or so it had seemed to him.
But would not that inevitably lead to war and the destruction of all of
humanity? Would it not be better to work with the other Soviets and
hope that eventually the Communist ideal could be subverted and the
Athenian established? With communities so small, the modified
Athenian form of government would be workable. Later, after the
Moon colonies increased in size and population, means could be
found for working out intercolonial problems.
Or perhaps, thought Broward, watching the monolithic Scone, Scone
did not really intend to force the other Soviets to cooperate? Perhaps,
he hoped they would fight to the death and the North American base
alone would be left to repopulate the world.
"Broward," said Scone, "go sound out Nashdoi. Do it subtly."
"Wise as the serpent, subtle as the dove," said Broward. "Or is it the
other way around?"
Scone lifted his eyebrows. "Never heard that before. From what
book?"
Broward walked away without answering. It was significant that
Scone did not know the source of the quotation. The Old and New
Testaments were allowed reading only for select scholars. Broward
had read an illegal copy, had put his freedom and life in jeopardy by
reading it.
But that was not the point here. The thought that occurred to him was
that, nationality and race aside, the people on the Moon were a rather
homogeneous group. Three-fourths of them were engineers or
scientists of high standing, therefore, had high I.Q.'s. They were
descended from ancestors who had proved their toughness and good
genes by surviving through the last hundred years. They were all
either agnostics or atheists or supposed to be so. There would not be
any religious differences to split them. They were all in superb health,
otherwise they would not be here. No diseases among them, not
even the common cold. They would all make good breeding stock.
Moreover, with recent advances in genetic manipulation, defective
genes could be eliminated electrochemically. Such a manipulation
had not been possible on Earth with its vast population where babies
were being born faster than defective genes could be wiped out. But
here where there were so few....
Perhaps, it would be better to allow the Soviet system to exist for
now. Later, use subtle means to bend it towards the desired goal.
No! The system was based on too many falsities, among which the
greatest was dialectical materialism. As long as the corrupt base
existed, the structure would be corrupt.

Broward sat down by Ingrid Nashdoi. She was a short dark and petite
woman of about thirty-three. Not very good-looking but, usually, witty
and vivacious. Now, she stared at the floor, her face frozen.
"I'm sorry about Jim," he said. "But we don't have time to grieve now.
Later, perhaps."
She did not look at him but replied in a low halting voice. "He may
have been dead before the war started. I never even got to say
goodbye to him. You know what that means. What it probably did
mean."
"I don't think they got anything out of him. Otherwise, you and I would
have been arrested, too."
He jerked his head towards Scone and said, "He doesn't know you're
one of us. I want him to think you're a candidate for the Nationalists.
After this struggle with the Russ is over, we may need someone who
can report on him. Think you can do it?"
She nodded her head, and Broward returned to Scone. "She hates
the Russians," he said. "You know they took her husband away. She
doesn't know why. But she hates Ivan's guts."
"Good. Ah, here we go."

After the destroyer had berthed at Clavius, and the three entered the
base, events went swiftly if not smoothly. Scone talked to the entire
personnel over the IP, told them what had happened. Then he went to
his office and issued orders to have the arsenal cleaned out of all
portable weapons. These were transferred to the four destroyers the
Russians had assigned to Clavius as a token force.
Broward then called in his four Athenians and Scone, his five
Nationalists. The situation was explained to them, and they were
informed of what was expected of them. Even Broward was startled,
but didn't protest.
After the weapons had been placed in the destroyers, Scone ordered
the military into his office one at a time. And, one at a time, they were
disarmed and escorted by another door to the arsenal and locked in.
Three of the soldiers asked to join Scone, and he accepted two.
Several protested furiously and denounced Scone as a traitor.
Then, Scone had the civilians assembled in the large auditorium.
(Technically, all personnel were in the military, but the scientists were
only used in that capacity during emergencies.) Here, he told them
what he had done, what he planned to do—except for one thing—and
asked them if they wished to enlist. Again, he got a violent
demonstration from some and sullen silence from others. These were
locked up in the arsenal.
The others were sworn in, except for one man, Whiteside. Broward
pointed him out as an agent and informer for both the Russians and
Chinese. Scone admitted that he had not known about the triple-
dealer, but he took Broward's word and had Whiteside locked up, too.
Then, the radios of the two scout ships were smashed, and the
prisoners marched out and jammed into them. Scone told them they
were free to fly to the Russian base. Within a few minutes, the scouts
hurtled away from Clavius towards the north.
"But, Colonel," said Broward, "they can't give the identifying code to
the Russians. They'll be shot down."
"They are traitors; they prefer the Russky to us. Better for us if they
are shot down. They'll not fight for Ivan."
Broward did not have much appetite when he sat down to eat and to
listen to Scone's detailing of his plan.
"The Zemlya," he said, "has everything we need to sustain us here.
And to clothe the Earth with vegetation and replace her animal life in
the distant future when the radiation is low enough for us to return.
Her deepfreeze tanks contain seeds and plants of thousands of
different species of vegetation. They also hold, in suspended
animation, the bodies of cattle, sheep, horses, rabbits, dogs, cats,
fowl, birds, useful insects and worms. The original intention was to
reanimate these and use them on any Terrestrial-type planet the
Zemlya might find.
"Now, our bases here are self-sustaining. But, when the time comes
to return to Earth, we must have vegetation and animals. Otherwise,
what's the use?
"So, whoever holds the Zemlya holds the key to the future. We must
be the ones who hold that key. With it, we can bargain; the Russians
and the Chinese will have to agree to independence if they want to
share in the seeds and livestock."
"What if the Zemlya's commander chooses destruction of his vessel
rather than surrender?" said Broward. "Then, all of humanity will be
robbed. We'll have no future."
"I have a plan to get us aboard the Zemlya without violence."

An hour later, the four USAF destroyers accelerated outwards


towards Earth. Their radar had picked up the Zemlya; it also had
detected five other Unidentified Space Objects. These were the size
of their own craft.
Abruptly, the Zemlya radioed that it was being attacked. Then,
silence. No answer to the requests from Eratosthenes for more
information.
Scone had no doubt about the attackers' identity. "The Axis leaders
wouldn't have stayed on Earth to die," he said. "They'll be on their
way to their big base on Mars. Or, more likely, they have the same
idea as us. Capture the Zemlya."
"And if they do?" said Broward.
"We take it from them."
The four vessels continued to accelerate in the great curve which
would take them out away from the Zemlya and then would bring
them around towards the Moon again. Their path was computed to
swing them around so they would come up behind the interstellar
ship and overtake it. Though the titanic globe was capable of
eventually achieving far greater speeds than the destroyers, it was
proceeding at a comparatively slow velocity. This speed was
determined by the orbit around the Moon into which the Zemlya
intended to slip.
In ten hours, the USAF complement had curved around and were
about 10,000 kilometers from the Zemlya. Their speed was
approximately 20,000 kilometers an hour at this point, but they were
decelerating. The Moon was bulking larger; ahead of them, visible by
the eye, were two steady gleams. The Zemlya and the only Axis
vessel which had not been blown to bits or sliced to fragments.
According to the Zemlya, which was again in contact with the Russian
base, the Axis ship had been cut in two by a tongue from Zemlya.
But the interstellar ship was now defenseless. It had launched every
missile and anti-missile in its arsenal. And the fuel for the tongue-
generators was exhausted.
"Furthermore," said Shaposhnikov, commander of the Zemlya, "new
USO has been picked up on the radar. Four coming in from Earth. If
these are also Axis, then the Zemlya has only two choices.
Surrender. Or destroy itself."
"There is nothing we can do," replied Eratosthenes. "But we do not
think those USO are Axis. We detected four destroyer-sized objects
leaving the vicinity of the USAF base, and we asked them for
identification. They did not answer, but we have reason to believe
they are North American."
"Perhaps they are coming to our rescue," suggested Shaposhnikov.
"They left before anyone knew you were being attacked. Besides,
they had no orders from us."
"What do I do?" said Shaposhnikov.
Scone, who had tapped into the tight laser beam, broke it up by
sending random pulses into it. The Zemlya discontinued its beam,
and Scone then sent them a message through a pulsed tongue which
the Russian base could tap into only through a wild chance.
After transmitting the proper code identification, Scone said, "Don't
renew contact with Eratosthenes. It is held by the Axis. They're trying
to lure you close enough to grab you. We escaped the destruction of
our base. Let me aboard where we can confer about our next step.
Perhaps, we may have to go to Alpha Centaurus with you."

For several minutes, the Zemlya did not answer. Shaposhnikov must
have been unnerved. Undoubtedly, he was in a quandary. In any
case, he could not prevent the strangers from approaching. If they
were Axis, they had him at their mercy.
Such must have been his reasoning. He replied, "Come ahead."
By then, the USAF dishes had matched their speeds to that of the
Zemlya's. From a distance of only a kilometer, the sphere looked like
a small Earth. It even had the continents painted on the surface,
though the effect was spoiled by the big Russian letters painted on
the Pacific Ocean.
Scone gave a lateral thrust to his vessel, and it nudged gently into the
enormous landing-port of the sphere. Within five minutes, his crew of
ten were in the control room.
Scone did not waste any time. He drew his gun; his men followed
suit; he told Shaposhnikov what he meant to do. The Russian, a tall
thin man of about fifty, seemed numbed. Perhaps, too many
catastrophes had happened in too short a time. The death of Earth,
the attack by the Axis ships, and, now, totally unexpected, this. The
world was coming to an end in too many shapes and too swiftly.
Scone cleared the control room of all Zemlya personnel except the
commander. The others were locked up with the forty-odd men and
women who were surprised at their posts by the Americans.
Scone ordered Shaposhnikov to set up orders to the navigational
computer for a new path. This one would send the Zemlya at the
maximum acceleration endurable by the personnel towards a point in
the south polar region near Clavius. When the Zemlya reached the
proper distance, it would begin a deceleration equally taxing which
would bring it to a halt approximately half a kilometer above the
surface at the indicated point.
Shaposhnikov, speaking disjointedly like a man coming up out of a
nightmare, protested that the Zemlya was not built to stand such a
strain. Moreover, if Scone succeeded in his plan to hide the great
globe at the bottom of a chasm under an overhang.... Well, he could
only predict that the lower half of the Zemlya would be crushed under
the weight—even with the Moon's weak gravity.
"That won't harm the animal tanks," said Scone. "They're in the upper
levels. Do as I say. If you don't, I'll shoot you and set up the computer
myself."
"You are mad," said Shaposhnikov. "But I will do my best to get us
down safely. If this were ordinary war, if we weren't man's—Earth's—
last hope, I would tell you to go ahead, shoot. But...."
Ingrid Nashdoi, standing beside Broward, whispered in a trembling
voice, "The Russian is right. He is mad. It's too great a gamble. If we
lose, then everybody loses."
"Exactly what Scone is betting on," murmured Broward. "He knows
the Russians and Chinese know it, too. Like you, I'm scared. If I could
have foreseen what he was going to do, I think I'd have put a bullet in
him back at Eratosthenes. But it's too late to back out now. We go
along with him no matter what."

The voyage from the Moon and the capture of the Zemlya had taken
twelve hours. Now, with the Zemlya's mighty drive applied—and the
four destroyers riding in the landing-port—the voyage back took three
hours. During this time, the Russian base sent messages. Scone
refused to answer. He intended to tell all the Moon his plans but not
until the Zemlya was close to the end of its path. When the globe was
a thousand kilometers from the surface, and decelerating with the
force of 3g's, he and his men returned to the destroyers. All except
three, who remained with Shaposhnikov.
The destroyers streaked ahead of the Zemlya towards an entrance to
a narrow canyon. This led downwards to a chasm where Scone
intended to place the Zemlya beneath a giant overhang.
But, as the four sped towards the opening two crags, their radar
picked up four objects coming over close to the mountains to the
north. A battlebird and three destroyers. Scone knew that the
Russians had another big craft and three more destroyers available.
But they probably did not want to send them out, too, and leave the
base comparatively defenseless.
He at once radioed the commander of the Lermontov and told him
what was going on.
"We declare independence, a return to Nationalism," he concluded.
"And we call on the other bases to do the same."
The commander roared, "Unless you surrender at once, we turn on
the bonephones! And you will writhe in pain until you die, you
American swine!"
"Do that little thing," said Scone, and he laughed.
He switched on the communication beams linking the four ships and
said, "Hang on for a minute or two, men. Then, it'll be all over. For us
and for them."

Two minutes later, the pain began. A stroke of heat like lightning that
seemed to sear the brains in their skulls. They screamed, all except
Scone, who grew pale and clutched the edge of the control panel. But
the dishes were, for the next two minutes, on automatic, unaffected
by their pilots' condition.
And then, just as suddenly as it had started, the pain died. They were
left shaking and sick, but they knew they would not feel that
unbearable agony again.
"Flutter your craft as if it's going out of control," said Scone. "Make it
seem we're crashing into the entrance to the canyon."
Scone himself put the lead destroyer through the simulation of a craft
with a pain-crazed pilot at the controls. The others followed his
maneuvers, and they slipped into the canyon.
From over the top of the cliff to their left rose a glare that would have
been intolerable if the plastic over the portholes had not automatically
polarized to dim the brightness.
Broward, looking through a screen which showed the view to the rear,
cried out. Not because of the light from the atomic bomb which had
exploded on the other side of the cliff. He yelled because the top of
the Zemlya had also lit up. And he knew in that second what had
happened. The light did not come from the warhead, for an extremely
high mountain was between the huge globe and the blast. If the
upper region of the Zemlya glowed, it was because a tongue from a
Russian ship had brushed against it.
It must have been an accident, for the Russians surely had no wish to
wreck the Zemlya. If they defeated the USAF, they could recapture
the globe with no trouble.
"My God, she's falling!" yelled Broward. "Out of control!"
Scone looked once and quickly. He turned away and said, "All craft
land immediately. All personnel transfer to my ship."
The maneuver took three minutes, for the men in the other dishes
had to connect air tanks to their suits and then run from their ships to
Scone's. Moreover, one man in each destroyer was later than his
fellows since he had to set up the controls on his craft.
Scone did not explain what he meant to do until all personnel had
made the transfer. In the meantime, they were at the mercy of the
Russians if the enemy had chosen to attack over the top of the cliff.
But Scone was gambling that the Russians would be too horrified at
what was happening to the Zemlya. His own men would have been
frozen if he had not compelled them to act. The Earth dying twice
within twenty-four hours was almost more than they could endure.
Only the American commander, the man of stone, seemed not to feel.
Scone took his ship up against the face of the cliff until she was just
below the top. Here the cliff was thin because of the slope on the
other side. And here, hidden from view of the Russians, he drove a
tongue two decimeters wide through the rock.
And, at the moment three Russian destroyers hurtled over the edge,
tongues of compressed light lashing out on every side in the classic
flailing movement, Scone's beam broke through the cliff.
The three empty USAF ships, on automatic, shot upwards at a speed
that would have squeezed their human occupants into jelly—if they
had had occupants. Their tongues shot out and flailed, caught the
Russian tongues, twisted, shot out and flailed, caught the Russian
tongues, twisted as the generators within the USAF vessels strove to
outbend the Russian tongues.
Then, the American vessels rammed into the Russians, drove them
upwards, flipped them over. And all six craft fell along the cliff's face,
Russian and American intermingled, crashing into each other,
bouncing off the sheer face, exploding, their fragments colliding, and
smashed into the bottom of the canyon.
Scone did not see this, for he had completed the tongue through the
tunnel, turned it off for a few seconds, and sent a video beam
through. He was just in time to see the big battlebird start to float off
the ground where it had been waiting. Perhaps, it had not
accompanied the destroyers because of Russian contempt for
American ability. Or, perhaps, because the commander was under
orders not to risk the big ship unless necessary. Even now, the
Lermontov rose slowly as if it might take two paths: over the cliff or
towards the Zemlya. But, as it rose, Scone applied full power.
Some one, or some detecting equipment, on the Lermontov must
have caught view of the tongue as it slid through space to intercept
the battlebird. A tongue shot out towards the American beam. But
Scone, in full and superb control, bent the axis of his beam, and the
Russian missed. Then Scone's was in contact with the hull, and a
hole appeared in the irradiated plastic.
Majestically, the Lermontov continued rising—and so cut itself almost
in half. And, majestically, it fell.
Not before the Russian commander touched off all the missiles
aboard his ship in a last frenzied defense, and the missiles flew out in
all directions. Two hit the slope, blew off the face of the mountain on
the Lermontov's side, and a jet of atomic energy flamed out through
the tunnel created by Scone.
But he had dropped his craft like an elevator, was halfway down the
cliff before the blasts made his side of the mountain tremble.
Half an hour later, the base of Eratosthenes sued for peace. For the
sake of human continuity, said Panchurin, all fighting must cease
forever on the moon.
The Chinese, who had been silent up to then despite their comrades'
pleas for help, also agreed to accept the policy of Nationalism.
Now, Broward expected Scone to break down, to give way to the
strain. He would only have been human if he had done so.
He did not. Not, at least, in anyone's presence.

Broward awoke early during a sleep-period. Unable to forget the


dream he had just had, he went to find Ingrid Nashdoi. She was not in
her lab; her assistant told him that she had gone to the dome with
Scone.
Jealous, Broward hurried there and found the two standing there and
looking up at the half-Earth. Ingrid was holding a puppy in her arms.
This was one of the few animals that had been taken unharmed from
the shattered tanks of the fallen Zemlya.
Broward, looking at them, thought of the problems that faced the
Moon people. There was that of government, though this seemed for
the moment to be settled. But he knew that there would be more
conflict between the bases and that his own promotion of the
Athenian ideology would cause grave trouble.
There was also the problem of women. One woman to every three
men. How would this be solved? Was there any answer other than
heartaches, frustration, hate, even murder?
"I had a dream," said Broward to them. "I dreamed that we on the
Moon were building a great tower which would reach up to the Earth
and that was our only way to get back to Earth. But everybody spoke
a different tongue, and we couldn't understand each other. Therefore,
we kept putting the bricks in the wrong places or getting into furious
but unintelligible argument about construction."
He stopped, saw they expected more, and said, "I'm sorry. That's all
there was. But the moral is obvious."
"Yes," said Ingrid, stroking the head of the wriggling puppy. She
looked up at Earth, close to the horizon. "The physicists say it'll be
two hundred years before we can go back. Do you realize that,
barring accident or war, all three of us might live to see that day? That
we might return with our great-great-great-great-great-great
grandchildren? And we can tell them of the Earth that was, so they
will know how to build the Earth that must be."
"Two hundred years?" said Broward. "We won't be the same persons
then."
But he doubted that even the centuries could change Scone. The
man was made of rock. He would not bend or flow. And then Broward
felt sorry for him. Scone would be a fossil, a true stone man, a
petrified hero. Stone had its time and its uses. But leather also had its
time.
"We'll never get back unless we do today's work every day," said
Scone. "I'll worry about Earth when it's time to worry. Let's go; we've
work to do."
THE END

You might also like