0% found this document useful (0 votes)
1 views

Introduction To Programming Using Java 7e Itebooks pdf download

The document is an introduction to programming using Java, specifically the 7th edition of the book by David J. Eck. It includes links to various related programming ebooks and provides a detailed table of contents covering fundamental programming concepts, Java applications, and programming environments. The book is available in PDF format for free online, with certain resources linked within the document.

Uploaded by

karmistorodd79
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
0% found this document useful (0 votes)
1 views

Introduction To Programming Using Java 7e Itebooks pdf download

The document is an introduction to programming using Java, specifically the 7th edition of the book by David J. Eck. It includes links to various related programming ebooks and provides a detailed table of contents covering fundamental programming concepts, Java applications, and programming environments. The book is available in PDF format for free online, with certain resources linked within the document.

Uploaded by

karmistorodd79
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/ 78

Introduction To Programming Using Java 7e

Itebooks download

https://ebookbell.com/product/introduction-to-programming-using-
java-7e-itebooks-23836692

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Introduction To Programming Using Java Version 9 Swing Edition David J


Eck

https://ebookbell.com/product/introduction-to-programming-using-java-
version-9-swing-edition-david-j-eck-50625664

Introduction To Programming Using Java David J Eck

https://ebookbell.com/product/introduction-to-programming-using-java-
david-j-eck-2375550

Multimedia Introduction To Programming Using Java 1st Edition David


Gries

https://ebookbell.com/product/multimedia-introduction-to-programming-
using-java-1st-edition-david-gries-2100192

Introduction To Programming Using Python Daniel Y Liang

https://ebookbell.com/product/introduction-to-programming-using-
python-daniel-y-liang-22039592
Introduction To Programming Using Visual Basics 10th Edition David I
Schneider

https://ebookbell.com/product/introduction-to-programming-using-
visual-basics-10th-edition-david-i-schneider-11768686

Introduction To Programming Using Visual Basic 11e 11th Edition David


I Schneider

https://ebookbell.com/product/introduction-to-programming-using-
visual-basic-11e-11th-edition-david-i-schneider-11732072

Introduction To Programming Using Fortran 9520032008 Version 3051 Ed


Jorgensen

https://ebookbell.com/product/introduction-to-programming-using-
fortran-9520032008-version-3051-ed-jorgensen-10466018

An Introduction To Programming Using Python Schneider David I

https://ebookbell.com/product/an-introduction-to-programming-using-
python-schneider-david-i-21354512

An Introduction To Programming Using Visual Basic 2008 With Visual


Studio Expression Edition Dvd 7th Ed Schneider

https://ebookbell.com/product/an-introduction-to-programming-using-
visual-basic-2008-with-visual-studio-expression-edition-dvd-7th-ed-
schneider-22041544
Introduction to Programming Using Java
Version 7.0, August 2014

David J. Eck
Hobart and William Smith Colleges

This is a PDF version of a free on-line book that is available at


http://math.hws.edu/javanotes/. The PDF does not include
source code files, solutions to exercises, or answers to quizzes, but
it does have external links to these resources, shown in blue.
The PDF also has internal links, shown in red. These links can
be used in Acrobat Reader and some other PDF reader programs.
ii

c 1996–2014, David J. Eck

David J. Eck (eck@hws.edu)


Department of Mathematics and Computer Science
Hobart and William Smith Colleges
Geneva, NY 14456

This book can be distributed in unmodified form for non-commercial purposes.


Modified versions can be made and distributed for non-commercial purposes
provided they are distributed under the same license as the original. More
specifically: This work is licensed under the Creative Commons Attribution-
NonCommercial-ShareAlike 3.0 License. To view a copy of this license, visit
http://creativecommons.org/licenses/by-nc-sa/3.0/. Other uses require
permission from the author.

The web site for this book is: http://math.hws.edu/javanotes


Contents

Preface xi

1 The Mental Landscape 1


1.1 Machine Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Asynchronous Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 The Java Virtual Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 Building Blocks of Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.5 Object-oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.6 The Modern User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.7 The Internet and Beyond . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Quiz on Chapter 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

2 Names and Things 19


2.1 The Basic Java Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.2 Variables and Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.2.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.2.2 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.2.3 Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.2.4 Strings and String Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.2.5 Variables in Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.3 Objects and Subroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.3.1 Built-in Subroutines and Functions . . . . . . . . . . . . . . . . . . . . . . 30
2.3.2 Classes and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.3.3 Operations on Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.3.4 Introduction to Enums . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.4 Text Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.4.1 Basic Output and Formatted Outupt . . . . . . . . . . . . . . . . . . . . . 38
2.4.2 A First Text Input Example . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.4.3 Basic TextIO Input Functions . . . . . . . . . . . . . . . . . . . . . . . . . 41
2.4.4 Introduction to File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
2.4.5 Other TextIO Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
2.4.6 Using Scanner for Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
2.5 Details of Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
2.5.1 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
2.5.2 Increment and Decrement . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
2.5.3 Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
2.5.4 Boolean Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
2.5.5 Conditional Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

i
CONTENTS ii

2.5.6 Assignment Operators and Type Conversion . . . . . . . . . . . . . . . . 51


2.5.7 Precedence Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
2.6 Programming Environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
2.6.1 Java Development Kit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
2.6.2 Command Line Environment . . . . . . . . . . . . . . . . . . . . . . . . . 55
2.6.3 Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
2.6.4 NetBeans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
2.6.5 BlueJ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
2.6.6 The Problem of Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Exercises for Chapter 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Quiz on Chapter 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

3 Control 67
3.1 Blocks, Loops, and Branches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
3.1.1 Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
3.1.2 The Basic While Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
3.1.3 The Basic If Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
3.1.4 Definite Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
3.2 Algorithm Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
3.2.1 Pseudocode and Stepwise Refinement . . . . . . . . . . . . . . . . . . . . 74
3.2.2 The 3N+1 Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
3.2.3 Coding, Testing, Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . 80
3.3 while and do..while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
3.3.1 The while Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
3.3.2 The do..while Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
3.3.3 break and continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
3.4 The for Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
3.4.1 For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
3.4.2 Example: Counting Divisors . . . . . . . . . . . . . . . . . . . . . . . . . . 91
3.4.3 Nested for Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
3.5 The if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
3.5.1 The Dangling else Problem . . . . . . . . . . . . . . . . . . . . . . . . . . 96
3.5.2 Multiway Branching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
3.5.3 If Statement Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
3.5.4 The Empty Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
3.6 The switch Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
3.6.1 The Basic switch Statement . . . . . . . . . . . . . . . . . . . . . . . . . . 104
3.6.2 Menus and switch Statements . . . . . . . . . . . . . . . . . . . . . . . . . 106
3.6.3 Enums in switch Statements . . . . . . . . . . . . . . . . . . . . . . . . . 108
3.6.4 Definite Assignment and switch Statements . . . . . . . . . . . . . . . . . 108
3.7 Exceptions and try..catch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
3.7.1 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
3.7.2 try..catch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
3.7.3 Exceptions in TextIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
3.8 Introduction to Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
3.8.1 Creating and Using Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 114
3.8.2 Arrays and For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
CONTENTS iii

3.8.3 Random Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117


3.8.4 Partially Full Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
3.8.5 Two-dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
3.9 GUI Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
3.9.1 Drawing Shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
3.9.2 Drawing in a Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
3.9.3 Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Exercises for Chapter 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Quiz on Chapter 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

4 Subroutines 135
4.1 Black Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
4.2 Static Subroutines and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
4.2.1 Subroutine Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
4.2.2 Calling Subroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
4.2.3 Subroutines in Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
4.2.4 Member Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
4.3 Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
4.3.1 Using Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
4.3.2 Formal and Actual Parameters . . . . . . . . . . . . . . . . . . . . . . . . 147
4.3.3 Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
4.3.4 Subroutine Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
4.3.5 Array Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
4.3.6 Command-line Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
4.3.7 Throwing Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
4.3.8 Global and Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 154
4.4 Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
4.4.1 The return statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
4.4.2 Function Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
4.4.3 3N+1 Revisited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
4.5 APIs, Packages, and Javadoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
4.5.1 Toolboxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
4.5.2 Java’s Standard Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
4.5.3 Using Classes from Packages . . . . . . . . . . . . . . . . . . . . . . . . . 163
4.5.4 Javadoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
4.5.5 Static Import . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
4.6 More on Program Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
4.6.1 Preconditions and Postconditions . . . . . . . . . . . . . . . . . . . . . . . 168
4.6.2 A Design Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
4.6.3 The Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
4.7 The Truth About Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
4.7.1 Initialization in Declarations . . . . . . . . . . . . . . . . . . . . . . . . . 175
4.7.2 Named Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
4.7.3 Naming and Scope Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Exercises for Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
Quiz on Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
CONTENTS iv

5 Objects and Classes 189


5.1 Objects and Instance Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
5.1.1 Objects, Classes, and Instances . . . . . . . . . . . . . . . . . . . . . . . . 190
5.1.2 Fundamentals of Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
5.1.3 Getters and Setters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
5.1.4 Arrays and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
5.2 Constructors and Object Initialization . . . . . . . . . . . . . . . . . . . . . . . . 199
5.2.1 Initializing Instance Variables . . . . . . . . . . . . . . . . . . . . . . . . . 199
5.2.2 Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
5.2.3 Garbage Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
5.3 Programming with Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
5.3.1 Some Built-in Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
5.3.2 The class “Object” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
5.3.3 Writing and Using a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
5.3.4 Object-oriented Analysis and Design . . . . . . . . . . . . . . . . . . . . . 212
5.4 Programming Example: Card, Hand, Deck . . . . . . . . . . . . . . . . . . . . . . 213
5.4.1 Designing the classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
5.4.2 The Card Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
5.4.3 Example: A Simple Card Game . . . . . . . . . . . . . . . . . . . . . . . . 220
5.5 Inheritance and Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
5.5.1 Extending Existing Classes . . . . . . . . . . . . . . . . . . . . . . . . . . 223
5.5.2 Inheritance and Class Hierarchy . . . . . . . . . . . . . . . . . . . . . . . 225
5.5.3 Example: Vehicles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
5.5.4 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
5.5.5 Abstract Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
5.6 this and super . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
5.6.1 The Special Variable this . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
5.6.2 The Special Variable super . . . . . . . . . . . . . . . . . . . . . . . . . . 235
5.6.3 super and this As Constructors . . . . . . . . . . . . . . . . . . . . . . . . 236
5.7 Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
5.7.1 Defining and Implementing Interfaces . . . . . . . . . . . . . . . . . . . . 238
5.7.2 Interfaces as Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
5.7.3 Interfaces in Java 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
5.8 Nested Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
5.8.1 Static Nested Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
5.8.2 Inner Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
5.8.3 Anonymous Inner Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
5.8.4 Java 8 Lambda Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Exercises for Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
Quiz on Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251

6 Introduction to GUI Programming 253


6.1 The Basic GUI Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
6.1.1 JFrame and JPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
6.1.2 Components and Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
6.1.3 Events and Listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
6.1.4 Some Java GUI History . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
CONTENTS v

6.2 Graphics and Painting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259


6.2.1 Coordinates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
6.2.2 Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
6.2.3 Fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
6.2.4 Shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
6.2.5 Graphics2D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
6.2.6 An Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
6.2.7 Where is main()? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
6.3 Mouse Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
6.3.1 Event Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
6.3.2 MouseEvent and MouseListener . . . . . . . . . . . . . . . . . . . . . . . . 272
6.3.3 MouseEvent Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
6.3.4 MouseMotionListeners and Dragging . . . . . . . . . . . . . . . . . . . . . 278
6.3.5 Anonymous Event Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . 281
6.4 Timers, KeyEvents, and State Machines . . . . . . . . . . . . . . . . . . . . . . . 283
6.4.1 Timers and Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
6.4.2 Keyboard Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
6.4.3 Focus Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
6.4.4 State Machines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
6.5 Basic Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
6.5.1 JButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
6.5.2 JLabel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
6.5.3 JCheckBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
6.5.4 JTextField and JTextArea . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
6.5.5 JSlider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
6.6 Basic Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
6.6.1 Basic Layout Managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
6.6.2 Borders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
6.6.3 SliderAndButtonDemo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
6.6.4 A Simple Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
6.6.5 Using a null Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
6.6.6 A Little Card Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
6.7 Menus and Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
6.7.1 Menus and Menubars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
6.7.2 Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
6.7.3 Fine Points of Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
6.7.4 Creating Jar Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
Exercises for Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
Quiz on Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330

7 Arrays and ArrayLists 331


7.1 Array Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
7.1.1 For-each Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
7.1.2 Variable Arity Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
7.1.3 Array Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
7.2 Array Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
7.2.1 Some Processing Examples . . . . . . . . . . . . . . . . . . . . . . . . . . 337
CONTENTS vi

7.2.2 Some Standard Array Methods . . . . . . . . . . . . . . . . . . . . . . . . 340


7.2.3 RandomStrings Revisited . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
7.2.4 Dynamic Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
7.3 ArrayList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
7.3.1 ArrayList and Parameterized Types . . . . . . . . . . . . . . . . . . . . . 347
7.3.2 Wrapper Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
7.3.3 Programming With ArrayList . . . . . . . . . . . . . . . . . . . . . . . . . 350
7.3.4 Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
7.4 Searching and Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
7.4.1 Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
7.4.2 Association Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
7.4.3 Insertion Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
7.4.4 Selection Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
7.4.5 Unsorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
7.5 Two-dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
7.5.1 The Truth About 2D Arrays . . . . . . . . . . . . . . . . . . . . . . . . . 364
7.5.2 Conway’s Game Of Life . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
7.5.3 Checkers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
Exercises for Chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
Quiz on Chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381

8 Correctness, Robustness, Efficiency 383


8.1 Introduction to Correctness and Robustness . . . . . . . . . . . . . . . . . . . . . 383
8.1.1 Horror Stories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
8.1.2 Java to the Rescue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
8.1.3 Problems Remain in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
8.2 Writing Correct Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
8.2.1 Provably Correct Programs . . . . . . . . . . . . . . . . . . . . . . . . . . 388
8.2.2 Robust Handling of Input . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
8.3 Exceptions and try..catch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
8.3.1 Exceptions and Exception Classes . . . . . . . . . . . . . . . . . . . . . . 396
8.3.2 The try Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
8.3.3 Throwing Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
8.3.4 Mandatory Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . 403
8.3.5 Programming with Exceptions . . . . . . . . . . . . . . . . . . . . . . . . 404
8.4 Assertions and Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
8.4.1 Assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
8.4.2 Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
8.5 Analysis of Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
Exercises for Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
Quiz on Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422

9 Linked Data Structures and Recursion 423


9.1 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
9.1.1 Recursive Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
9.1.2 Towers of Hanoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
9.1.3 A Recursive Sorting Algorithm . . . . . . . . . . . . . . . . . . . . . . . . 429
9.1.4 Blob Counting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
CONTENTS vii

9.2 Linked Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435


9.2.1 Recursive Linking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
9.2.2 Linked Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
9.2.3 Basic Linked List Processing . . . . . . . . . . . . . . . . . . . . . . . . . 438
9.2.4 Inserting into a Linked List . . . . . . . . . . . . . . . . . . . . . . . . . . 441
9.2.5 Deleting from a Linked List . . . . . . . . . . . . . . . . . . . . . . . . . . 443
9.3 Stacks, Queues, and ADTs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
9.3.1 Stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
9.3.2 Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
9.3.3 Postfix Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
9.4 Binary Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
9.4.1 Tree Traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
9.4.2 Binary Sort Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
9.4.3 Expression Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
9.5 A Simple Recursive Descent Parser . . . . . . . . . . . . . . . . . . . . . . . . . . 466
9.5.1 Backus-Naur Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
9.5.2 Recursive Descent Parsing . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
9.5.3 Building an Expression Tree . . . . . . . . . . . . . . . . . . . . . . . . . . 472
Exercises for Chapter 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
Quiz on Chapter 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478

10 Generic Programming and Collection Classes 481


10.1 Generic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
10.1.1 Generic Programming in Smalltalk . . . . . . . . . . . . . . . . . . . . . . 482
10.1.2 Generic Programming in C++ . . . . . . . . . . . . . . . . . . . . . . . . 483
10.1.3 Generic Programming in Java . . . . . . . . . . . . . . . . . . . . . . . . . 484
10.1.4 The Java Collection Framework . . . . . . . . . . . . . . . . . . . . . . . . 485
10.1.5 Iterators and for-each Loops . . . . . . . . . . . . . . . . . . . . . . . . . . 487
10.1.6 Equality and Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
10.1.7 Generics and Wrapper Classes . . . . . . . . . . . . . . . . . . . . . . . . 491
10.2 Lists and Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
10.2.1 ArrayList and LinkedList . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
10.2.2 Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
10.2.3 TreeSet and HashSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
10.2.4 EnumSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
10.2.5 Priority Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
10.3 Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
10.3.1 The Map Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
10.3.2 Views, SubSets, and SubMaps . . . . . . . . . . . . . . . . . . . . . . . . 503
10.3.3 Hash Tables and Hash Codes . . . . . . . . . . . . . . . . . . . . . . . . . 506
10.4 Programming with the JFC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
10.4.1 Symbol Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
10.4.2 Sets Inside a Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
10.4.3 Using a Comparator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
10.4.4 Word Counting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
10.5 Writing Generic Classes and Methods . . . . . . . . . . . . . . . . . . . . . . . . 517
10.5.1 Simple Generic Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
CONTENTS viii

10.5.2 Simple Generic Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519


10.5.3 Type Wildcards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
10.5.4 Bounded Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
Exercises for Chapter 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
Quiz on Chapter 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532

11 Streams, Files, and Networking 533


11.1 Streams, Readers, and Writers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
11.1.1 Character and Byte Streams . . . . . . . . . . . . . . . . . . . . . . . . . 534
11.1.2 PrintWriter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
11.1.3 Data Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
11.1.4 Reading Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
11.1.5 The Scanner Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
11.1.6 Serialized Object I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
11.2 Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
11.2.1 Reading and Writing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
11.2.2 Files and Directories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
11.2.3 File Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
11.3 Programming With Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
11.3.1 Copying a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
11.3.2 Persistent Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
11.3.3 Files in GUI Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
11.3.4 Storing Objects in Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
11.4 Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
11.4.1 URLs and URLConnections . . . . . . . . . . . . . . . . . . . . . . . . . . 567
11.4.2 TCP/IP and Client/Server . . . . . . . . . . . . . . . . . . . . . . . . . . 569
11.4.3 Sockets in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
11.4.4 A Trivial Client/Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
11.4.5 A Simple Network Chat . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
11.5 A Brief Introduction to XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
11.5.1 Basic XML Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
11.5.2 Working With the DOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
Exercises for Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
Quiz on Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591

12 Threads and Multiprocessing 593


12.1 Introduction to Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
12.1.1 Creating and Running Threads . . . . . . . . . . . . . . . . . . . . . . . . 594
12.1.2 Operations on Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598
12.1.3 Mutual Exclusion with “synchronized” . . . . . . . . . . . . . . . . . . . . 601
12.1.4 Volatile Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604
12.2 Programming with Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
12.2.1 Threads Versus Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
12.2.2 Recursion in a Thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607
12.2.3 Threads for Background Computation . . . . . . . . . . . . . . . . . . . . 609
12.2.4 Threads for Multiprocessing . . . . . . . . . . . . . . . . . . . . . . . . . . 611
12.2.5 The SwingUtilities Approach . . . . . . . . . . . . . . . . . . . . . . . . . 613
12.3 Threads and Parallel Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . 614
CONTENTS ix

12.3.1 Problem Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614


12.3.2 Thread Pools and Task Queues . . . . . . . . . . . . . . . . . . . . . . . . 615
12.3.3 Producer/Consumer and Blocking Queues . . . . . . . . . . . . . . . . . . 618
12.3.4 Wait and Notify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
12.4 Threads and Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
12.4.1 The Blocking I/O Problem . . . . . . . . . . . . . . . . . . . . . . . . . . 628
12.4.2 An Asynchronous Network Chat Program . . . . . . . . . . . . . . . . . . 629
12.4.3 A Threaded Network Server . . . . . . . . . . . . . . . . . . . . . . . . . . 633
12.4.4 Using a Thread Pool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635
12.4.5 Distributed Computing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637
12.5 Network Programming Example . . . . . . . . . . . . . . . . . . . . . . . . . . . 643
12.5.1 The Netgame Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
12.5.2 A Simple Chat Room . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648
12.5.3 A Networked TicTacToe Game . . . . . . . . . . . . . . . . . . . . . . . . 650
12.5.4 A Networked Poker Game . . . . . . . . . . . . . . . . . . . . . . . . . . . 653
Exercises for Chapter 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654
Quiz on Chapter 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658

13 Advanced GUI Programming 659


13.1 Images and Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659
13.1.1 Images and BufferedImages . . . . . . . . . . . . . . . . . . . . . . . . . . 659
13.1.2 Working With Pixels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666
13.1.3 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668
13.1.4 Cursors and Icons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669
13.1.5 Image File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671
13.2 Fancier Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672
13.2.1 Measuring Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 673
13.2.2 Transparency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675
13.2.3 Antialiasing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677
13.2.4 Strokes and Paints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 678
13.2.5 Transforms and Shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681
13.3 Actions and Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684
13.3.1 Action and AbstractAction . . . . . . . . . . . . . . . . . . . . . . . . . . 684
13.3.2 Icons on Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686
13.3.3 Making Choices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687
13.3.4 Toolbars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691
13.3.5 Keyboard Accelerators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
13.3.6 HTML on Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
13.4 Complex Components and MVC . . . . . . . . . . . . . . . . . . . . . . . . . . . 695
13.4.1 Model-View-Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695
13.4.2 Lists and ListModels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 696
13.4.3 Tables and TableModels . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699
13.4.4 Documents and Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703
13.4.5 Custom Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 704
13.5 Finishing Touches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 709
13.5.1 The Mandelbrot Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 709
13.5.2 Design of the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711
CONTENTS x

13.5.3 Internationalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713


13.5.4 Events, Events, Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 715
13.5.5 Custom Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717
13.5.6 Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 718
Exercises for Chapter 13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 720
Quiz on Chapter 13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 723

Appendix: Source Files 725

Glossary 735
Preface

Introduction to Programming Using Java is a free introductory computer programming


textbook that uses Java as the language of instruction. It is suitable for use in an introductory
programming course and for people who are trying to learn programming on their own. There
are no prerequisites beyond a general familiarity with the ideas of computers and programs.
There is enough material for a full year of college-level programming. Chapters 1 through 7
can be used as a textbook in a one-semester college-level course or in a year-long high school
course. The remaining chapters can be covered in a second course.
The Seventh Edition of the book covers “Java 7.” The most recent version of Java is 8, but
this book has only a few very short mentions of the new features in Java 8.
The home web site for this book is http://math.hws.edu/javanotes/. The page at that
address contains links for downloading a copy of the web site and for downloading PDF versions
of the book. The web site—and the web site download—includes source code for the sample
programs that are discussed in the text, answers to end-of-chapter quizzes and a discussion and
solution for each end-of-chapter exercises. Readers are encouraged to download the source code
for the examples and to read and run the programs as they read the book. Readers are also
strongly encouraged to read the exercise solutions if they want to get the most out of this book.
In style, this is a textbook rather than a tutorial. That is, it concentrates on explaining
concepts rather than giving step-by-step how-to-do-it guides. I have tried to use a conversa-
tional writing style that might be closer to classroom lecture than to a typical textbook. This
is certainly not a Java reference book, and it is not a comprehensive survey of all the features
of Java. It is not written as a quick introduction to Java for people who already know another
programming language. Instead, it is directed mainly towards people who are learning program-
ming for the first time, and it is as much about general programming concepts as it is about
Java in particular. I believe that Introduction to Programming using Java is fully competitive
with the conventionally published, printed programming textbooks that are available on the
market. (Well, all right, I’ll confess that I think it’s better.)
There are several approaches to teaching Java. One approach uses graphical user interface
programming from the very beginning. Some people believe that object oriented programming
should also be emphasized from the very beginning. This is not the approach that I take. The
approach that I favor starts with the more basic building blocks of programming and builds
from there. After an introductory chapter, I cover procedural programming in Chapters 2,
3, and 4. Object-oriented programming is introduced in Chapter 5. Chapter 6 covers the
closely related topic of event-oriented programming and graphical user interfaces. Arrays are
introduced in Chapter 3 with a full treatment in Chapter 7. Chapter 8 is a short chapter that
marks a turning point in the book, moving beyond the fundamental ideas of programming to
cover more advanced topics. Chapter 8 is about writing robust, correct, and efficient programs.
Chapters 9 and 10 cover recursion and data structures, including the Java Collection Framework.
Chapter 11 is about files and networking. Chapter 12 covers threads and parallel processing.

xi
Preface xii

Finally, Chapter 13 returns to the topic of graphical user interface programming to cover some
of Java’s more advanced capabilities.
∗ ∗ ∗
The Seventh Edition of “Introduction to Programming using Java” is not a huge update
from the sixth edition. In fact, my main motivation for the new version was to remove any use
of applets or coverage of applets from the book. Applets are Java programs that run on a web
page. When Java first came out, they were exciting, and it seemed like they would become a
major way of creating active content for the Web. Up until the sixth edition, the web pages
for this book included applets for running many of the sample programs. However, because
of security issues and the emergence of other technologies, applets are no longer widely used.
Furthermore, the most recent versions of Java made it fairly difficult and unpleasant to use the
applets in the book. In place of applets, I have tried to make it as easy as possible for readers
to download the sample programs and run them on their own computers.
Another significant change in the seventh edition is that arrays are now introduced in
Chapter 3 in a basic form that is used throughout the next three chapters. Previously, arrays
were not introduced until Chapter 7, after objects and GUI programming had already been
covered. Much of the more advanced coverage of arrays is still in Chapter 7.
Aside from that, there are many small improvements throughout, mostly related to features
that were new in Java 7.
∗ ∗ ∗
The latest complete edition of Introduction to Programming using Java is available on line
at http://math.hws.edu/javanotes/. The first version of the book was written in 1996, and
there have been several editions since then. All editions are archived at the following Web
addresses:
• First edition: http://math.hws.edu/eck/cs124/javanotes1/ (Covers Java 1.0.)
• Second edition: http://math.hws.edu/eck/cs124/javanotes2/ (Covers Java 1.1.)
• Third edition: http://math.hws.edu/eck/cs124/javanotes3/ (Covers Java 1.1.)
• Fourth edition: http://math.hws.edu/eck/cs124/javanotes4/ (Covers Java 1.4.)
• Fifth edition: http://math.hws.edu/eck/cs124/javanotes5/ (Covers Java 5.0.)
• Sixth edition: http://math.hws.edu/eck/cs124/javanotes6/ (Covers Java 5.0 and later.)
• Seventh edition: http://math.hws.edu/eck/cs124/javanotes7/ (Covers Java 7.)
Introduction to Programming using Java is free, but it is not in the pub-
lic domain. Version 7 is published under the terms of the Creative Commons
Attribution-NonCommercial-ShareAlike 3.0 License. To view a copy of this license, visit
http://creativecommons.org/licenses/by-nc-sa/3.0/. For example, you can:
• Post an unmodified copy of the on-line version on your own Web site (including the parts
that list the author and state the license under which it is distributed!).
• Give away unmodified copies of this book or sell them at cost of production, as long as
they meet the requirements of the license.
• Make modified copies of the complete book or parts of it and post them on the web or
otherwise distribute them non-commercially, provided that attribution to the author is
given, the modifications are clearly noted, and the modified copies are distributed under
the same license as the original. This includes translations to other languages.
Preface xiii

For uses of the book in ways not covered by the license, permission of the author is required.
While it is not actually required by the license, I do appreciate hearing from people who
are using or distributing my work.
∗ ∗ ∗
A technical note on production: The on-line and PDF versions of this book are created
from a single source, which is written largely in XML. To produce the PDF version, the XML
is processed into a form that can be used by the TeX typesetting program. In addition to XML
files, the source includes DTDs, XSLT transformations, Java source code files, image files, a
TeX macro file, and a couple of scripts that are used in processing. The scripts work on Linux
and on Mac OS.
I have made the complete source files available for download at the following
address:
http://math.hws.edu/eck/cs124/downloads/javanotes7-full-source.zip
These files were not originally meant for publication, and therefore are not very cleanly
written. Furthermore, it requires a fair amount of expertise to use them. However, I have had
several requests for the sources and have made them available on an “as-is” basis. For more
information about the sources and how they are used see the README file from the source
download.
∗ ∗ ∗
Professor David J. Eck
Department of Mathematics and Computer Science
Hobart and William Smith Colleges
300 Pulteney Street
Geneva, New York 14456, USA
Email: eck@hws.edu
WWW: http://math.hws.edu/eck/
Chapter 1

Overview: The Mental Landscape

When you begin a journey, it’s a good idea to have a mental map of the terrain you’ll be
passing through. The same is true for an intellectual journey, such as learning to write computer
programs. In this case, you’ll need to know the basics of what computers are and how they
work. You’ll want to have some idea of what a computer program is and how one is created.
Since you will be writing programs in the Java programming language, you’ll want to know
something about that language in particular and about the modern computing environment for
which Java is designed.
As you read this chapter, don’t worry if you can’t understand everything in detail. (In fact,
it would be impossible for you to learn all the details from the brief expositions in this chapter.)
Concentrate on learning enough about the big ideas to orient yourself, in preparation for the
rest of the book. Most of what is covered in this chapter will be covered in much greater detail
later in the book.

1.1 The Fetch and Execute Cycle: Machine Language


A computer is a complex system consisting of many different components. But at the
heart—or the brain, if you want—of the computer is a single component that does the actual
computing. This is the Central Processing Unit, or CPU. In a modern desktop computer,
the CPU is a single “chip” on the order of one square inch in size. The job of the CPU is to
execute programs.
A program is simply a list of unambiguous instructions meant to be followed mechanically
by a computer. A computer is built to carry out instructions that are written in a very simple
type of language called machine language. Each type of computer has its own machine
language, and the computer can directly execute a program only if the program is expressed in
that language. (It can execute programs written in other languages if they are first translated
into machine language.)
When the CPU executes a program, that program is stored in the computer’s main mem-
ory (also called the RAM or random access memory). In addition to the program, memory
can also hold data that is being used or processed by the program. Main memory consists of a
sequence of locations. These locations are numbered, and the sequence number of a location
is called its address. An address provides a way of picking out one particular piece of informa-
tion from among the millions stored in memory. When the CPU needs to access the program
instruction or data in a particular location, it sends the address of that information as a sig-
nal to the memory; the memory responds by sending back the data contained in the specified

1
CHAPTER 1. THE MENTAL LANDSCAPE 2

location. The CPU can also store information in memory by specifying the information to be
stored and the address of the location where it is to be stored.
On the level of machine language, the operation of the CPU is fairly straightforward (al-
though it is very complicated in detail). The CPU executes a program that is stored as a
sequence of machine language instructions in main memory. It does this by repeatedly reading,
or fetching , an instruction from memory and then carrying out, or executing , that instruc-
tion. This process—fetch an instruction, execute it, fetch another instruction, execute it, and so
on forever—is called the fetch-and-execute cycle. With one exception, which will be covered
in the next section, this is all that the CPU ever does.
The details of the fetch-and-execute cycle are not terribly important, but there are a few
basic things you should know. The CPU contains a few internal registers, which are small
memory units capable of holding a single number or machine language instruction. The CPU
uses one of these registers—the program counter , or PC—to keep track of where it is in the
program it is executing. The PC simply stores the memory address of the next instruction that
the CPU should execute. At the beginning of each fetch-and-execute cycle, the CPU checks the
PC to see which instruction it should fetch. During the course of the fetch-and-execute cycle,
the number in the PC is updated to indicate the instruction that is to be executed in the next
cycle. (Usually, but not always, this is just the instruction that sequentially follows the current
instruction in the program.)
∗ ∗ ∗
A computer executes machine language programs mechanically—that is without under-
standing them or thinking about them—simply because of the way it is physically put together.
This is not an easy concept. A computer is a machine built of millions of tiny switches called
transistors, which have the property that they can be wired together in such a way that an
output from one switch can turn another switch on or off. As a computer computes, these
switches turn each other on or off in a pattern determined both by the way they are wired
together and by the program that the computer is executing.
Machine language instructions are expressed as binary numbers. A binary number is made
up of just two possible digits, zero and one. Each zero or one is called a bit. So, a machine
language instruction is just a sequence of zeros and ones. Each particular sequence encodes
some particular instruction. The data that the computer manipulates is also encoded as binary
numbers. In modern computers, each memory location holds a byte, which is a sequence of
eight bits. (A machine language instruction or a piece of data generally consists of several bytes,
stored in consecutive memory locations.)
A computer can work directly with binary numbers because switches can readily represent
such numbers: Turn the switch on to represent a one; turn it off to represent a zero. Machine
language instructions are stored in memory as patterns of switches turned on or off. When a
machine language instruction is loaded into the CPU, all that happens is that certain switches
are turned on or off in the pattern that encodes that instruction. The CPU is built to respond
to this pattern by executing the instruction it encodes; it does this simply because of the way
all the other switches in the CPU are wired together.
So, you should understand this much about how computers work: Main memory holds
machine language programs and data. These are encoded as binary numbers. The CPU fetches
machine language instructions from memory one after another and executes them. It does
this mechanically, without thinking about or understanding what it does—and therefore the
program it executes must be perfect, complete in all details, and unambiguous because the CPU
can do nothing but execute it exactly as written. Here is a schematic view of this first-stage
CHAPTER 1. THE MENTAL LANDSCAPE 3

understanding of the computer:

Memory
10001010 (Location 0)
00110100 (Location 1)
Data to Memory 01110111 (Location 2)
10100100 (Location 3)

CPU Data from Memory 11010010


10000110
(Location 4)
(Location 5)
01001111 (Location 6)
Program 10100000 (Location 7)
counter: 00000010 (Location 8)
0010110111001000 Address for 10100010 (Location 9)
reading/writing 00010100 (Location 10)
data
..
.

1.2 Asynchronous Events: Polling Loops and Interrupts


The CPU spends almost all of its time fetching instructions from memory and executing
them. However, the CPU and main memory are only two out of many components in a real
computer system. A complete system contains other devices such as:
• A hard disk or solid state drive for storing programs and data files. (Note that main
memory holds only a comparatively small amount of information, and holds it only as
long as the power is turned on. A hard disk or solid state drive is used for permanent
storage of larger amounts of information, but programs have to be loaded from there into
main memory before they can actually be executed. A hard disk stores data on a spinning
magnetic disk, while a solid state drive is a purely electronic device with no moving parts.)
• A keyboard and mouse for user input.
• A monitor and printer which can be used to display the computer’s output.
• An audio output device that allows the computer to play sounds.
• A network interface that allows the computer to communicate with other computers
that are connected to it on a network, either wirelessly or by wire.
• A scanner that converts images into coded binary numbers that can be stored and
manipulated on the computer.
The list of devices is entirely open ended, and computer systems are built so that they can
easily be expanded by adding new devices. Somehow the CPU has to communicate with and
control all these devices. The CPU can only do this by executing machine language instructions
(which is all it can do, period). The way this works is that for each device in a system, there
is a device driver , which consists of software that the CPU executes when it has to deal
with the device. Installing a new device on a system generally has two steps: plugging the
device physically into the computer, and installing the device driver software. Without the
device driver, the actual physical device would be useless, since the CPU would not be able to
communicate with it.
CHAPTER 1. THE MENTAL LANDSCAPE 4

∗ ∗ ∗
A computer system consisting of many devices is typically organized by connecting those
devices to one or more busses. A bus is a set of wires that carry various sorts of information
between the devices connected to those wires. The wires carry data, addresses, and control
signals. An address directs the data to a particular device and perhaps to a particular register
or location within that device. Control signals can be used, for example, by one device to alert
another that data is available for it on the data bus. A fairly simple computer system might
be organized like this:

CPU Empty Slot


for future
Memory Disk Drive Expansion

Input/ Data
Output Address
Controller Control

Display Keyboard Network


Interface

Now, devices such as keyboard, mouse, and network interface can produce input that needs
to be processed by the CPU. How does the CPU know that the data is there? One simple idea,
which turns out to be not very satisfactory, is for the CPU to keep checking for incoming data
over and over. Whenever it finds data, it processes it. This method is called polling , since
the CPU polls the input devices continually to see whether they have any input data to report.
Unfortunately, although polling is very simple, it is also very inefficient. The CPU can waste
an awful lot of time just waiting for input.
To avoid this inefficiency, interrupts are generally used instead of polling. An interrupt
is a signal sent by another device to the CPU. The CPU responds to an interrupt signal by
putting aside whatever it is doing in order to respond to the interrupt. Once it has handled
the interrupt, it returns to what it was doing before the interrupt occurred. For example, when
you press a key on your computer keyboard, a keyboard interrupt is sent to the CPU. The
CPU responds to this signal by interrupting what it is doing, reading the key that you pressed,
processing it, and then returning to the task it was performing before you pressed the key.
Again, you should understand that this is a purely mechanical process: A device signals an
interrupt simply by turning on a wire. The CPU is built so that when that wire is turned on,
the CPU saves enough information about what it is currently doing so that it can return to
the same state later. This information consists of the contents of important internal registers
such as the program counter. Then the CPU jumps to some predetermined memory location
and begins executing the instructions stored there. Those instructions make up an interrupt
handler that does the processing necessary to respond to the interrupt. (This interrupt handler
is part of the device driver software for the device that signaled the interrupt.) At the end of
the interrupt handler is an instruction that tells the CPU to jump back to what it was doing;
it does that by restoring its previously saved state.
CHAPTER 1. THE MENTAL LANDSCAPE 5

Interrupts allow the CPU to deal with asynchronous events. In the regular fetch-and-
execute cycle, things happen in a predetermined order; everything that happens is “synchro-
nized” with everything else. Interrupts make it possible for the CPU to deal efficiently with
events that happen “asynchronously,” that is, at unpredictable times.
As another example of how interrupts are used, consider what happens when the CPU needs
to access data that is stored on a hard disk. The CPU can access data directly only if it is
in main memory. Data on the disk has to be copied into memory before it can be accessed.
Unfortunately, on the scale of speed at which the CPU operates, the disk drive is extremely
slow. When the CPU needs data from the disk, it sends a signal to the disk drive telling it
to locate the data and get it ready. (This signal is sent synchronously, under the control of
a regular program.) Then, instead of just waiting the long and unpredictable amount of time
that the disk drive will take to do this, the CPU goes on with some other task. When the disk
drive has the data ready, it sends an interrupt signal to the CPU. The interrupt handler can
then read the requested data.
∗ ∗ ∗
Now, you might have noticed that all this only makes sense if the CPU actually has several
tasks to perform. If it has nothing better to do, it might as well spend its time polling for input
or waiting for disk drive operations to complete. All modern computers use multitasking to
perform several tasks at once. Some computers can be used by several people at once. Since the
CPU is so fast, it can quickly switch its attention from one user to another, devoting a fraction
of a second to each user in turn. This application of multitasking is called timesharing . But a
modern personal computer with just a single user also uses multitasking. For example, the user
might be typing a paper while a clock is continuously displaying the time and a file is being
downloaded over the network.
Each of the individual tasks that the CPU is working on is called a thread . (Or a process;
there are technical differences between threads and processes, but they are not important here,
since it is threads that are used in Java.) Many CPUs can literally execute more than one
thread simultaneously—such CPUs contain multiple “cores,” each of which can run a thread—
but there is always a limit on the number of threads that can be executed at the same time.
Since there are often more threads than can be executed simultaneously, the computer has to be
able switch its attention from one thread to another, just as a timesharing computer switches
its attention from one user to another. In general, a thread that is being executed will continue
to run until one of several things happens:
• The thread might voluntarily yield control, to give other threads a chance to run.
• The thread might have to wait for some asynchronous event to occur. For example, the
thread might request some data from the disk drive, or it might wait for the user to press
a key. While it is waiting, the thread is said to be blocked , and other threads, if any, have
a chance to run. When the event occurs, an interrupt will “wake up” the thread so that
it can continue running.
• The thread might use up its allotted slice of time and be suspended to allow other threads
to run. Not all computers can “forcibly” suspend a thread in this way; those that can are
said to use preemptive multitasking . To do preemptive multitasking, a computer needs
a special timer device that generates an interrupt at regular intervals, such as 100 times
per second. When a timer interrupt occurs, the CPU has a chance to switch from one
thread to another, whether the thread that is currently running likes it or not. All modern
desktop and laptop computers, and even typical smartphones and tablets, use preemptive
CHAPTER 1. THE MENTAL LANDSCAPE 6

multitasking.
Ordinary users, and indeed ordinary programmers, have no need to deal with interrupts and
interrupt handlers. They can concentrate on the different tasks or threads that they want the
computer to perform; the details of how the computer manages to get all those tasks done are
not important to them. In fact, most users, and many programmers, can ignore threads and
multitasking altogether. However, threads have become increasingly important as computers
have become more powerful and as they have begun to make more use of multitasking and
multiprocessing. In fact, the ability to work with threads is fast becoming an essential job skill
for programmers. Fortunately, Java has good support for threads, which are built into the Java
programming language as a fundamental programming concept. Programming with threads
will be covered in Chapter 12.
Just as important in Java and in modern programming in general is the basic concept of
asynchronous events. While programmers don’t actually deal with interrupts directly, they do
often find themselves writing event handlers, which, like interrupt handlers, are called asyn-
chronously when specific events occur. Such “event-driven programming” has a very different
feel from the more traditional straight-through, synchronous programming. We will begin with
the more traditional type of programming, which is still used for programming individual tasks,
but we will return to threads and events later in the text, starting in Chapter 6
∗ ∗ ∗
By the way, the software that does all the interrupt handling, handles communication with
the user and with hardware devices, and controls which thread is allowed to run is called the
operating system. The operating system is the basic, essential software without which a
computer would not be able to function. Other programs, such as word processors and Web
browsers, are dependent upon the operating system. Common operating systems include Linux,
various versions of Windows, and Mac OS.

1.3 The Java Virtual Machine


Machine language consists of very simple instructions that can be executed directly by
the CPU of a computer. Almost all programs, though, are written in high-level programming
languages such as Java, Fortran, or C++. A program written in a high-level language cannot
be run directly on any computer. First, it has to be translated into machine language. This
translation can be done by a program called a compiler . A compiler takes a high-level-language
program and translates it into an executable machine-language program. Once the translation
is done, the machine-language program can be run any number of times, but of course it can only
be run on one type of computer (since each type of computer has its own individual machine
language). If the program is to run on another type of computer it has to be re-translated,
using a different compiler, into the appropriate machine language.
There is an alternative to compiling a high-level language program. Instead of using a
compiler, which translates the program all at once, you can use an interpreter , which translates
it instruction-by-instruction, as necessary. An interpreter is a program that acts much like a
CPU, with a kind of fetch-and-execute cycle. In order to execute a program, the interpreter
runs in a loop in which it repeatedly reads one instruction from the program, decides what is
necessary to carry out that instruction, and then performs the appropriate machine-language
commands to do so.
CHAPTER 1. THE MENTAL LANDSCAPE 7

One use of interpreters is to execute high-level language programs. For example, the pro-
gramming language Lisp is usually executed by an interpreter rather than a compiler. However,
interpreters have another purpose: they can let you use a machine-language program meant
for one type of computer on a completely different type of computer. For example, one of the
original home computers was the Commodore 64 or “C64”. While you might not find an actual
C64, you can find programs that run on other computers—or even in a web browser—that
“emulate” one. Such an emulator can run C64 programs by acting as an interpreter for the
C64 machine language.
∗ ∗ ∗
The designers of Java chose to use a combination of compilation and interpreting. Pro-
grams written in Java are compiled into machine language, but it is a machine language for
a computer that doesn’t really exist. This so-called “virtual” computer is known as the Java
Virtual Machine, or JVM. The machine language for the Java Virtual Machine is called Java
bytecode. There is no reason why Java bytecode couldn’t be used as the machine language of a
real computer, rather than a virtual computer. But in fact the use of a virtual machine makes
possible one of the main selling points of Java: the fact that it can actually be used on any
computer. All that the computer needs is an interpreter for Java bytecode. Such an interpreter
simulates the JVM in the same way that a C64 emulator simulates a Commodore 64 computer.
(The term JVM is also used for the Java bytecode interpreter program that does the simulation,
so we say that a computer needs a JVM in order to run Java programs. Technically, it would
be more correct to say that the interpreter implements the JVM than to say that it is a JVM.)
Of course, a different Java bytecode interpreter is needed for each type of computer, but
once a computer has a Java bytecode interpreter, it can run any Java bytecode program, and
the same program can be run on any computer that has such an interpreter. This is one of the
essential features of Java: the same compiled program can be run on many different types of
computers.

Java Interperter
for Mac OS

Java
Java Java Interperter
Compiler Bytecode
Program for Windows
Program

Java Interperter
for Linux

Why, you might wonder, use the intermediate Java bytecode at all? Why not just distribute
the original Java program and let each person compile it into the machine language of whatever
computer they want to run it on? There are several reasons. First of all, a compiler has to
understand Java, a complex high-level language. The compiler is itself a complex program.
A Java bytecode interpreter, on the other hand, is a relatively small, simple program. This
makes it easy to write a bytecode interpreter for a new type of computer; once that is done,
that computer can run any compiled Java program. It would be much harder to write a Java
compiler for the same computer.
Furthermore, some Java programs are meant to be downloaded over a network. This leads
to obvious security concerns: you don’t want to download and run a program that will damage
CHAPTER 1. THE MENTAL LANDSCAPE 8

your computer or your files. The bytecode interpreter acts as a buffer between you and the
program you download. You are really running the interpreter, which runs the downloaded
program indirectly. The interpreter can protect you from potentially dangerous actions on the
part of that program.
When Java was still a new language, it was criticized for being slow: Since Java bytecode was
executed by an interpreter, it seemed that Java bytecode programs could never run as quickly
as programs compiled into native machine language (that is, the actual machine language of the
computer on which the program is running). However, this problem has been largely overcome
by the use of just-in-time compilers for executing Java bytecode. A just-in-time compiler
translates Java bytecode into native machine language. It does this while it is executing the
program. Just as for a normal interpreter, the input to a just-in-time compiler is a Java bytecode
program, and its task is to execute that program. But as it is executing the program, it also
translates parts of it into machine language. The translated parts of the program can then be
executed much more quickly than they could be interpreted. Since a given part of a program is
often executed many times as the program runs, a just-in-time compiler can significantly speed
up the overall execution time.
I should note that there is no necessary connection between Java and Java bytecode. A
program written in Java could certainly be compiled into the machine language of a real com-
puter. And programs written in other languages can be compiled into Java bytecode. However,
the combination of Java and Java bytecode is platform-independent, secure, and network-
compatible while allowing you to program in a modern high-level object-oriented language.
(In the past few years, it has become fairly common to create new programming languages,
or versions of old languages, that compile into Java bytecode. The compiled bytecode programs
can then be executed by a standard JVM. New languages that have been developed specifically
for programming the JVM include Groovy, Clojure, and Processing. Jython and JRuby are
versions of older languages, Python and Ruby, that target the JVM. These languages make it
possible to enjoy many of the advantages of the JVM while avoiding some of the technicalities
of the Java language. In fact, the use of other languages with the JVM has become important
enough that several new features have been added to the JVM specifically to add better support
for some of those languages. And this improvement to the JVM has in turn made possible some
of the new features in Java 7 and Java 8.)
∗ ∗ ∗
I should also note that the really hard part of platform-independence is providing a “Graph-
ical User Interface”—with windows, buttons, etc.—that will work on all the platforms that
support Java. You’ll see more about this problem in Section 1.6.

1.4 Fundamental Building Blocks of Programs


There are two basic aspects of programming: data and instructions. To work with
data, you need to understand variables and types; to work with instructions, you need to
understand control structures and subroutines. You’ll spend a large part of the course
becoming familiar with these concepts.
A variable is just a memory location (or several consecutive locations treated as a unit)
that has been given a name so that it can be easily referred to and used in a program. The
programmer only has to worry about the name; it is the compiler’s responsibility to keep track
of the memory location. As a programmer, you need to keep in mind that the name refers to
CHAPTER 1. THE MENTAL LANDSCAPE 9

a kind of “box” in memory that can hold data, even though you don’t have to know where in
memory that box is located.
In Java and in many other programming languages, a variable has a type that indicates
what sort of data it can hold. One type of variable might hold integers—whole numbers such as
3, -7, and 0—while another holds floating point numbers—numbers with decimal points such as
3.14, -2.7, or 17.0. (Yes, the computer does make a distinction between the integer 17 and the
floating-point number 17.0; they actually look quite different inside the computer.) There could
also be types for individual characters (’A’, ’;’, etc.), strings (“Hello”, “A string can include
many characters”, etc.), and less common types such as dates, colors, sounds, or any other kind
of data that a program might need to store.
Programming languages always have commands for getting data into and out of variables
and for doing computations with data. For example, the following “assignment statement,”
which might appear in a Java program, tells the computer to take the number stored in the
variable named “principal”, multiply that number by 0.07, and then store the result in the
variable named “interest”:
interest = principal * 0.07;
There are also “input commands” for getting data from the user or from files on the computer’s
disks, and there are “output commands” for sending data in the other direction.
These basic commands—for moving data from place to place and for performing
computations—are the building blocks for all programs. These building blocks are combined
into complex programs using control structures and subroutines.
∗ ∗ ∗
A program is a sequence of instructions. In the ordinary “flow of control,” the computer
executes the instructions in the sequence in which they occur in the program, one after the
other. However, this is obviously very limited: the computer would soon run out of instructions
to execute. Control structures are special instructions that can change the flow of control.
There are two basic types of control structure: loops, which allow a sequence of instructions
to be repeated over and over, and branches, which allow the computer to decide between two
or more different courses of action by testing conditions that occur as the program is running.
For example, it might be that if the value of the variable “principal” is greater than 10000,
then the “interest” should be computed by multiplying the principal by 0.05; if not, then the
interest should be computed by multiplying the principal by 0.04. A program needs some
way of expressing this type of decision. In Java, it could be expressed using the following “if
statement”:
if (principal > 10000)
interest = principal * 0.05;
else
interest = principal * 0.04;
(Don’t worry about the details for now. Just remember that the computer can test a condition
and decide what to do next on the basis of that test.)
Loops are used when the same task has to be performed more than once. For example,
if you want to print out a mailing label for each name on a mailing list, you might say, “Get
the first name and address and print the label; get the second name and address and print
the label; get the third name and address and print the label. . . ” But this quickly becomes
ridiculous—and might not work at all if you don’t know in advance how many names there are.
What you would like to say is something like “While there are more names to process, get the
CHAPTER 1. THE MENTAL LANDSCAPE 10

next name and address, and print the label.” A loop can be used in a program to express such
repetition.
∗ ∗ ∗
Large programs are so complex that it would be almost impossible to write them if there
were not some way to break them up into manageable “chunks.” Subroutines provide one way to
do this. A subroutine consists of the instructions for performing some task, grouped together
as a unit and given a name. That name can then be used as a substitute for the whole set of
instructions. For example, suppose that one of the tasks that your program needs to perform
is to draw a house on the screen. You can take the necessary instructions, make them into
a subroutine, and give that subroutine some appropriate name—say, “drawHouse()”. Then
anyplace in your program where you need to draw a house, you can do so with the single
command:
drawHouse();
This will have the same effect as repeating all the house-drawing instructions in each place.
The advantage here is not just that you save typing. Organizing your program into sub-
routines also helps you organize your thinking and your program design effort. While writing
the house-drawing subroutine, you can concentrate on the problem of drawing a house without
worrying for the moment about the rest of the program. And once the subroutine is written,
you can forget about the details of drawing houses—that problem is solved, since you have a
subroutine to do it for you. A subroutine becomes just like a built-in part of the language which
you can use without thinking about the details of what goes on “inside” the subroutine.
∗ ∗ ∗
Variables, types, loops, branches, and subroutines are the basis of what might be called
“traditional programming.” However, as programs become larger, additional structure is needed
to help deal with their complexity. One of the most effective tools that has been found is object-
oriented programming, which is discussed in the next section.

1.5 Objects and Object-oriented Programming


Programs must be designed. No one can just sit down at the computer and compose a
program of any complexity. The discipline called software engineering is concerned with
the construction of correct, working, well-written programs. The software engineer tries to
use accepted and proven methods for analyzing the problem to be solved and for designing a
program to solve that problem.
During the 1970s and into the 80s, the primary software engineering methodology was
structured programming . The structured programming approach to program design was
based on the following advice: To solve a large problem, break the problem into several pieces
and work on each piece separately; to solve each piece, treat it as a new problem which can itself
be broken down into smaller problems; eventually, you will work your way down to problems
that can be solved directly, without further decomposition. This approach is called top-down
programming .
There is nothing wrong with top-down programming. It is a valuable and often-used ap-
proach to problem-solving. However, it is incomplete. For one thing, it deals almost entirely
with producing the instructions necessary to solve a problem. But as time went on, people
realized that the design of the data structures for a program was at least as important as the
CHAPTER 1. THE MENTAL LANDSCAPE 11

design of subroutines and control structures. Top-down programming doesn’t give adequate
consideration to the data that the program manipulates.
Another problem with strict top-down programming is that it makes it difficult to reuse
work done for other projects. By starting with a particular problem and subdividing it into
convenient pieces, top-down programming tends to produce a design that is unique to that
problem. It is unlikely that you will be able to take a large chunk of programming from another
program and fit it into your project, at least not without extensive modification. Producing
high-quality programs is difficult and expensive, so programmers and the people who employ
them are always eager to reuse past work.
∗ ∗ ∗
So, in practice, top-down design is often combined with bottom-up design. In bottom-up
design, the approach is to start “at the bottom,” with problems that you already know how to
solve (and for which you might already have a reusable software component at hand). From
there, you can work upwards towards a solution to the overall problem.
The reusable components should be as “modular” as possible. A module is a component of a
larger system that interacts with the rest of the system in a simple, well-defined, straightforward
manner. The idea is that a module can be “plugged into” a system. The details of what goes on
inside the module are not important to the system as a whole, as long as the module fulfills its
assigned role correctly. This is called information hiding , and it is one of the most important
principles of software engineering.
One common format for software modules is to contain some data, along with some sub-
routines for manipulating that data. For example, a mailing-list module might contain a list of
names and addresses along with a subroutine for adding a new name, a subroutine for printing
mailing labels, and so forth. In such modules, the data itself is often hidden inside the module;
a program that uses the module can then manipulate the data only indirectly, by calling the
subroutines provided by the module. This protects the data, since it can only be manipulated
in known, well-defined ways. And it makes it easier for programs to use the module, since they
don’t have to worry about the details of how the data is represented. Information about the
representation of the data is hidden.
Modules that could support this kind of information-hiding became common in program-
ming languages in the early 1980s. Since then, a more advanced form of the same idea has
more or less taken over software engineering. This latest approach is called object-oriented
programming , often abbreviated as OOP.
The central concept of object-oriented programming is the object, which is a kind of module
containing data and subroutines. The point-of-view in OOP is that an object is a kind of self-
sufficient entity that has an internal state (the data it contains) and that can respond to
messages (calls to its subroutines). A mailing list object, for example, has a state consisting
of a list of names and addresses. If you send it a message telling it to add a name, it will
respond by modifying its state to reflect the change. If you send it a message telling it to print
itself, it will respond by printing out its list of names and addresses.
The OOP approach to software engineering is to start by identifying the objects involved in
a problem and the messages that those objects should respond to. The program that results is
a collection of objects, each with its own data and its own set of responsibilities. The objects
interact by sending messages to each other. There is not much “top-down” in the large-scale
design of such a program, and people used to more traditional programs can have a hard time
getting used to OOP. However, people who use OOP would claim that object-oriented programs
tend to be better models of the way the world itself works, and that they are therefore easier
CHAPTER 1. THE MENTAL LANDSCAPE 12

to write, easier to understand, and more likely to be correct.


∗ ∗ ∗
You should think of objects as “knowing” how to respond to certain messages. Different
objects might respond to the same message in different ways. For example, a “print” message
would produce very different results, depending on the object it is sent to. This property of
objects—that different objects can respond to the same message in different ways—is called
polymorphism.
It is common for objects to bear a kind of “family resemblance” to one another. Objects
that contain the same type of data and that respond to the same messages in the same way
belong to the same class. (In actual programming, the class is primary; that is, a class is
created and then one or more objects are created using that class as a template.) But objects
can be similar without being in exactly the same class.
For example, consider a drawing program that lets the user draw lines, rectangles, ovals,
polygons, and curves on the screen. In the program, each visible object on the screen could be
represented by a software object in the program. There would be five classes of objects in the
program, one for each type of visible object that can be drawn. All the lines would belong to
one class, all the rectangles to another class, and so on. These classes are obviously related;
all of them represent “drawable objects.” They would, for example, all presumably be able to
respond to a “draw yourself” message. Another level of grouping, based on the data needed to
represent each type of object, is less obvious, but would be very useful in a program: We can
group polygons and curves together as “multipoint objects,” while lines, rectangles, and ovals
are “two-point objects.” (A line is determined by its two endpoints, a rectangle by two of its
corners, and an oval by two corners of the rectangle that contains it. The rectangles that I am
talking about here have sides that are vertical and horizontal, so that they can be specified by
just two points; this is the common meaning of “rectangle” in drawing programs.) We could
diagram these relationships as follows:

DrawableObject

MultipointObject TwoPointObject

Polygon Curve Line Rectangle Oval

DrawableObject, MultipointObject, and TwoPointObject would be classes in the program.


MultipointObject and TwoPointObject would be subclasses of DrawableObject. The class
Line would be a subclass of TwoPointObject and (indirectly) of DrawableObject. A subclass of
a class is said to inherit the properties of that class. The subclass can add to its inheritance and
it can even “override” part of that inheritance (by defining a different response to some method).
Nevertheless, lines, rectangles, and so on are drawable objects, and the class DrawableObject
expresses this relationship.
Inheritance is a powerful means for organizing a program. It is also related to the problem
of reusing software components. A class is the ultimate reusable component. Not only can it
CHAPTER 1. THE MENTAL LANDSCAPE 13

be reused directly if it fits exactly into a program you are trying to write, but if it just almost
fits, you can still reuse it by defining a subclass and making only the small changes necessary
to adapt it exactly to your needs.
So, OOP is meant to be both a superior program-development tool and a partial solution
to the software reuse problem. Objects, classes, and object-oriented programming will be
important themes throughout the rest of this text. You will start using objects that are built
into the Java language in the next chapter, and in Chapter 5 you will begin creating your own
classes and objects.

1.6 The Modern User Interface


When computers were first introduced, ordinary people—including most programmers—
couldn’t get near them. They were locked up in rooms with white-coated attendants who would
take your programs and data, feed them to the computer, and return the computer’s response
some time later. When timesharing—where the computer switches its attention rapidly from
one person to another—was invented in the 1960s, it became possible for several people to
interact directly with the computer at the same time. On a timesharing system, users sit at
“terminals” where they type commands to the computer, and the computer types back its re-
sponse. Early personal computers also used typed commands and responses, except that there
was only one person involved at a time. This type of interaction between a user and a computer
is called a command-line interface.
Today, of course, most people interact with computers in a completely different way. They
use a Graphical User Interface, or GUI. The computer draws interface components on the
screen. The components include things like windows, scroll bars, menus, buttons, and icons.
Usually, a mouse is used to manipulate such components or, on “touchscreens,” your fingers.
Assuming that you have not just been teleported in from the 1970s, you are no doubt already
familiar with the basics of graphical user interfaces!
A lot of GUI interface components have become fairly standard. That is, they have similar
appearance and behavior on many different computer platforms including Mac OS, Windows,
and Linux. Java programs, which are supposed to run on many different platforms without
modification to the program, can use all the standard GUI components. They might vary a
little in appearance from platform to platform, but their functionality should be identical on
any computer on which the program runs.
Shown below is an image of a very simple Java program that demonstrates a few standard
GUI interface components. When the program is run, a window similar to the picture shown
here will open on the computer screen. There are four components in the window with which the
user can interact: a button, a checkbox, a text field, and a pop-up menu. These components
are labeled. There are a few other components in the window. The labels themselves are
components (even though you can’t interact with them). The right half of the window is a
text area component, which can display multiple lines of text. A scrollbar component appears
alongside the text area when the number of lines of text becomes larger than will fit in the
text area. And in fact, in Java terminology, the whole window is itself considered to be a
“component.”
CHAPTER 1. THE MENTAL LANDSCAPE 14

(If you would like to run this program, the source code, GUIDemo.java, as well as a compiled
program, GUIDemo.jar, are available on line. For more information on using this and other
examples from this textbook, see Section 2.6.)
Now, Java actually has two complete sets of GUI components. One of these, the AWT or
Abstract Windowing Toolkit, was available in the original version of Java. The other, which
is known as Swing , was introduced in Java version 1.2, and is used in preference to the AWT
in most modern Java programs. The program that is shown above uses components that are
part of Swing.
When a user interacts with GUI components, “events” are generated. For example, clicking
a push button generates an event, and pressing return while typing in a text field generates an
event. Each time an event is generated, a message is sent to the program telling it that the
event has occurred, and the program responds according to its program. In fact, a typical GUI
program consists largely of “event handlers” that tell the program how to respond to various
types of events. In this example, the program has been programmed to respond to each event
by displaying a message in the text area. In a more realistic example, the event handlers would
have more to do.
The use of the term “message” here is deliberate. Messages, as you saw in the previous sec-
tion, are sent to objects. In fact, Java GUI components are implemented as objects. Java
includes many predefined classes that represent various types of GUI components. Some of
these classes are subclasses of others. Here is a diagram showing just a few of Swing’s GUI
classes and their relationships:

JComponent

JLabel JAbstractButton JComboBox JSlider JTextComponent

JButton JToggleButton JTextField JTextArea

JCheckBox JRadioButton

Don’t worry about the details for now, but try to get some feel about how object-oriented
programming and inheritance are used here. Note that all the GUI classes are subclasses,
directly or indirectly, of a class called JComponent, which represents general properties that are
shared by all Swing components. In the diagram, two of the direct subclasses of JComponent
themselves have subclasses. The classes JTextArea and JTextField, which have certain behaviors
CHAPTER 1. THE MENTAL LANDSCAPE 15

in common, are grouped together as subclasses of JTextComponent. Similarly JButton and


JToggleButton are subclasses of JAbstractButton, which represents properties common to both
buttons and checkboxes. (JComboBox, by the way, is the Swing class that represents pop-up
menus.)
Just from this brief discussion, perhaps you can see how GUI programming can make effec-
tive use of object-oriented design. In fact, GUIs, with their “visible objects,” are probably a
major factor contributing to the popularity of OOP.
Programming with GUI components and events is one of the most interesting aspects of
Java. However, we will spend several chapters on the basics before returning to this topic in
Chapter 6.

1.7 The Internet and Beyond


Computers can be connected together on networks. A computer on a network can
communicate with other computers on the same network by exchanging data and files or by
sending and receiving messages. Computers on a network can even work together on a large
computation.
Today, millions of computers throughout the world are connected to a single huge network
called the Internet. New computers are being connected to the Internet every day, both
by wireless communication and by physical connection using technologies such as DSL, cable
modems, and Ethernet.
There are elaborate protocols for communication over the Internet. A protocol is simply a
detailed specification of how communication is to proceed. For two computers to communicate
at all, they must both be using the same protocols. The most basic protocols on the Internet are
the Internet Protocol (IP), which specifies how data is to be physically transmitted from one
computer to another, and the Transmission Control Protocol (TCP), which ensures that
data sent using IP is received in its entirety and without error. These two protocols, which are
referred to collectively as TCP/IP, provide a foundation for communication. Other protocols
use TCP/IP to send specific types of information such as web pages, electronic mail, and data
files.
All communication over the Internet is in the form of packets. A packet consists of some
data being sent from one computer to another, along with addressing information that indicates
where on the Internet that data is supposed to go. Think of a packet as an envelope with an
address on the outside and a message on the inside. (The message is the data.) The packet
also includes a “return address,” that is, the address of the sender. A packet can hold only
a limited amount of data; longer messages must be divided among several packets, which are
then sent individually over the net and reassembled at their destination.
Every computer on the Internet has an IP address, a number that identifies it uniquely
among all the computers on the net. (Actually, the claim about uniqueness is not quite true, but
the basic idea is valid, and the full truth is complicated.) The IP address is used for addressing
packets. A computer can only send data to another computer on the Internet if it knows that
computer’s IP address. Since people prefer to use names rather than numbers, most computers
are also identified by names, called domain names. For example, the main computer of
the Mathematics Department at Hobart and William Smith Colleges has the domain name
math.hws.edu. (Domain names are just for convenience; your computer still needs to know
IP addresses before it can communicate. There are computers on the Internet whose job it
is to translate domain names to IP addresses. When you use a domain name, your computer
CHAPTER 1. THE MENTAL LANDSCAPE 16

sends a message to a domain name server to find out the corresponding IP address. Then, your
computer uses the IP address, rather than the domain name, to communicate with the other
computer.)
The Internet provides a number of services to the computers connected to it (and, of course,
to the users of those computers). These services use TCP/IP to send various types of data over
the net. Among the most popular services are instant messaging, file sharing, electronic mail,
and the World-Wide Web. Each service has its own protocols, which are used to control
transmission of data over the network. Each service also has some sort of user interface, which
allows the user to view, send, and receive data through the service.
For example, the email service uses a protocol known as SMTP (Simple Mail Transfer
Protocol) to transfer email messages from one computer to another. Other protocols, such as
POP and IMAP, are used to fetch messages from an email account so that the recipient can
read them. A person who uses email, however, doesn’t need to understand or even know about
these protocols. Instead, they are used behind the scenes by computer programs to send and
receive email messages. These programs provide the user with an easy-to-use user interface to
the underlying network protocols.
The World-Wide Web is perhaps the most exciting of network services. The World-Wide
Web allows you to request pages of information that are stored on computers all over the
Internet. A Web page can contain links to other pages on the same computer from which it
was obtained or to other computers anywhere in the world. A computer that stores such pages
of information is called a web server . The user interface to the Web is the type of program
known as a web browser . Common web browsers include Internet Explorer, Firefox, Chrome,
and Safari. You use a Web browser to request a page of information. The browser sends a
request for that page to the computer on which the page is stored, and when a response is
received from that computer, the web browser displays it to you in a neatly formatted form.
A web browser is just a user interface to the Web. Behind the scenes, the web browser uses a
protocol called HTTP (HyperText Transfer Protocol) to send each page request and to receive
the response from the web server.
∗ ∗ ∗
Now just what, you might be thinking, does all this have to do with Java? In fact, Java
is intimately associated with the Internet and the World-Wide Web. When Java was first
introduced, one of its big attractions was the ability to write applets. An applet is a small
program that is transmitted over the Internet and that runs on a web page. Applets make it
possible for a web page to perform complex tasks and have complex interactions with the user.
Alas, applets have suffered from a variety of security problems, and fixing those problems has
made them more difficult to use. Applets have become much less common on the Web, and in
any case, there are other options for running programs on Web pages.
But applets are only one aspect of Java’s relationship with the Internet. Java can be used to
write complex, stand-alone applications that do not depend on a Web browser. Many of these
programs are network-related. For example many of the largest and most complex web sites
use web server software that is written in Java. Java includes excellent support for network
protocols, and its platform independence makes it possible to write network programs that
work on many different types of computer. You will learn about Java’s network support in
Chapter 11.
Its support for networking is not Java’s only advantage. But many good programming
languages have been invented only to be soon forgotten. Java has had the good luck to ride on
the coattails of the Internet’s immense and increasing popularity.
CHAPTER 1. THE MENTAL LANDSCAPE 17

∗ ∗ ∗
As Java has matured, its applications have reached far beyond the Net. The standard version
of Java already comes with support for many technologies, such as cryptography and data
compression. Free extensions are available to support many other technologies such as advanced
sound processing and three-dimensional graphics. Complex, high-performance systems can be
developed in Java. For example, Hadoop, a system for large scale data processing, is written in
Java. Hadoop is used by Yahoo, Facebook, and other Web sites to process the huge amounts
of data generated by their users.
Furthermore, Java is not restricted to use on traditional computers. Java can be used to
write programs for many smartphones (though not for the iPhone). It is the primary develop-
ment language for Android-based devices. (Some mobile devices use a version of Java called
Java ME (“Mobile Edition”), but Android uses Google’s own version of Java and does not use
the same graphical user interface components as standard Java.) Java is also the programming
language for the Amazon Kindle eBook reader and for interactive features on Blu-Ray video
disks.
At this time, Java certainly ranks as one of the most widely used programming languages.
It is a good choice for almost any programming project that is meant to run on more than
one type of computing device, and is a reasonable choice even for many programs that will
run on only one device. It is probably still the most widely taught language at Colleges and
Universities. It is similar enough to other popular languages, such as C, C++, and Python,
that knowing it will give you a good start on learning those languages as well. Overall, learning
Java is a great starting point on the road to becoming an expert programmer. I hope you enjoy
the journey!
Quiz 18

Quiz on Chapter 1
(answers)

1. One of the components of a computer is its CPU. What is a CPU and what role does it
play in a computer?

2. Explain what is meant by an “asynchronous event.” Give some examples.

3. What is the difference between a “compiler” and an “interpreter”?

4. Explain the difference between high-level languages and machine language.

5. If you have the source code for a Java program, and you want to run that program, you
will need both a compiler and an interpreter. What does the Java compiler do, and what
does the Java interpreter do?

6. What is a subroutine?

7. Java is an object-oriented programming language. What is an object?

8. What is a variable? (There are four different ideas associated with variables in Java. Try
to mention all four aspects in your answer. Hint: One of the aspects is the variable’s
name.)

9. Java is a “platform-independent language.” What does this mean?

10. What is the “Internet”? Give some examples of how it is used. (What kind of services
does it provide?)
Chapter 2

Programming in the Small I:


Names and Things

On a basic level (the level of machine language), a computer can perform only very simple
operations. A computer performs complex tasks by stringing together large numbers of such
operations. Such tasks must be “scripted” in complete and perfect detail by programs. Creating
complex programs will never be really easy, but the difficulty can be handled to some extent by
giving the program a clear overall structure. The design of the overall structure of a program
is what I call “programming in the large.”
Programming in the small, which is sometimes called coding , would then refer to filling in
the details of that design. The details are the explicit, step-by-step instructions for performing
fairly small-scale tasks. When you do coding, you are working “close to the machine,” with some
of the same concepts that you might use in machine language: memory locations, arithmetic
operations, loops and branches. In a high-level language such as Java, you get to work with
these concepts on a level several steps above machine language. However, you still have to
worry about getting all the details exactly right.
This chapter and the next examine the facilities for programming in the small in the Java
programming language. Don’t be misled by the term “programming in the small” into thinking
that this material is easy or unimportant. This material is an essential foundation for all types
of programming. If you don’t understand it, you can’t write programs, no matter how good
you get at designing their large-scale structure.
The last section of this chapter discusses programming environments. That section
contains information about how to compile and run Java programs, and you should take a look
at it before trying to write and use your own programs or trying to use the sample programs
in this book.

2.1 The Basic Java Application


A program is a sequence of instructions that a computer can execute to perform some
task. A simple enough idea, but for the computer to make any use of the instructions, they
must be written in a form that the computer can use. This means that programs have to be
written in programming languages. Programming languages differ from ordinary human
languages in being completely unambiguous and very strict about what is and is not allowed
in a program. The rules that determine what is allowed are called the syntax of the language.
Syntax rules specify the basic vocabulary of the language and how programs can be constructed

19
CHAPTER 2. NAMES AND THINGS 20

using things like loops, branches, and subroutines. A syntactically correct program is one that
can be successfully compiled or interpreted; programs that have syntax errors will be rejected
(hopefully with a useful error message that will help you fix the problem).
So, to be a successful programmer, you have to develop a detailed knowledge of the syntax
of the programming language that you are using. However, syntax is only part of the story. It’s
not enough to write a program that will run—you want a program that will run and produce
the correct result! That is, the meaning of the program has to be right. The meaning of
a program is referred to as its semantics. More correctly, the semantics of a programming
language is the set of rules that determine the meaning of a program written in that language.
A semantically correct program is one that does what you want it to.
Furthermore, a program can be syntactically and semantically correct but still be a pretty
bad program. Using the language correctly is not the same as using it well. For example, a
good program has “style.” It is written in a way that will make it easy for people to read and
to understand. It follows conventions that will be familiar to other programmers. And it has
an overall design that will make sense to human readers. The computer is completely oblivious
to such things, but to a human reader, they are paramount. These aspects of programming are
sometimes referred to as pragmatics. (I will often use the more common term style.)
When I introduce a new language feature, I will explain the syntax, the semantics, and
some of the pragmatics of that feature. You should memorize the syntax; that’s the easy part.
Then you should get a feeling for the semantics by following the examples given, making sure
that you understand how they work, and, ideally, writing short programs of your own to test
your understanding. And you should try to appreciate and absorb the pragmatics—this means
learning how to use the language feature well, with style that will earn you the admiration of
other programmers.
Of course, even when you’ve become familiar with all the individual features of the language,
that doesn’t make you a programmer. You still have to learn how to construct complex programs
to solve particular problems. For that, you’ll need both experience and taste. You’ll find hints
about software development throughout this textbook.
∗ ∗ ∗
We begin our exploration of Java with the problem that has become traditional for such
beginnings: to write a program that displays the message “Hello World!”. This might seem like
a trivial problem, but getting a computer to do this is really a big first step in learning a new
programming language (especially if it’s your first programming language). It means that you
understand the basic process of:
1. getting the program text into the computer,
2. compiling the program, and
3. running the compiled program.
The first time through, each of these steps will probably take you a few tries to get right. I
won’t go into the details here of how you do each of these steps; it depends on the particular
computer and Java programming environment that you are using. See Section 2.6 for informa-
tion about creating and running Java programs in specific programming environments. But in
general, you will type the program using some sort of text editor and save the program in a file.
Then, you will use some command to try to compile the file. You’ll either get a message that the
program contains syntax errors, or you’ll get a compiled version of the program. In the case of
Java, the program is compiled into Java bytecode, not into machine language. Finally, you can
run the compiled program by giving some appropriate command. For Java, you will actually use
CHAPTER 2. NAMES AND THINGS 21

an interpreter to execute the Java bytecode. Your programming environment might automate
some of the steps for you—for example, the compilation step is often done automatically—but
you can be sure that the same three steps are being done in the background.
Here is a Java program to display the message “Hello World!”. Don’t expect to understand
what’s going on here just yet; some of it you won’t really understand until a few chapters from
now:
/** A program to display the message
* "Hello World!" on standard output.
*/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
} // end of class HelloWorld
The command that actually displays the message is:
System.out.println("Hello World!");
This command is an example of a subroutine call statement. It uses a “built-in subroutine”
named System.out.println to do the actual work. Recall that a subroutine consists of the
instructions for performing some task, chunked together and given a name. That name can be
used to “call” the subroutine whenever that task needs to be performed. A built-in subroutine
is one that is already defined as part of the language and therefore automatically available for
use in any program.
When you run this program, the message “Hello World!” (without the quotes) will be
displayed on standard output. Unfortunately, I can’t say exactly what that means! Java is
meant to run on many different platforms, and standard output will mean different things on
different platforms. However, you can expect the message to show up in some convenient or
inconvenient place. (If you use a command-line interface, like that in Oracle’s Java Development
Kit, you type in a command to tell the computer to run the program. The computer will type
the output from the program, Hello World!, on the next line. In an integrated development
environment such as Eclipse, the output might appear somewhere in one of the environment’s
windows.)
You must be curious about all the other stuff in the above program. Part of it consists of
comments. Comments in a program are entirely ignored by the computer; they are there for
human readers only. This doesn’t mean that they are unimportant. Programs are meant to be
read by people as well as by computers, and without comments, a program can be very difficult
to understand. Java has two types of comments. The first type begins with // and extends to
the end of a line. There is a comment of this form on the last line of the above program. The
computer ignores the // and everything that follows it on the same line. The second type of
comment starts with /* and ends with */, and it can extend over more than one line. The first
three lines of the program are an example of this second type of comment. (A comment that
actually begins with /**, like this one does, has special meaning; it is a “Javadoc” comment
that can be used to produce documentation for the program.)
Everything else in the program is required by the rules of Java syntax. All programming in
Java is done inside “classes.” The first line in the above program (not counting the comment)
says that this is a class named HelloWorld. “HelloWorld,” the name of the class, also serves as
CHAPTER 2. NAMES AND THINGS 22

the name of the program. Not every class is a program. In order to define a program, a class
must include a subroutine named main, with a definition that takes the form:
public static void main(String[] args) {
hstatements i
}
When you tell the Java interpreter to run the program, the interpreter calls this main()
subroutine, and the statements that it contains are executed. These statements make up the
script that tells the computer exactly what to do when the program is executed. The main()
routine can call other subroutines that are defined in the same class or even in other classes,
but it is the main() routine that determines how and in what order the other subroutines are
used.
The word “public” in the first line of main() means that this routine can be called from out-
side the program. This is essential because the main() routine is called by the Java interpreter,
which is something external to the program itself. The remainder of the first line of the routine
is harder to explain at the moment; for now, just think of it as part of the required syntax.
The definition of the subroutine—that is, the instructions that say what it does—consists of
the sequence of “statements” enclosed between braces, { and }. Here, I’ve used hstatementsi as
a placeholder for the actual statements that make up the program. Throughout this textbook,
I will always use a similar format: anything that you see in hthis style of texti (italic in angle
brackets) is a placeholder that describes something you need to type when you write an actual
program.
As noted above, a subroutine can’t exist by itself. It has to be part of a “class”. A program
is defined by a public class that takes the form:
public class hprogram-name i {
hoptional-variable-declarations-and-subroutines i
public static void main(String[] args) {
hstatements i
}
hoptional-variable-declarations-and-subroutines i
}
The name on the first line is the name of the program, as well as the name of the class.
(Remember, again, that hprogram-namei is a placeholder for the actual name!)
If the name of the class is HelloWorld, then the class must be saved in a file called
HelloWorld.java. When this file is compiled, another file named HelloWorld.class will
be produced. This class file, HelloWorld.class, contains the translation of the program into
Java bytecode, which can be executed by a Java interpreter. HelloWorld.java is called the
source code for the program. To execute the program, you only need the compiled class file,
not the source code.
The layout of the program on the page, such as the use of blank lines and indentation, is not
part of the syntax or semantics of the language. The computer doesn’t care about layout—you
could run the entire program together on one line as far as it is concerned. However, layout is
important to human readers, and there are certain style guidelines for layout that are followed
by most programmers.
CHAPTER 2. NAMES AND THINGS 23

Also note that according to the above syntax specification, a program can contain other
subroutines besides main(), as well as things called “variable declarations.” You’ll learn more
about these later, but not until Chapter 4.

2.2 Variables and the Primitive Types


Names are fundamental to programming. In programs, names are used to refer to many
different sorts of things. In order to use those things, a programmer must understand the rules
for giving names to them and the rules for using the names to work with them. That is, the
programmer must understand the syntax and the semantics of names.
According to the syntax rules of Java, the most basic names are identifiers. Identifiers
can be used to name classes, variables, and subroutines. An identifier is a sequence of one or
more characters. It must begin with a letter or underscore and must consist entirely of letters,
digits, and underscores. (“Underscore” refers to the character ’ ’.) For example, here are some
legal identifiers:
N n rate x15 quite a long name HelloWorld
No spaces are allowed in identifiers; HelloWorld is a legal identifier, but “Hello World” is
not. Upper case and lower case letters are considered to be different, so that HelloWorld,
helloworld, HELLOWORLD, and hElloWorLD are all distinct names. Certain words are reserved
for special uses in Java, and cannot be used as identifiers. These reserved words include:
class, public, static, if, else, while, and several dozen other words. (Remember that
reserved words are not identifiers, since they can’t be used as names for things.)
Java is actually pretty liberal about what counts as a letter or a digit. Java uses the
Unicode character set, which includes thousands of characters from many different languages
and different alphabets, and many of these characters count as letters or digits. However, I will
be sticking to what can be typed on a regular English keyboard.
The pragmatics of naming includes style guidelines about how to choose names for things.
For example, it is customary for names of classes to begin with upper case letters, while names
of variables and of subroutines begin with lower case letters; you can avoid a lot of confusion by
following this standard convention in your own programs. Most Java programmers do not use
underscores in names, although some do use them at the beginning of the names of certain kinds
of variables. When a name is made up of several words, such as HelloWorld or interestRate,
it is customary to capitalize each word, except possibly the first; this is sometimes referred
to as camel case, since the upper case letters in the middle of a name are supposed to look
something like the humps on a camel’s back.
Finally, I’ll note that in addition to simple identifiers, things in Java can have compound
names which consist of several simple names separated by periods. (Compound names are also
called qualified names.) You’ve already seen an example: System.out.println. The idea
here is that things in Java can contain other things. A compound name is a kind of path to an
item through one or more levels of containment. The name System.out.println indicates that
something called “System” contains something called “out” which in turn contains something
called “println”.

2.2.1 Variables
Programs manipulate data that are stored in memory. In machine language, data can only be
referred to by giving the numerical address of the location in memory where the data is stored.
CHAPTER 2. NAMES AND THINGS 24

In a high-level language such as Java, names are used instead of numbers to refer to data. It
is the job of the computer to keep track of where in memory the data is actually stored; the
programmer only has to remember the name. A name used in this way—to refer to data stored
in memory—is called a variable.
Variables are actually rather subtle. Properly speaking, a variable is not a name for the
data itself but for a location in memory that can hold data. You should think of a variable as
a container or box where you can store data that you will need to use later. The variable refers
directly to the box and only indirectly to the data in the box. Since the data in the box can
change, a variable can refer to different data values at different times during the execution of
the program, but it always refers to the same box. Confusion can arise, especially for beginning
programmers, because when a variable is used in a program in certain ways, it refers to the
container, but when it is used in other ways, it refers to the data in the container. You’ll see
examples of both cases below.
(In this way, a variable is something like the title, “The President of the United States.”
This title can refer to different people at different times, but it always refers to the same office.
If I say “the President is playing basketball,” I mean that Barack Obama is playing basketball.
But if I say “Hillary Clinton wants to be President” I mean that she wants to fill the office, not
that she wants to be Barack Obama.)
In Java, the only way to get data into a variable—that is, into the box that the variable
names—is with an assignment statement. An assignment statement takes the form:
hvariable i = hexpression i;
where hexpressioni represents anything that refers to or computes a data value. When the
computer comes to an assignment statement in the course of executing a program, it evaluates
the expression and puts the resulting data value into the variable. For example, consider the
simple assignment statement
rate = 0.07;
The hvariablei in this assignment statement is rate, and the hexpressioni is the number 0.07.
The computer executes this assignment statement by putting the number 0.07 in the variable
rate, replacing whatever was there before. Now, consider the following more complicated
assignment statement, which might come later in the same program:
interest = rate * principal;
Here, the value of the expression “rate * principal” is being assigned to the variable
interest. In the expression, the * is a “multiplication operator” that tells the computer
to multiply rate times principal. The names rate and principal are themselves variables,
and it is really the values stored in those variables that are to be multiplied. We see that when
a variable is used in an expression, it is the value stored in the variable that matters; in this
case, the variable seems to refer to the data in the box, rather than to the box itself. When
the computer executes this assignment statement, it takes the value of rate, multiplies it by
the value of principal, and stores the answer in the box referred to by interest. When a
variable is used on the left-hand side of an assignment statement, it refers to the box that is
named by the variable.
(Note, by the way, that an assignment statement is a command that is executed by the
computer at a certain time. It is not a statement of fact. For example, suppose a program
includes the statement “rate = 0.07;”. If the statement “interest = rate * principal;”
is executed later in the program, can we say that the principal is multiplied by 0.07? No!
CHAPTER 2. NAMES AND THINGS 25

The value of rate might have been changed in the meantime by another statement. The
meaning of an assignment statement is completely different from the meaning of an equation
in mathematics, even though both use the symbol “=”.)

2.2.2 Types
A variable in Java is designed to hold only one particular type of data; it can legally hold that
type of data and no other. The compiler will consider it to be a syntax error if you try to
violate this rule by assigning a variable of the wrong type to a variable. We say that Java is a
strongly typed language because it enforces this rule.
There are eight so-called primitive types built into Java. The primitive types are named
byte, short, int, long, float, double, char, and boolean. The first four types hold integers
(whole numbers such as 17, -38477, and 0). The four integer types are distinguished by the
ranges of integers they can hold. The float and double types hold real numbers (such as 3.6 and
-145.99). Again, the two real types are distinguished by their range and accuracy. A variable
of type char holds a single character from the Unicode character set. And a variable of type
boolean holds one of the two logical values true or false.
Any data value stored in the computer’s memory must be represented as a binary number,
that is as a string of zeros and ones. A single zero or one is called a bit. A string of eight
bits is called a byte. Memory is usually measured in terms of bytes. Not surprisingly, the byte
data type refers to a single byte of memory. A variable of type byte holds a string of eight
bits, which can represent any of the integers between -128 and 127, inclusive. (There are 256
integers in that range; eight bits can represent 256—two raised to the power eight—different
values.) As for the other integer types,
• short corresponds to two bytes (16 bits). Variables of type short have values in the range
-32768 to 32767.
• int corresponds to four bytes (32 bits). Variables of type int have values in the range
-2147483648 to 2147483647.
• long corresponds to eight bytes (64 bits). Variables of type long have values in the range
-9223372036854775808 to 9223372036854775807.
You don’t have to remember these numbers, but they do give you some idea of the size of
integers that you can work with. Usually, for representing integer data you should just stick to
the int data type, which is good enough for most purposes.
The float data type is represented in four bytes of memory, using a standard method for
encoding real numbers. The maximum value for a float is about 10 raised to the power 38.
A float can have about 7 significant digits. (So that 32.3989231134 and 32.3989234399 would
both have to be rounded off to about 32.398923 in order to be stored in a variable of type
float.) A double takes up 8 bytes, can range up to about 10 to the power 308, and has about
15 significant digits. Ordinarily, you should stick to the double type for real values.
A variable of type char occupies two bytes in memory. The value of a char variable is a
single character such as A, *, x, or a space character. The value can also be a special character
such a tab or a carriage return or one of the many Unicode characters that come from different
languages. Values of type char are closely related to integer values, since a character is actually
stored as a 16-bit integer code number. In fact, we will see that chars in Java can actually be
used like integers in certain situations.
It is important to remember that a primitive type value is represented using ony a certain,
finite number of bits. So, an int can’t be an arbitrary integer; it can only be an integer
CHAPTER 2. NAMES AND THINGS 26

in a certain finite range of values. Similarly, float and double variables can only take on
certain values. They are not true real numbers in the mathematical sense. For example, the
mathematical constant π can only be approximated by a value of type float or double, since
it would require an infinite number of decimal places to represent it exactly. For that matter,
simple numbers like 1/3 can only be approximated by floats and doubles.

2.2.3 Literals
A data value is stored in the computer as a sequence of bits. In the computer’s memory, it
doesn’t look anything like a value written on this page. You need a way to include constant
values in the programs that you write. In a program, you represent constant values as literals.
A literal is something that you can type in a program to represent a value. It is a kind of name
for a constant value.
For example, to type a value of type char in a program, you must surround it with a pair
of single quote marks, such as ’A’, ’*’, or ’x’. The character and the quote marks make up a
literal of type char. Without the quotes, A would be an identifier and * would be a multiplication
operator. The quotes are not part of the value and are not stored in the variable; they are just
a convention for naming a particular character constant in a program. If you want to store the
character A in a variable ch of type char, you could do so with the assignment statement
ch = ’A’;
Certain special characters have special literals that use a backslash, \, as an “escape character”.
In particular, a tab is represented as ’\t’, a carriage return as ’\r’, a linefeed as ’\n’, the
single quote character as ’\’’, and the backslash itself as ’\\’. Note that even though you
type two characters between the quotes in ’\t’, the value represented by this literal is a single
tab character.
Numeric literals are a little more complicated than you might expect. Of course, there
are the obvious literals such as 317 and 17.42. But there are other possibilities for expressing
numbers in a Java program. First of all, real numbers can be represented in an exponential
form such as 1.3e12 or 12.3737e-108. The “e12” and “e-108” represent powers of 10, so that
1.3e12 means 1.3 times 1012 and 12.3737e-108 means 12.3737 times 10−108 . This format can be
used to express very large and very small numbers. Any numeric literal that contains a decimal
point or exponential is a literal of type double. To make a literal of type float, you have to
append an “F” or “f” to the end of the number. For example, “1.2F” stands for 1.2 considered
as a value of type float. (Occasionally, you need to know this because the rules of Java say that
you can’t assign a value of type double to a variable of type float, so you might be confronted
with a ridiculous-seeming error message if you try to do something like “x = 1.2;” if x is a
variable of type float. You have to say “x = 1.2F;". This is one reason why I advise sticking
to type double for real numbers.)
Even for integer literals, there are some complications. Ordinary integers such as 177777
and -32 are literals of type byte, short, or int, depending on their size. You can make a literal
of type long by adding “L” as a suffix. For example: 17L or 728476874368L. As another
complication, Java allows binary, octal (base-8), and hexadecimal (base-16) literals. I don’t
want to cover number bases in detail, but in case you run into them in other people’s programs,
it’s worth knowing a few things: Octal numbers use only the digits 0 through 7. In Java, a
numeric literal that begins with a 0 is interpreted as an octal number; for example, the octal
literal 045 represents the number 37, not the number 45. Octal numbers are rarely used, but
you need to be aware of what happens when you start a number with a zero. Hexadecimal
CHAPTER 2. NAMES AND THINGS 27

numbers use 16 digits, the usual digits 0 through 9 and the letters A, B, C, D, E, and F. Upper
case and lower case letters can be used interchangeably in this context. The letters represent
the numbers 10 through 15. In Java, a hexadecimal literal begins with 0x or 0X, as in 0x45
or 0xFF7A. Finally, binary literals start with 0b or 0B and contain only the digits 0 and 1; for
example: 0b10110.
As a final complication, numeric literals in Java 7 can include the underscore character (“ ”),
which can be used to separate groups of digits. For example, the integer constant for seven
billion could be written 7 000 000 000, which is a good deal easier to decipher than 7000000000.
There is no rule about how many digits have to be in each group. Underscores can be especially
useful in long binary numbers; for example, 0b1010 1100 1011.
I will note that hexadecimal numbers can also be used in character literals to represent
arbitrary Unicode characters. A Unicode literal consists of \u followed by four hexadecimal
digits. For example, the character literal ’\u00E9’ represents the Unicode character that is an
“e” with an acute accent.
For the type boolean, there are precisely two literals: true and false. These literals are
typed just as I’ve written them here, without quotes, but they represent values, not variables.
Boolean values occur most often as the values of conditional expressions. For example,
rate > 0.05
is a boolean-valued expression that evaluates to true if the value of the variable rate is greater
than 0.05, and to false if the value of rate is not greater than 0.05. As you’ll see in Chapter 3,
boolean-valued expressions are used extensively in control structures. Of course, boolean values
can also be assigned to variables of type boolean. For example, if test is a variable of type
boolean, then both of the following assignment statements are legal:
test = true;
test = rate > 0.05;

2.2.4 Strings and String Literals


Java has other types in addition to the primitive types, but all the other types represent objects
rather than “primitive” data values. For the most part, we are not concerned with objects for
the time being. However, there is one predefined object type that is very important: the type
String. (String is a type, but not a primitive type; it is in fact the name of a class, and we will
return to that aspect of strings in the next section.)
A value of type String is a sequence of characters. You’ve already seen a string literal:
"Hello World!". The double quotes are part of the literal; they have to be typed in the
program. However, they are not part of the actual String value, which consists of just the
characters between the quotes. A string can contain any number of characters, even zero. A
string with no characters is called the empty string and is represented by the literal "", a pair
of double quote marks with nothing between them. Remember the difference between single
quotes and double quotes! Single quotes are used for char literals and double quotes for String
literals! There is a big difference between the String "A" and the char ’A’.
Within a string literal, special characters can be represented using the backslash notation.
Within this context, the double quote is itself a special character. For example, to represent
the string value
I said, "Are you listening!"
with a linefeed at the end, you would have to type the string literal:
CHAPTER 2. NAMES AND THINGS 28

"I said, \"Are you listening!\"\n"


You can also use \t, \r, \\, and Unicode sequences such as \u00E9 to represent other
special characters in string literals.

2.2.5 Variables in Programs


A variable can be used in a program only if it has first been declared . A variable declaration
statement is used to declare one or more variables and to give them names. When the computer
executes a variable declaration, it sets aside memory for the variable and associates the variable’s
name with that memory. A simple variable declaration takes the form:
htype-name i hvariable-name-or-names i;
The hvariable-name-or-namesi can be a single variable name or a list of variable names
separated by commas. (We’ll see later that variable declaration statements can actually be
somewhat more complicated than this.) Good programming style is to declare only one variable
in a declaration statement, unless the variables are closely related in some way. For example:
int numberOfStudents;
String name;
double x, y;
boolean isFinished;
char firstInitial, middleInitial, lastInitial;
It is also good style to include a comment with each variable declaration to explain its
purpose in the program, or to give other information that might be useful to a human reader.
For example:
double principal; // Amount of money invested.
double interestRate; // Rate as a decimal, not percentage.
In this chapter, we will only use variables declared inside the main() subroutine of a pro-
gram. Variables declared inside a subroutine are called local variables for that subroutine.
They exist only inside the subroutine, while it is running, and are completely inaccessible from
outside. Variable declarations can occur anywhere inside the subroutine, as long as each vari-
able is declared before it is used in any way. Some people like to declare all the variables at
the beginning of the subroutine. Others like to wait to declare a variable until it is needed. My
preference: Declare important variables at the beginning of the subroutine, and use a comment
to explain the purpose of each variable. Declare “utility variables” which are not important to
the overall logic of the subroutine at the point in the subroutine where they are first used. Here
is a simple program using some variables and assignment statements:
/**
* This class implements a simple program that
* will compute the amount of interest that is
* earned on $17,000 invested at an interest
* rate of 0.027 for one year. The interest and
* the value of the investment after one year are
* printed to standard output.
*/
public class Interest {
public static void main(String[] args) {
CHAPTER 2. NAMES AND THINGS 29

/* Declare the variables. */


double principal; // The value of the investment.
double rate; // The annual interest rate.
double interest; // Interest earned in one year.
/* Do the computations. */
principal = 17000;
rate = 0.027;
interest = principal * rate; // Compute the interest.
principal = principal + interest;
// Compute value of investment after one year, with interest.
// (Note: The new value replaces the old value of principal.)
/* Output the results. */
System.out.print("The interest earned is $");
System.out.println(interest);
System.out.print("The value of the investment after one year is $");
System.out.println(principal);
} // end of main()
} // end of class Interest
This program uses several subroutine call statements to display information to the user of the
program. Two different subroutines are used: System.out.print and System.out.println.
The difference between these is that System.out.println adds a linefeed after the end of the
information that it displays, while System.out.print does not. Thus, the value of interest,
which is displayed by the subroutine call “System.out.println(interest);”, follows on the
same line as the string displayed by the previous System.out.print statement. Note that the
value to be displayed by System.out.print or System.out.println is provided in parentheses
after the subroutine name. This value is called a parameter to the subroutine. A parameter
provides a subroutine with information it needs to perform its task. In a subroutine call state-
ment, any parameters are listed in parentheses after the subroutine name. Not all subroutines
have parameters. If there are no parameters in a subroutine call statement, the subroutine
name must be followed by an empty pair of parentheses.
All the sample programs for this textbook are available in separate source code files in the
on-line version of this text at http://math.hws.edu/javanotes/source. They are also included
in the downloadable archives of the web site, in a folder named source. The source code for
the Interest program, for example, can be found in the file Interest.java in subfolder named
chapter2 inside the source folder.

2.3 Strings, Classes, Objects, and Subroutines


The previous section introduced the eight primitive data types and the type String. There
is a fundamental difference between the primitive types and String : Values of type String
are objects. While we will not study objects in detail until Chapter 5, it will be useful for
you to know a little about them and about a closely related topic: classes. This is not just
because strings are useful but because objects and classes are essential to understanding another
important programming concept, subroutines.
CHAPTER 2. NAMES AND THINGS 30

2.3.1 Built-in Subroutines and Functions


Recall that a subroutine is a set of program instructions that have been chunked together and
given a name. A subroutine is designed to perform some task. To get that task performed
in a program, you can “call” the subroutine using a subroutine call statement. In Chapter 4,
you’ll learn how to write your own subroutines, but you can get a lot done in a program just
by calling subroutines that have already been written for you. In Java, every subroutine is
contained either in a class or in an object. Some classes that are standard parts of the Java
language contain predefined subroutines that you can use. A value of type String, which is an
object, contains subroutines that can be used to manipulate that string. These subroutines
are “built into” the Java language. You can call all these subroutines without understanding
how they were written or how they work. Indeed, that’s the whole point of subroutines: A
subroutine is a “black box” which can be used without knowing what goes on inside.
Let’s first consider subroutines that are part of a class. One of the purposes of a class is
to group together some variables and subroutines, which are contained in that class. These
variables and subroutines are called static members of the class. You’ve seen one example:
In a class that defines a program, the main() routine is a static member of the class. The parts
of a class definition that define static members are marked with the reserved word “static”,
such as the word “static” in public static void main...
When a class contains a static variable or subroutine, the name of the class is part of the full
name of the variable or subroutine. For example, the standard class named System contains
a subroutine named exit. To use that subroutine in your program, you must refer to it as
System.exit. This full name consists of the name of the class that contains the subroutine,
followed by a period, followed by the name of the subroutine. This subroutine requires an
integer as parameter, so you would actually use it with a subroutine call statement such as
System.exit(0);
Calling System.exit will terminate the program and shut down the Java Virtual Machine. You
could use it if you had some reason to terminate the program before the end of the main routine.
(The parameter tells the computer why the program was terminated. A parameter value of 0
indicates that the program ended normally. Any other value indicates that the program was
terminated because an error was detected, so you could call System.exit(1) to indicate that
the program is ending because of an error. The parameter is sent back to the operating system;
in practice, the value is usually ignored by the operating system.)
System is just one of many standard classes that come with Java. Another useful class
is called Math. This class gives us an example of a class that contains static variables: It
includes the variables Math.PI and Math.E whose values are the mathematical constants π
and e. Math also contains a large number of mathematical “functions.” Every subroutine
performs some specific task. For some subroutines, that task is to compute or retrieve some
data value. Subroutines of this type are called functions. We say that a function returns a
value. Generally, the returned value is meant to be used somehow in the program that calls
the function.
You are familiar with the mathematical function that computes the square root of a number.
The corresponding function in Java is called Math.sqrt. This function is a static member
subroutine of the class named Math. If x is any numerical value, then Math.sqrt(x) computes
and returns the square root of that value. Since Math.sqrt(x) represents a value, it doesn’t
make sense to put it on a line by itself in a subroutine call statement such as
Math.sqrt(x); // This doesn’t make sense!
CHAPTER 2. NAMES AND THINGS 31

What, after all, would the computer do with the value computed by the function in this case?
You have to tell the computer to do something with the value. You might tell the computer to
display it:
System.out.print( Math.sqrt(x) ); // Display the square root of x.
or you might use an assignment statement to tell the computer to store that value in a variable:
lengthOfSide = Math.sqrt(x);
The function call Math.sqrt(x) represents a value of type double, and it can be used anyplace
where a numeric literal of type double could be used.
The Math class contains many static member functions. Here is a list of some of the more
important of them:
• Math.abs(x), which computes the absolute value of x.
• The usual trigonometric functions, Math.sin(x), Math.cos(x), and Math.tan(x). (For
all the trigonometric functions, angles are measured in radians, not degrees.)
• The inverse trigonometric functions arcsin, arccos, and arctan, which are written as:
Math.asin(x), Math.acos(x), and Math.atan(x). The return value is expressed in radi-
ans, not degrees.
• The exponential function Math.exp(x) for computing the number e raised to the power
x, and the natural logarithm function Math.log(x) for computing the logarithm of x in
the base e.
• Math.pow(x,y) for computing x raised to the power y.
• Math.floor(x), which rounds x down to the nearest integer value that is less than or
equal to x. Even though the return value is mathematically an integer, it is returned
as a value of type double, rather than of type int as you might expect. For example,
Math.floor(3.76) is 3.0. The function Math.round(x) returns the integer that is closest
to x, and Math.ceil(x) rounds x up to an integer. (“Ceil” is short for “ceiling”, the
opposite of “floor.”)
• Math.random(), which returns a randomly chosen double in the range 0.0 <=
Math.random() < 1.0. (The computer actually calculates so-called “pseudorandom”
numbers, which are not truly random but are effectively random enough for most pur-
poses.) We will find a lot of uses for Math.random in future examles.
For these functions, the type of the parameter—the x or y inside the parentheses—can be
any value of any numeric type. For most of the functions, the value returned by the function
is of type double no matter what the type of the parameter. However, for Math.abs(x), the
value returned will be the same type as x; if x is of type int, then so is Math.abs(x). So, for
example, while Math.sqrt(9) is the double value 3.0, Math.abs(9) is the int value 9.
Note that Math.random() does not have any parameter. You still need the parentheses,
even though there’s nothing between them. The parentheses let the computer know that this is
a subroutine rather than a variable. Another example of a subroutine that has no parameters
is the function System.currentTimeMillis(), from the System class. When this function is
executed, it retrieves the current time, expressed as the number of milliseconds that have passed
since a standardized base time (the start of the year 1970, if you care). One millisecond is one-
thousandth of a second. The return value of System.currentTimeMillis() is of type long (a
64-bit integer). This function can be used to measure the time that it takes the computer to
CHAPTER 2. NAMES AND THINGS 32

perform a task. Just record the time at which the task is begun and the time at which it is
finished and take the difference.
Here is a sample program that performs a few mathematical tasks and reports the time
that it takes for the program to run. On some computers, the time reported might be zero,
because it is too small to measure in milliseconds. Even if it’s not zero, you can be sure that
most of the time reported by the computer was spent doing output or working on tasks other
than the program, since the calculations performed in this program occupy only a tiny fraction
of a millisecond of a computer’s time.
/**
* This program performs some mathematical computations and displays the
* results. It also displays the value of the constant Math.PI. It then
* reports the number of seconds that the computer spent on this task.
*/
public class TimedComputation {
public static void main(String[] args) {
long startTime; // Starting time of program, in milliseconds.
long endTime; // Time when computations are done, in milliseconds.
double time; // Time difference, in seconds.
startTime = System.currentTimeMillis();
double width, height, hypotenuse; // sides of a triangle
width = 42.0;
height = 17.0;
hypotenuse = Math.sqrt( width*width + height*height );
System.out.print("A triangle with sides 42 and 17 has hypotenuse ");
System.out.println(hypotenuse);
System.out.println("\nMathematically, sin(x)*sin(x) + "
+ "cos(x)*cos(x) - 1 should be 0.");
System.out.println("Let’s check this for x = 1:");
System.out.print(" sin(1)*sin(1) + cos(1)*cos(1) - 1 is ");
System.out.println( Math.sin(1)*Math.sin(1)
+ Math.cos(1)*Math.cos(1) - 1 );
System.out.println("(There can be round-off errors when"
+ " computing with real numbers!)");
System.out.print("\nHere is a random number: ");
System.out.println( Math.random() );
System.out.print("The value of Math.PI is ");
System.out.println( Math.PI );
endTime = System.currentTimeMillis();
time = (endTime - startTime) / 1000.0;
System.out.print("\nRun time in seconds was: ");
System.out.println(time);
} // end main()
} // end class TimedComputation
CHAPTER 2. NAMES AND THINGS 33

2.3.2 Classes and Objects


Classes can be containers for static variables and subroutines. However classes also have another
purpose. They are used to describe objects. In this role, the class is a type, in the same way
that int and double are types. That is, the class name can be used to declare variables. Such
variables can only hold one type of value. The values in this case are objects. An object is
a collection of variables and subroutines. Every object has an associated class that tells what
“type” of object it is. The class of an object specifies what subroutines and variables that
object contains. All objects defined by the same class are similar in that they contain similar
collections of variables and subroutines. For example, an object might represent a point in the
plane, and it might contain variables named x and y to represent the coordinates of that point.
Every point object would have an x and a y, but different points would have different values for
these variables. A class, named Point, for example, could exist to define the common structure
of all point objects, and all such objects would then be values of type Point.
As another example, let’s look again at System.out.println. System is a class, and out
is a static variable within that class. However, the value of System.out is an object, and
System.out.println is actually the full name of a subroutine that is contained in the ob-
ject System.out. You don’t need to understand it at this point, but the object referred to
by System.out is an object of the class PrintStream. PrintStream is another class that is a
standard part of Java. Any object of type PrintStream is a destination to which information
can be printed; any object of type PrintStream has a println subroutine that can be used
to send information to that destination. The object System.out is just one possible desti-
nation, and System.out.println is a subroutine that sends information to that particular
destination. Other objects of type PrintStream might send information to other destinations
such as files or across a network to other computers. This is object-oriented programming:
Many different things which have something in common—they can all be used as destina-
tions for information—can all be used in the same way—through a println subroutine. The
PrintStream class expresses the commonalities among all these objects.
The dual role of classes can be confusing, and in practice most classes are designed to
perform primarily or exclusively in only one of the two possible roles. Fortunately, you will not
need to worry too much about it until we start working with objects in a more serious way, in
Chapter 5.
By the way, since class names and variable names are used in similar ways, it might be hard
to tell which is which. Remember that all the built-in, predefined names in Java follow the rule
that class names begin with an upper case letter while variable names begin with a lower case
letter. While this is not a formal syntax rule, I strongly recommend that you follow it in your
own programming. Subroutine names should also begin with lower case letters. There is no
possibility of confusing a variable with a subroutine, since a subroutine name in a program is
always followed by a left parenthesis.
As one final general note, you should be aware that subroutines in Java are often referred
to as methods. Generally, the term “method” means a subroutine that is contained in a class
or in an object. Since this is true of every subroutine in Java, every subroutine in Java is a
method. The same is not true for other programming languages, and for the time being, I will
prefer to use the more general term, “subroutine.” However, I should note that some people
prefer to use the term “method” from the beginning.
CHAPTER 2. NAMES AND THINGS 34

2.3.3 Operations on Strings


String is a class, and a value of type String is an object. That object contains data, namely
the sequence of characters that make up the string. It also contains subroutines. All of these
subroutines are in fact functions. For example, every string object contains a function named
length that computes the number of characters in that string. Suppose that advice is a
variable that refers to a String. For example, advice might have been declared and assigned a
value as follows:
String advice;
advice = "Seize the day!";
Then advice.length() is a function call that returns the number of characters in the string
“Seize the day!”. In this case, the return value would be 14. In general, for any variable str
of type String, the value of str.length() is an int equal to the number of characters in the
string. Note that this function has no parameter; the particular string whose length is being
computed is the value of str. The length subroutine is defined by the class String, and it
can be used with any value of type String. It can even be used with String literals, which are,
after all, just constant values of type String. For example, you could have a program count the
characters in “Hello World” for you by saying
System.out.print("The number of characters in ");
System.out.print("the string \"Hello World\" is ");
System.out.println( "Hello World".length() );
The String class defines a lot of functions. Here are some that you might find useful. Assume
that s1 and s2 are variables of type String :
• s1.equals(s2) is a function that returns a boolean value. It returns true if s1 consists
of exactly the same sequence of characters as s2, and returns false otherwise.
• s1.equalsIgnoreCase(s2) is another boolean-valued function that checks whether s1
is the same string as s2, but this function considers upper and lower case letters
to be equivalent. Thus, if s1 is “cat”, then s1.equals("Cat") is false, while
s1.equalsIgnoreCase("Cat") is true.
• s1.length(), as mentioned above, is an integer-valued function that gives the number of
characters in s1.
• s1.charAt(N), where N is an integer, returns a value of type char. It returns the Nth
character in the string. Positions are numbered starting with 0, so s1.charAt(0) is
actually the first character, s1.charAt(1) is the second, and so on. The final position is
s1.length() - 1. For example, the value of "cat".charAt(1) is ’a’. An error occurs if
the value of the parameter is less than zero or is greater than or equal to s1.length().
• s1.substring(N,M), where N and M are integers, returns a value of type String. The
returned value consists of the characters of s1 in positions N, N+1,. . . , M-1. Note that the
character in position M is not included. The returned value is called a substring of s1. The
subroutine s1.substring(N) returns the substring of s1 consisting of characters starting
at position N up until the end of the string.
• s1.indexOf(s2) returns an integer. If s2 occurs as a substring of s1, then the returned
value is the starting position of that substring. Otherwise, the returned value is -1. You
can also use s1.indexOf(ch) to search for a char, ch, in s1. To find the first occurrence
of x at or after position N, you can use s1.indexOf(x,N). To find the last occurance of x
in s1, use s1.lastIndexOf(x).
CHAPTER 2. NAMES AND THINGS 35

• s1.compareTo(s2) is an integer-valued function that compares the two strings. If the


strings are equal, the value returned is zero. If s1 is less than s2, the value returned
is a number less than zero, and if s1 is greater than s2, the value returned is some
number greater than zero. (If both of the strings consist entirely of lower case letters, or
if they consist entirely of upper case letters, then “less than” and “greater than” refer to
alphabetical order. Otherwise, the ordering is more complicated.)
• s1.toUpperCase() is a String -valued function that returns a new string that is equal to s1,
except that any lower case letters in s1 have been converted to upper case. For example,
"Cat".toUpperCase() is the string "CAT". There is also a function s1.toLowerCase().
• s1.trim() is a String -valued function that returns a new string that is equal to s1 except
that any non-printing characters such as spaces and tabs have been trimmed from the
beginning and from the end of the string. Thus, if s1 has the value "fred ", then
s1.trim() is the string "fred", with the spaces at the end removed.
For the functions s1.toUpperCase(), s1.toLowerCase(), and s1.trim(), note that the
value of s1 is not changed. Instead a new string is created and returned as the value of
the function. The returned value could be used, for example, in an assignment statement
such as “smallLetters = s1.toLowerCase();”. To change the value of s1, you could use an
assignment “s1 = s1.toLowerCase();”.
∗ ∗ ∗
Here is another extremely useful fact about strings: You can use the plus operator, +, to
concatenate two strings. The concatenation of two strings is a new string consisting of all the
characters of the first string followed by all the characters of the second string. For example,
"Hello" + "World" evaluates to "HelloWorld". (Gotta watch those spaces, of course—if you
want a space in the concatenated string, it has to be somewhere in the input data, as in
"Hello " + "World".)
Let’s suppose that name is a variable of type String and that it already refers to the name
of the person using the program. Then, the program could greet the user by executing the
statement:
System.out.println("Hello, " + name + ". Pleased to meet you!");
Even more surprising is that you can actually concatenate values of any type onto a String
using the + operator. The value is converted to a string, just as it would be if you printed it to
the standard output, and then that string is concatenated with the other string. For example,
the expression "Number" + 42 evaluates to the string "Number42". And the statements
System.out.print("After ");
System.out.print(years);
System.out.print(" years, the value is ");
System.out.print(principal);
can be replaced by the single statement:
System.out.print("After " + years +
" years, the value is " + principal);
Obviously, this is very convenient. It would have shortened some of the examples presented
earlier in this chapter.
Other documents randomly have
different content
"What do I think of him Robert?"—with a sigh—"poor Mary."
"Why, poor Mary, do you not like his appearance?"
"I should not much like to trust my happiness, or that of any one I
loved, to his keeping."
"Indeed! he is very good-looking at any rate."
"Yes, handsome certainly—eyes, such as you perhaps have seldom,
if ever seen, and which, if they would only look you full in the face,
are certainly calculated to do a great deal of execution. But he did
not look so into mine; and there was something about his
countenance altogether which I cannot explain—something which,
though I can fancy it well calculated to make an impression—of
some sort or another, over one's mind—I confess on mine—to have
been one, which is far from canny. His looks too bespeak him, I am
afraid, to be suffering rather from the jading effects of London
dissipation, than the gentler pains and anxieties attendant on his
situation, as a lover separated from the object of his affection."
Mr. Gillespie looked concerned at this report, feeling a great interest
in his amiable young sister-in-law. And though he generally
expressed mistrust, with respect to his wife's too hasty reliance on
her first impressions, still he was often in the end forced to
acknowledge their frequent accuracy.
Yet at the same time, as the countenance of the lover did not in any
way alter the case with regard to Mary's position or circumstances,
there was nothing to be said or done by her friends whilst awaiting
the issue of affairs, but to observe with regret that though with the
same meek "patience, abnegation of self, and devotion to others,"
their sister pursued the even tenor of her way, the cheerful serenity
which before had continued to shine forth in her countenance, and
characterize her bearing, had departed. Her mind had been evidently
unsettled by the rencontre with Eugene Trevor—her heart's calm rest
disturbed.
How was it indeed with Mary? Had the hints conveyed by Eugene
during their interview depressed her hopes, and re-awakened her
misgivings as to the happy issue of the year's probation? Or more
bitter still—had anything in that same interview occurred to give that
first disenchanting touch, which by degrees detracts from the perfect
charm which has hitherto robed our idol, and we see the image of
goodness and beauty, whose idol shape we worshipped, melting
from our sight, and though still it binds the fatal spell, and still it
draws us on, the spirit of our love is changed—a shadow has fallen
upon it. We feel it to be "of the earth earthy."
Had Mary received any startling impression, her feelings any
boulversement, by beholding Eugene Trevor for the first time so
unlike the Eugene she had hitherto loved—under the irritating
disturbing influences of opposition and reverse.
But from whatever cause they might proceed, certainly "the gloom
and the shadow" spread broader and deeper on her brow; and when
on his return from the Moors, Eugene Trevor, probably for the
chance of another interview, revisited the Scotch metropolis, he
learnt, by particular inquiry of a maid-servant he found standing by
the door of Mr. Gillespie's closed house, that the family had left
Edinburgh, and gone to the sea-side.
"Were they all well?" he inquired.
"All well, only the young lady, Mrs. Gillespie's sister, a little pale, and
pining for country air. So the young Maister Arthur had come, and
persuaded them to put up their gear, and take the bairns and all to
the sea; but the maister was expected home the morrow, if the
gentleman liked to step up and see him."
We may imagine that Trevor had no inclination to tarry for this
purpose, and that same day left Scotland en route for Montrevor.
CHAPTER III.
He glowed with a spirit pure and high,
They called the feeling madness,
And he wept for woe with a melting eye,
'Twas weak and moody sadness.

PERCIVAL.

It was Epsom week. London was all astir with the influx of company
returning from the races.
A pale girl sat alone in one of the apartments of an hotel in Brook
Street, listening long and anxiously to the coming sounds of the
carriage-wheels, as they whirled along in that direction.
At length a carriage stopped before the door, and in a few moments
a lady entered the room, whose showy costume and flushed excited
countenance, (forming so strong a contrast to the appearance of the
other, whom she warmly greeted,) plainly evinced her to have but
just returned from that gay resort, the Stand at Epsom.
"You are come then, dear Mary. I hope you have not been very long
waiting."
"No, not so very long," and the eyes of the speaker wandered
anxiously towards the door, as if she seemed to expect the
appearance of a second person.
Mrs. de Burgh understood that glance too well—she shook her head
compassionately.
"Alas!—no, dear Mary; you must not expect to see him just now; he
has been unfortunately prevented—that was the reason which made
me so late; but I will tell you all about it presently, only let me have
a glass of wine first, for I am nearly exhausted."
And during the interval of suspense, whilst Mrs. de Burgh refreshed
herself after the fatiguing pleasures of the day, let us remind our
readers, that the momentous year had some little time ago drawn to
a close. Its expiration had not, however, brought with it, any
immediate results.
Nothing had been seen or heard of Eugene Trevor by any of the
family for the first month or two. He had been in London only at
intervals, and he had not opened any communication with his
fiancée, till she—on coming to London at the urgent solicitation of
her sister Lady Morgan, who was not well—had a few days after her
arrival, been surprised by a note from Mrs. de Burgh, whom she was
not aware was even in town, begging her to come to her—naming a
particular day—at the hotel where she was staying—as Eugene
Trevor wished particularly to see her. She added that he would be
obliged by her not mentioning the object of this visit to her relations,
lest by any chance they might interfere with the interview, and it
was very necessary that it should occur, before any more general
communication took place.
"Still mystery and concealment!" was poor Mary's disappointed
soliloquy. "Why not come here openly and see and speak to me? But
I will go this once, as Eugene wishes it, and I cannot refuse perhaps
without occasioning trouble and confusion."
And so she went; for still alas! the attractive chain too powerfully
bound her, and her heart could not but spring forward with yearning
hope to this meeting once again, with her intended. It may be
imagined, therefore, how her heart had sunk within her, at Mrs. de
Burgh's disappointing communication.
"Prevented coming," after having had her hopes and expectations
strained to such a pitch—and she awaited with painful solicitude the
promised explanation.
She had not seen her cousin since her last unhappy time in London,
and though, even then, to a certain degree, a kind of estrangement
had risen up between them; and all that she had since heard by
report of the gay wife's conduct and proceedings, had not greatly
raised the beautiful Olivia in her esteem, yet Mary could not but
retain a grateful remembrance of the warm-hearted kindness she
had received whilst under her roof—and a still more pleasing and
vivid impression of the too tenderly cherished associations, with
which she was so intimately connected.
But at this moment, the dearest friend on earth would have only
been appreciated by Mary, as the being on whose lips she hung for
information on the subject, and which she alone at this moment had
the power to communicate; and "why had not Eugene come?" was
all that spoke in her anxious countenance, or in the faltering tone in
which she attempted, with some show of cousinly interest, to make
a few inquiries after Louis and the children.
Mrs. de Burgh came at last to her relief—if relief it could be called—
for the first thing she heard was, that Eugene instead of coming to
see her, intended setting off for Montrevor that very evening.
"And why?" Mary with quivering lips interrupted.
"Having lost a large sum of money on the Derby, he was obliged to
have immediate recourse to his father for the necessary cash to
cover this unfortunate transaction. He has therefore commissioned
me to break to you this intelligence. I cannot tell you, my dear Mary,
the state of mind poor Eugene was in when we parted—not only on
account of the immediate disappointment this occasioned him; but
because this enormous loss must again retard the possibility of his
marriage taking place at present. My dear Mary, you are doomed to
the trial of hope deferred—the strength and constancy of your
attachment has indeed been sorely taxed."
Mary did not immediately reply. She sat very pale, her eyes fixed
upon the ground, something more than common disappointment
expressed in her thoughtful countenance.
At length she looked up, and said in a grave and anxious tone:
"Does Eugene always lose like this at races?"
"Oh no, dear! fortunately," laughed Mrs. de Burgh, "not often; he is
very lucky in general," but checking herself, as she saw Mary's
shocked countenance, "I mean," and she hesitated, "that after all he
has not so very decided a taste for this sort of thing," and Mrs. de
Burgh laughed again, saying: "but, my dear girl, do not look so very
serious upon the subject, what is there so very shocking in it after
all."
Mary thought it was a subject, to her at least, of most serious
importance and concern. A new and uncomfortable misgiving began
to arise in her mind.
Was it in any way relating to this propensity in Eugene Trevor,
against which Louis de Burgh originally warned her—and did it in
reality—more than the reason which Eugene had brought forth to
her brother, tend to interfere in any way with her happiness? So
strongly did this idea suddenly possess her, that she could not
refrain from asking Mrs. de Burgh whether she thought this was the
case. Her cousin's evasive answer did not tend much to the removal
of her suspicions.
Eugene certainly did play—did bet a little on the turf. She thought
Mary had always been aware of that—men must have some pursuit,
some excitement. If it were not one thing it was another—equally—
perhaps one might call it—"not quite right;" however, all the best
men in London were on the turf. Eugene was only like the rest, but
with married men, it was quite different.
"Indeed, Mary," the fair lady continued, "Eugene always assures me,
he means to give up everything of the sort when he marries, and I
am quite sure he will do so. I only wish you were married, dear."
Mary only sighed.
"You are not getting weary of your engagement, Mary?" Mrs. de
Burgh inquired.
"Weary!—oh, no, Olivia. I was sighing for Eugene's sake."
"You may well do so, for he is, I assure you, very unhappy at all this
delay."
Mary shook her head, and her lip curled a little disdainfully. The
gesture seemed to say, "Whose fault is it now?"
Mrs. de Burgh seemed to understand it as such, for she said—
"It is all that miserly old father's fault. He could set everything right
at once, if he chose."
"But," said Mary, in a low tone, "I see no end of all this."
"No," hesitated Mrs. de Burgh, "not I suppose till the brother turns
up; unless, indeed—" she murmured.
"What?" inquired Mary, anxiously.
"You had better come and stay with me at Silverton," was Mrs. de
Burgh's indirect reply.
Mary smiled dejectedly.
"That would never do," she replied, "they would not consent to my
doing so, under present circumstances."
"They—who are they? I am sure, Mary, I should not allow any
brother or sister to interfere with my proceedings. You are of age,
and quite at liberty, I should imagine, to act as you please on any
subject."
Mary shook her head. She did not feel quite so independent-spirited
as all that—and besides, she did not herself see that such a step
would be quite expedient at present.
She did not, however, say this aloud, and Mrs. de Burgh attributed
her silence to yielding consent.
"Eugene wishes it very much I can assure you."
Mary looked up as if the tempter himself had murmured the
insinuating observation in her ear, for there was something
significant in the way Mrs. de Burgh had spoken, which she could
not but understand, and still more in the words which followed.
"If you were only married to Eugene, Mary, you might rely on his
giving up all objectionable and hurtful things."
"But as that cannot be," sighed Mary, despondingly.
"It could," hesitated Mrs. de Burgh; "it is only your friends'
opposition which would stand in the way, until Eugene is able to
settle something satisfactory as to his future prospects. Were I you,
Mary, if it were only for Eugene's sake, I should not be so scrupulous
about securing each other's happiness and his welfare, as he tells
me you are."
But Mary turned away almost indignantly. If the proposal had even
revolted her spirit when coming from Eugene's own lips, much more
so, did it grate upon her feelings, when thus insinuated by those of
another.
But whatever might here have ensued, was interrupted by the
entrance of Mr. de Burgh. It seemed that he had only arrived in
London that day, unexpectedly to Mrs. de Burgh, who otherwise
would not have planned the meeting of Mary and Eugene.
He came evidently in one of his London humours, as his wife called
it; and though he greeted Mary kindly, she fancied there was a
certain alteration in his manner towards her, which she instinctively
felt to originate in his disapprovement of the present circumstances
of her engagement; she remembered that he never was friendly to
the affair, though the direct subject was now avoided by each of the
party.
He sat and made captious and cutting allusions to the races, and
every one concerned therein, which, whether really intended at
Eugene, Mary interpreted as such—and they touched the poor girl to
the quick.
Probably she was not far wrong in her supposition as to the
pointedness of his remarks, for suddenly glancing on his listener's
downcast anxious countenance he exclaimed, addressing his wife:
"Bye the bye, Olivia, I mean to be off abroad in a day or two."
"Good Heavens, Louis! what new fancy is this?"
"Why, I have heard something to-day which has really put me quite
into a fever."
"Well, what is it? Some nonsense, I dare say."
"I at least do not think it so. Dawson, who I saw to-day, declares
that Trevor, Eustace Trevor I mean, was seen by some one not long
ago in Switzerland. Yes," he continued, encouraged by Mary's glance
of intense and startled interest, "he was seen with another person—
the keeper I suppose they talk about—somewhere on the Alps."
"The Alps!—poor fellow! gone there to cool his brain, I suppose,"
said Mrs. de Burgh, whose countenance nevertheless had bespoke
her not a little moved by this communication.
"Cool his brain!—nonsense! cool enough by this time, depend upon
it."
"But does Eugene know of this?" faltered Mary.
"I suppose so," replied Mr. de Burgh, coldly.
"Impossible, Louis!" Mary exclaimed with eagerness.
"Well, perhaps so. I don't know at all," Mr. de Burgh continued. "I
shouldn't be so much surprised if he did; there are a great many
things which surprise me more than that, Mary; for instance you
yourself—yes, you, Mary," as she lifted up her eyes to her cousin's
handsome face, with quiet surprise, "that you should see things in a
light so different to what I should have expected from you."
"Ridiculous!" interposed Mrs. de Burgh—"that is to say that you
should have expected her to have seen everything with your own
jaundiced, prejudiced perception; but about Eustace Trevor."
"Yes, about Eustace Trevor; he is a subject certainly worth a little of
your interest and inquiry. Mary, you should have known him,"
exclaimed Mr. de Burgh, with rising enthusiasm.
"You were very much attached to him then?" demanded Mary, with
deep interest.
"Attached to him!—yes, indeed I was; that was a man whom one
might well glory in calling friend; or," he murmured to himself, "a
woman might be proud to worship as a lover."
"Yes," interposed Mrs. de Burgh, "I suppose he was a very superior,
delightful person; but I own he always appeared to me, even as a
boy, a little tête monté, so that it did not surprise me so very much
when I heard of the calamity which had befallen him. He was just
the sort of person upon whose mind any strong excitement, or
sudden shock would have had the like effect."
"Olivia, you are talking nonsense," Mr. de Burgh petulantly
exclaimed.
"It was his mother's death, I think, I heard which brought on this
dreadful crisis?" Mary inquired.
"Exactly so," answered Mrs. de Burgh.
"How do you know?" exclaimed her husband. "What does any one
know about the matter?"
"We can only judge from what one has heard from the best
authority," again persisted his wife.
"Best authority! well, I can only say that far from being of your
opinion, I should have said that Eustace Trevor had been as far from
madness as earth from heaven."
"Really, Louis!" exclaimed Mrs. de Burgh, perceiving Mary's look of
anxious interest and surprise, "one would fancy from the way you
talk that you suspected him never really to have been mad."

"'And this the world called frenzy; but the wise


Have a far deeper madness, and the glance
Of melancholy is a fearful gift.
What is it but the telescope of truth,
Which brings life near in utter nakedness,
Making the cold reality more cold,'"

quoted Mr. de Burgh for all reply.


"What is all this to do with the point in question?" said Mrs. de Burgh
impatiently. "Really, Louis, Mary will think you also decidedly have
gone mad."
"Mary likes poetry," he answered quietly; "she will not think it is
madness what I have uttered."
"But, Louis, what do you really mean about Eugene's brother?—tell
me something about him. I have heard so very little," demanded
Mary, earnestly.
"Why do you not make Eugene tell you himself? I can only say:

'He was a man, take him for all in all,


I shall not look upon his like again!'"
"He was very handsome—very clever," said Mrs. de Burgh, taking up
the theme more prosaically, "and very amiable I believe, though
rather impetuous and hot-tempered; always at daggers drawn with
his father, because he spent the old man's money a little faster than
he liked, it is said."
"Good heavens, Olivia!" burst forth Mr. de Burgh, passionately, "how
can you sit there, and distort the truth in that shameful manner? you
know as well as I do the true version of this part of the story. Mary,"
turning to his cousin with flashing eyes, "Eustace Trevor had a
mother; an excellent charming creature, whose existence, through
the combined influence of her husband and a most baneful,
pernicious wretch of a woman, that Marryott, of whom no doubt you
have heard, was rendered one long tissue of wretchedness and
wrong, the extent of which I believe is hardly known. Eustace, who
adored his mother, keenly felt and manfully espoused her cause;
therefore, you may see at once this was the reason of his father's
hatred of him, and the old man's treatment of this son, was one
shameful system of injustice and tyranny—enough, I confess, to
drive any man into a state of mental irritation, possessed of
Eustace's sensitive temperament."
Mary's wandering, startled gaze turned inquiringly on Mrs. de Burgh,
as if to ask whether this new and melancholy representation of the
case could be really true. Mrs. de Burgh looked a little disconcerted,
but replied carelessly:
"Yes, poor Aunt Trevor! she had certainly a sad time of it; but then it
was partly her own fault. She was a weak-spirited creature. What
other woman would have endured what she did in that tame and
passive manner?"
"Yes, these poor weak-spirited creatures have often, however,
strength to bear a great deal for the sake of others," replied Mr. de
Burgh, sarcastically. "It would have been more high and noble-
spirited, I dare say, to have blazed abroad her domestic grievances;
but she had no doubt a little consideration for her children, and the
honour and respectability of their house and name."
"Oh, nonsense! that was all very well when they were children to
consider them; but when they were men, it signified very little," said
Mrs. de Burgh.
"But then," suggested Mary, with trembling earnestness, "then she
must have had great comfort in their affection and support."
"Yes," answered Mr. de Burgh, "in Eustace she had, I know, unfailing
comfort and support."
"And Eugene?" anxiously demanded Mary. "Surely he too—"
"Of course," Mrs. de Burgh hastened to exclaim, "no one could be
fonder or kinder to his mother though, because"—looking angrily at
her husband—"he had the sense and the discretion not to quarrel
with his father, and strength of mind not to go mad—Louis, I
suppose, wishes to make you believe that Eugene was not kind to
his mother."
"Nothing would make me believe that Eugene was not kind to his
mother," added Mary with an earnest energy, which showed with
what indignation she would repel this distracting idea.
And Mr. de Burgh replied with great moderation:
"Nor did I say anything of the sort. I am not at all in the custom of
asserting grave charges against a person, without certain proof. I
only saw as much into 'the secrets of the prison-house' at Montrevor
as would make me very sorry to have had anything further to do
with its interior."
Poor Mary! She asked no more questions, she had heard quite
enough to give new and dark impressions to her mind. She saw
everything in a still more bewildering and uncertain light—yet felt a
vague, indefinite dread of further revelation.
Her sister's carriage being speedily announced, she bade adieu to
her cousins, who were leaving London the next day, and

"Went like one that hath been stunned,


And is of sense forlorn,"

bearing in her secret soul restless doubts and blind misgivings, she
shrank even from confiding to her most beloved Arthur.
CHAPTER IV.
I knew that in thy bosom dwelt
A silent grief, a hidden fear,
A sting which could be only felt
By spirits to their God most dear,
Which yet thou felt'st from year to year,
Unsoftened, nay, embitter'd still;
And many a secret sigh and tear
Heaved thy sad heart, thine eyes did fill,
And anxious thoughts thou hadst
presaging direst ill.

MOULTRIE.

The sequel only brought forth for our heroine further disturbance
and discomfort.
The newly-risen impediment to the marriage was of necessity the
subject of correspondence. He again threw the blame upon his
father, urging his increasing infirmities of mind and body as the
excuse.
But the plea appeared to Mary's friends evasive and ambiguous, and
greatly indeed was the strength and stability of her affection tried by
the urgent solicitations of those so dear to her, that she would
consent to break off entirely this ill-starred—and as they the more
and more considered it—objectionable engagement.
But no, there was yet one still more dear to her; and to him, through
good and evil report, her spirit yet must cling—
"And stand as stands a lonely tree,
That still unbroke, though gently bent,
Still waves with fond fidelity
Its boughs above a monument."

By letter too—for there was one crisis of affairs during which the
lovers corresponded on the anxious subject, Eugene failed not to
urge the maintenance of an engagement which on his part he
declared he would never consent to be the first to relinquish.
Then, how could Mary cast aside an attachment, a hope which had
become so linked with the happiness of her existence, that to
contemplate its extinction, was to see before her extended

"Dreary and vast and silent the desert of life."

No, rather was she content in doubt, darkness and uncertainty to


wait and wander, her hope still fixed upon the distant light in the
hazy future.
A position, such as that in which Mary found herself placed—an ill-
defined and ambiguous matrimonial engagement—is to a young
woman ever, more or less, a misfortune and a trial: something there
is in her life

"Incomplete, imperfect, and unfinished,"

comprising also as it must do, much of uncertainty and restless


doubt.
The circumstances of Mary's case, rendered hers more peculiarly a
subject for such influences. Removed from the sphere in which her
lover moved, even their correspondence, after the time just
mentioned, entirely ceased; and she heard of him only at intervals—
by chance and vague report.
She had longed to have those doubts and repellant ideas, Mr. de
Burgh's conversation had insinuated into her mind, cleared away, as
she believed they might, by Eugene's own word of mouth. But this
had been denied her. She had indeed alluded to the report
respecting his brother, which Mr. de Burgh had heard; but Eugene
had merely said in reply, that he was taking every measure to
ascertain its accuracy; and she heard nothing further on that point.
From Mrs. de Burgh she also ascertained that her cousin Louis had
never carried out his proposed expedition, in search of the friend for
whom he had professed such warm admiration and interest.
Mary was not so much surprised at this, it being only accordant with
her cousin's ineffectual character—warm and affectionate in heart
and feeling, but unstable in action and resolve; without self-
devotedness or energy in any duty or pursuit, which turned not on
the immediate fancy or interest of the moment—something else had
probably put the intention out of his head. It did seem to Mary
strange and unnatural, that the disappearance of a man such as
Eustace Trevor had been represented to her lively and susceptible
fancy, should have been so tamely endured by his friends in general,
to say nothing of his own brother; but to think on that point was
now to raise such a dark and bewildering cloud of ill-defined
misgivings, that Mary put it from her mind as much as possible.
There was another point too, on which she indirectly sought
enlightenment and assurance. Eugene's mother. Alas! there indeed
she had heard enough to make her shudder at the idea connected
with much within that house, which she had visited with such
pleasure in her unconscious innocence—but more especially with
that sinful old man, who, in the garb of venerable old age, had been
by her so ignorantly revered; yes, she shuddered to think how
appearances may deceive, and shrunk at the thoughts of ever
entering again the scene of such wickedness, as long at least as
Eugene's father continued there to exist.
That Eugene had in the remotest degree even countenanced that
wickedness, was another point she would not allow herself to
question—or rather, she put it away, like every other deteriorating
rumour, hearsay, or inarticulate whisper, which in the course of time
come with its airy hand to point out her lover as unworthy of the
devotedness of a heart and affections such as hers; put it away in
the utmost recesses of her heart, as we do those things we fear to
see or hear substantiated—when even a breath, a word would
suffice to destroy the illusion now become so closely interwoven with
the happiness of one's existence.
In the meantime, Mary lived chiefly with the Gillespies though her
heart's true home was with that dear brother, upon whose progress
and success in his profession the chief interest of her life,
independent of her one great hope, was centred; and who, on his
part, unselfishly devoted every interval between the course of study
he so energetically pursued, to her society, endeavouring in every
way to promote her happiness or amusement; and chafing inwardly
as he did, over the position in which she stood; for her sake
preserved outward patience and equanimity, on a point which
nevertheless touched him to the quick. Much he heard, too, which
made him devoutly wish the engagement with Eugene Trevor to be
broken off, without his having courage to take the bandage from his
sister's eyes. Much of the private history of these, Eugene Trevor's
days—we call them—of probation—nay, the profligate course his
love for Mary could not even restrain within bounds. Episodes in his
daily walk, with which it is not our intention to sully our pages, but
calculated to make the brother's blood boil with indignation at the
idea of his pure, spotless sister, becoming the wife of such a man.
But how difficult the task to force on her unsuspecting mind
convictions which might go nigh to break her trembling innocent
heart—or at least blight the happiness of her life. He must patiently
allow fate to work out its course, fervently praying that all might end
well.
About a year and a half went by—another six months and Arthur
Seaham's term of law study would have terminated; and he declared
that to prepare himself for his last important term, it was necessary
that he should have some more than ordinary relaxation of mind. He
had a fancy to go to Italy, and that Mary should accompany him.
She smiled at first incredulously, thinking he was in jest. She thought
the idea too delightful to be realised.
He was in earnest, he declared.
But the journey would be so long; and the expense—could they
manage it?
What were such considerations to the affectionate brother, when he
remarked the glow which had mantled his sister's pale cheeks, or
the animation which lit up her languid eye, as in imagination the
warm breezes of Italy already fanned her brow—her feet trode
lightly on its classic grounds. Their friends had a few prudent
objections to the plan—Italy was so far; Germany—the Rhine, were
suggested. But no; Arthur saw that Mary's countenance fell when
the mark fell short of Italy, therefore he stood firm.
And thither then the brother and sister went, with an old attached
maid-servant of the family, who still followed the fortunes of the
unmarried daughter; and by the Rhine and Switzerland they
proceeded into Italy.
CHAPTER V.
We came to Italy. I felt
A yearning for its sunny sky;
My very spirit seem'd to melt
As swept its first warm breezes by.

WILLIS.

An early morning in Italy! Who that from experience has not enjoyed
—can realise the conception, much less describe, the luxurious
delight of the first hours of a summer morning in that radiant
climate.
"It was the morn of such a day, as must have risen on Eden first,"
that Mary Seaham went forth from the little inn near Tivoli, to join
her brother who had preceded her some little time to make
arrangements respecting their intended excursion of the day.
She waited—but when he did not come, could no longer resist the
tempting aspect of the scenery without, to stroll onwards from the
house towards the merry waters which danced on their musical way
not far distant from the spot; and as she proceeded through the
fragrant air—beneath the transparent sky, the sigh she heaved could
have been caused but by the burden of enjoyment now weighing
upon her senses; for all human care—all sadness, all unrest, all
passionate yearnings or pensive remembrances—in short, all
unconnected with "the mere and breathing charm of life," seemed in
that thrilling hour, annihilated and forgotten.
But something glittering on the ground, near a flower she had
stooped to pick, suddenly attracted her attention. She took it up and
examined it more closely. It was a massive signet ring. What was
Mary's astonishment to see engraved upon the seal, the initials "E.
T." with the Trevor coat of arms.
Her first thought was of Eugene—could it be that he by some
strange coincidence was near? or that he had purposely followed her
to Italy? and her heart beat fast, and her cheek glowed at the
suggestion. Yet she had never remembered observing such a ring on
Eugene's finger, and then—another indefinite recollection of having
somewhere before seen that same impression on some letter,
certainly not from her lover, occurred to her.
Yes—and suddenly the breakfast-table at Silverton, and that letter—
the letter to Eugene which she had ever since suspected must have
been the turning-point of her previous perfect felicity, but which she
had always supposed must have been from Eugene's father. That
large red seal the little Louisa had displayed before her eyes. All was
now before her. But how then came it lying here upon this foreign
soil?
Was it forbidden her to lose, even for a moment, the thrilling
consciousness of the fate which bound her, that there should be now
thrown across her very path, this startling reminder?
Standing fixed to the spot—turning the signet over and over in her
hand, an uncertain, half-bewildered expression on her sweet face—a
sudden idea which crimsoned it to the very temples, then leaving it
paler than before—suddenly lit up her countenance.
How, indeed, came it lying there? "E. T." Surely from the old man's
finger it had not dropped; and if not from Eugene's, might it, could it
have been from that of the lost, unhappy, wandering brother,
Eustace's?
With what object, what intent, she scarcely knew herself—but
impulse moved her, with beating heart and trembling step, to pursue
the path which she had taken, only remembering the while, that last
night, after she was in bed, there had been an arrival at the inn. Two
gentlemen from Rome, the cameriera who called her in the morning
told her, had roused the house up at a very late hour; and that one
of these belated travellers had nevertheless already pressed the
dewy turf before her—that it might be him who was the loser, was
perhaps, the paramount idea which now possessed her as she
hurried on over this fair Italian ground as light in limb—alas! less
light at heart as when bounding over the breezy wilds of her native
land.
She had not been wrong in her conjecture. A sudden turn in the
lovely vale she had entered presented to her view, at no great
distance from the spot she had attained, a broken fountain, the
silvery sound of whose ringing waters faintly reached her ear; and
near this, half concealed by the branches of a leaning tree, she
discerned the figure of a man, standing watching its light and
sparkling play.
A few half irresolute steps brought her nearer and nearer still—a few
more, and she stood attracted as if by an irresistible spell almost
close behind the object of her search. His face had been turned
away, but the light rustling of her garments when she drew so near,
attracted his attention.
He looked round, and there stood Mary with parted lips and
crimsoned brow—that look of strange, deep, and eager scrutiny
directed towards him.
Never did the face of mortal man undergo such immediate change,
as did the calm, noble countenance which at the same time revealed
itself to the intruder; never were two simple words uttered with such
thrilling fervency of tone, as was the ejaculation which broke from
the stranger's lips.
"Miss Seaham," he exclaimed; and in accents scarce less earnest in
its emotion, Mary's trembling lips faltered Mr. Temple's name.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like