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

Guide to Java: A Concise Introduction to Programming (2nd Edition) James T. Streib instant download

The document is a guide to the second edition of 'Guide to Java: A Concise Introduction to Programming' by James T. Streib and Takako Soma, aimed at helping readers learn Java programming quickly through a focus on fundamentals, examples, and illustrations. It includes features such as early introductions to object-oriented programming, contour diagrams, and interactive questions to enhance learning. The second edition updates and reorganizes content, introduces new topics, and provides additional exercises for practice.

Uploaded by

mydmijeky755
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)
4 views

Guide to Java: A Concise Introduction to Programming (2nd Edition) James T. Streib instant download

The document is a guide to the second edition of 'Guide to Java: A Concise Introduction to Programming' by James T. Streib and Takako Soma, aimed at helping readers learn Java programming quickly through a focus on fundamentals, examples, and illustrations. It includes features such as early introductions to object-oriented programming, contour diagrams, and interactive questions to enhance learning. The second edition updates and reorganizes content, introduces new topics, and provides additional exercises for practice.

Uploaded by

mydmijeky755
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

Guide to Java: A Concise Introduction to

Programming (2nd Edition) James T. Streib


install download

https://ebookmeta.com/product/guide-to-java-a-concise-
introduction-to-programming-2nd-edition-james-t-streib/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Concise Guide To Databases: A Practical Introduction


Konstantinos Domdouzis

https://ebookmeta.com/product/concise-guide-to-databases-a-
practical-introduction-konstantinos-domdouzis/

A Concise Introduction to Robot Programming with ROS2


1st Edition Francisco Martín Rico

https://ebookmeta.com/product/a-concise-introduction-to-robot-
programming-with-ros2-1st-edition-francisco-martin-rico/

Introduction to Programming with Java: A Problem


Solving Approach 3rd Edition John Dean

https://ebookmeta.com/product/introduction-to-programming-with-
java-a-problem-solving-approach-3rd-edition-john-dean/

The Eagle Has Eyes The FBI Surveillance of César


Estrada Chávez of the United Farm Workers Union of
America 1965 1975 1st Edition José Angel Gutiérrez

https://ebookmeta.com/product/the-eagle-has-eyes-the-fbi-
surveillance-of-cesar-estrada-chavez-of-the-united-farm-workers-
union-of-america-1965-1975-1st-edition-jose-angel-gutierrez/
War in the Mountains: Peasant Society and
Counterinsurgency in Algeria, 1918-1958 1st Edition
Neil Macmaster

https://ebookmeta.com/product/war-in-the-mountains-peasant-
society-and-counterinsurgency-in-algeria-1918-1958-1st-edition-
neil-macmaster/

Stunt Doubled Roommates 3 1st Edition Stephanie Brother

https://ebookmeta.com/product/stunt-doubled-roommates-3-1st-
edition-stephanie-brother/

Software Telemetry 1st Edition Jamie Riedesel

https://ebookmeta.com/product/software-telemetry-1st-edition-
jamie-riedesel/

Fakemas A Holiday Instalove Romance Briar Vale 1st


Edition Gia Bailey

https://ebookmeta.com/product/fakemas-a-holiday-instalove-
romance-briar-vale-1st-edition-gia-bailey/

Handbook Factory Planning And Design 1st Edition Hans-


Peter Wiendahl

https://ebookmeta.com/product/handbook-factory-planning-and-
design-1st-edition-hans-peter-wiendahl/
Wavelet Analysis: Basic Concepts and Applications 1st
Edition Sabrine Arfaoui

https://ebookmeta.com/product/wavelet-analysis-basic-concepts-
and-applications-1st-edition-sabrine-arfaoui/
Undergraduate Topics in Computer Science

James T. Streib · Takako Soma

Guide to Java
A Concise Introduction
to Programming
Second Edition
Undergraduate Topics in Computer Science

Series Editor
Ian Mackie, University of Sussex, Brighton, UK

Advisory Editors
Samson Abramsky , Department of Computer Science, University of Oxford,
Oxford, UK
Chris Hankin , Department of Computing, Imperial College London, London, UK
Mike Hinchey , Lero – The Irish Software Research Centre, University of
Limerick, Limerick, Ireland
Dexter C. Kozen, Department of Computer Science, Cornell University, Ithaca,
NY, USA
Andrew Pitts , Department of Computer Science and Technology, University of
Cambridge, Cambridge, UK
Hanne Riis Nielson , Department of Applied Mathematics and Computer Science,
Technical University of Denmark, Kongens Lyngby, Denmark
Steven S. Skiena, Department of Computer Science, Stony Brook University, Stony
Brook, NY, USA
Iain Stewart , Department of Computer Science, Durham University, Durham,
UK
Joseph Migga Kizza, College of Engineering and Computer Science,
The University of Tennessee-Chattanooga, Chattanooga, TN, USA
‘Undergraduate Topics in Computer Science’ (UTiCS) delivers high-quality
instructional content for undergraduates studying in all areas of computing and
information science. From core foundational and theoretical material to final-year
topics and applications, UTiCS books take a fresh, concise, and modern approach
and are ideal for self-study or for a one- or two-semester course. The texts are all
authored by established experts in their fields, reviewed by an international advisory
board, and contain numerous examples and problems, many of which include fully
worked solutions.
The UTiCS concept relies on high-quality, concise books in softback format, and
generally a maximum of 275–300 pages. For undergraduate textbooks that are
likely to be longer, more expository, Springer continues to offer the highly regarded
Texts in Computer Science series, to which we refer potential authors.
James T. Streib Takako Soma

Guide to Java
A Concise Introduction to Programming

Second Edition

123
James T. Streib Takako Soma
Program in Computer Science Program in Computer Science
Illinois College Illinois College
Jacksonville, IL, USA Jacksonville, IL, USA

ISSN 1863-7310 ISSN 2197-1781 (electronic)


Undergraduate Topics in Computer Science
ISBN 978-3-031-22841-4 ISBN 978-3-031-22842-1 (eBook)
https://doi.org/10.1007/978-3-031-22842-1

1st edition: © Springer-Verlag London 2014


2nd edition: © The Editor(s) (if applicable) and The Author(s), under exclusive license to Springer
Nature Switzerland AG 2023
This work is subject to copyright. All rights are solely and exclusively licensed by the Publisher, whether
the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and
transmission or information storage and retrieval, electronic adaptation, computer software, or by similar
or dissimilar methodology now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this
publication does not imply, even in the absence of a specific statement, that such names are exempt from
the relevant protective laws and regulations and therefore free for general use.
The publisher, the authors, and the editors are safe to assume that the advice and information in this
book are believed to be true and accurate at the date of publication. Neither the publisher nor the
authors or the editors give a warranty, expressed or implied, with respect to the material contained
herein or for any errors or omissions that may have been made. The publisher remains neutral with regard
to jurisdictional claims in published maps and institutional affiliations.

This Springer imprint is published by the registered company Springer Nature Switzerland AG
The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland
Preface

James T. Streiba,1 and Takako Somaa,2


a
Computer Science Program, Illinois College, Jacksonville, IL, USA
1
Email: james.streib@jtstreib.com.
2
Email: tsoma@ic.edu.

Purpose
The purpose of this text is to help the reader learn very quickly how to program using the
Java programming language. This is accomplished by concentrating on the fundamentals,
providing plenty of illustrations and examples, and using visual contour diagrams to
illustrate the object-oriented semantics of the language.

Comparison to Other Texts


There are a number of texts on the Java programming language. Some of these texts provide
plenty of examples and are very comprehensive, but unfortunately, they sometimes seem
to cover too many details, which might make it difficult for a beginning programmer to
discern which points are the most relevant. There are also other texts that attempt to provide
a shortened introduction to the language, but it seems that these texts might not provide the
necessary examples and illustrations and might be better suited for readers who have
previous programming experience.

Need
This text attempts to fill the gap between the above two types of books. First, it provides
plenty of examples and concentrates primarily on the fundamentals of the Java
programming language so that the reader can stay focused on the key concepts. Second, by
concentrating on the fundamentals, it allows the text to be more concise and yet still
accessible to readers who have no prior programming experience. The result is that the
reader can learn the Java programming language very quickly and also have a good
foundation to learn more complex topics later.

Features of This Text


This text provides many examples and illustrations. It further has an early introduction to
object-oriented programming and uses contour diagrams to illustrate various object-
oriented concepts. The contour model was originally developed by John B. Johnson [4].
The model was elaborated on by Organick, Forsythe, and Plummer to illustrate
subprograms, parameter passing, and recursion in procedural and functional languages [7].
The model seems quite adaptable to newer programming methodologies such as object-
oriented programming as illustrated in a paper by the authors of this text [8]. As discussed
in that paper, it was shown that the use of contour diagrams can be an effective tool in

v
vi Preface

helping one learn object-oriented concepts in the Java programming language. By


acquiring a good working model of objects, there is less chance of possible misconceptions.
In many places in the text, questions are asked of the reader to help them interact with
the material and think about the subject matter just presented. Hopefully the reader will
take a few moments to try to answer these questions on their own before proceeding to the
answer that follows. To help further reinforce concepts, each chapter has one or more
complete programs to illustrate many of the concepts presented and also to help readers
learn how to write programs on their own. In addition, for review and practice, there are
summaries and exercises provided at the end of each chapter. Further, in the appendices at
the end of the text, there are answers to selected exercises and a glossary of important
terms. A summary of the features of this text are listed below:
‡ Stresses the fundamentals.
‡ Provides many examples and illustrations.
‡ Has an early introduction to objects.
‡ Uses contour diagrams to illustrate object-oriented concepts.
‡ Asks readers questions to help them interact with the material.
‡ Has one or more complete programs in every chapter.
‡ Provides chapter summaries.
‡ Includes exercises at the end of each chapter, with selected answers in an appendix.
‡ Has a glossary of important terms.

Features New to the Second Edition

The second edition retains all the features of the first edition. In addition to fixing any
known errors, any areas that could be clarified have been reworded. Features new to the
second edition, include the following:

‡ Chapter 1 has been reorganized into Chapters 0 and 1. Whereas an experienced


programmer can go straight to Chapter 1, it is recommended a new programmer or an
experienced programmer who wants a review start with the computer concepts in
Chapter 0.
‡ Chapter 0 contains new topics such as computational thinking and computer ethics.
‡ Where previously some topics in Chapter 1 were scattered in different sections, they
have been consolidated into single sections to help the reader focus on each topic
individually.
‡ Simple graphical user interface (GUI) is introduced in Chapter 1 and used in different
sections throughout the text.
‡ Chapter 11 has been added to include an introduction to bit-wise logic for computer
science students taking computer organization in the future or for pre-engineering
students to gain exposure to some of the logic capabilities in the C-like languages.
‡ Chapter 12 introduces parallel processing programming for computer science students
who will be taking a course in operating systems in the future.
‡ Appendix A contains a detailed description of the Java skeleton introduced in Chapter
1 along with additional information on standard output and GUI.
‡ Additional exercises have been added to various chapters.
Preface vii

Overview of the Chapters


This text first introduces the reader to various computer concepts such as hardware,
software, computational thinking, software design, and computer ethics. It then allows the
reader to understand a simple program with the appropriate input, processing, and output,
followed by an early introduction to objects. It then looks at selection and iteration
structures followed by more object-oriented concepts. Next, strings and arrays are
examined. This is followed by recursion, inheritance and polymorphism, and elementary
files. Then there is an introduction to bit-wise logic and parallel processing. The appendices
include information on the Java skeleton, standard output, graphical input/output,
exception processing, Javadoc, a glossary, and answers to selected exercises. Lastly, there
are references, useful websites and an index. The following provides a brief synopsis of
the chapters and appendices:
.
‡ Chapter 0 begins with the computer concepts of hardware/software, computational
thinking, design, and computer ethics.
‡ Chapter 1 provides an introduction to variables, input/output, and arithmetic
operations.
‡ Chapter 2 introduces objects and contour diagrams.
‡ Chapter 3 explains selection structures.
‡ Chapter 4 shows how iteration structures work.
‡ Chapter 5 revisits object-oriented concepts.
‡ Chapter 6 introduces string variables and processing.
‡ Chapter 7 illustrates arrays and array processing.
‡ Chapter 8 examines recursion.
‡ Chapter 9 explores inheritance and polymorphism.
‡ Chapter 10 discusses elementary files.
‡ Chapter 11 describes how bit-wise logic works
‡ Chapter 12 introduces parallel processing programming.
‡ Appendix A elaborates on the Java skeleton, standard output, and graphical
input/output.
‡ Appendix B discusses elementary exception processing.
‡ Appendix C presents the basics of Javadoc.
‡ Appendix D lists a glossary of key terms.
‡ Appendix E provides answers to selected exercises.

Ordering of the Chapters

Typically, there are three ways objects can be introduced to the beginning programmer:

‡ Objects first.
‡ Objects last.
‡ Objects interleaved.

This text takes the latter approach where objects are discussed in Chapters 2, 5, and 9.
However, recognizing that some readers and instructors might want to use one of the first
two approaches, this text can be read using alternative orders. For example, should an
viii Preface

objects first approach want to be taken, after reading Chapter 1, Chapters 2 and 5 can be
read next, followed by Chapters 3 and 4. Should an object later approach want to be used,
Chapters 3 and 4 can be read prior to Chapters 2 and 5.

To help facilitate these alternative approaches, starting with Chapter 3, the Complete
Program sections at the end of each chapter have examples with and without using objects.
Note that Chapter 9 requires an understanding of arrays, which is covered in Chapter 7,
and it can be read after completing that chapter.

Scope
As mentioned previously, this text concentrates on the fundamentals of the Java
programming language such as input/output, object-oriented programming, arithmetic and
logic instructions, control structures, strings, arrays including elementary sorting and
searching, recursion, files, bit-wise logic, and parallel processing programming. As a result,
it might not cover all the details that are found in some other texts, and if necessary, these
topics can be supplemented by the instructor or reader, or covered in a subsequent text
and/or second semester course.

Audience
This text is intended primarily for readers who have not had any previous programming
experience; however, this does not preclude its use by others who have programmed
previously. It can serve as a text in an introductory programming course, as an introduction
to a second language in a practicum course, as a supplement in a course on the concepts of
programming languages, or as a self-study guide in either academe or industry. Although
no prior programming is assumed, it is recommended that readers have the equivalent of
an introduction to functions course that includes trigonometry which will help with
problem solving and understanding the examples presented in the text.

Acknowledgments
In addition to the reviewers of the first edition, the authors would like to thank Mark E.
Bollman of Albion College and James W. Chaffee of the University of Iowa for their
continued work on this edition. Also, the authors would like to acknowledge the students
of Illinois College who have read and used various sections of the first edition in the
classroom. On a personal note, James Streib would like to thank his wife Kimberly A.
Streib and son Daniel M. Streib. Takako Soma would like to thank her family and friends,
near and far.
Note that Java is a registered trademark of Oracle and/or its affiliates and that Windows
is a registered trademark of Microsoft Corporation in the United States and/or other
countries.

Feedback
The possibility of errors exist in any text, therefore any corrections, comments, or
suggestions are welcome and can be sent to the authors via the e-mail addresses below. In
addition to copies of the complete programs presented in the text, any significant
corrections can be found at the website below.
Preface ix

Website: http://www.jtstreib.com/GuideJavaProgramming.html

Illinois College James T. Streib


Jacksonville, IL, USA james.streib@jtstreib.com
October 1, 2022 Takako Soma
tsoma@ic.edu
Contents

0 Introduction to Computing Concepts 1


0.1 Introduction 1
0.2 Overview of Hardware and Software 1
0.2.1 Hardware 1
0.2.2 Software 2
0.2.3 History and Java 3
0.2.4 High-level Translation 3
0.3 Introduction ro Computational Thinking 5
0.4 Essentials of Software Design 7
0.4.1 Syntax, Semantics, and Errors 7
0.4.2 Design Methodology 8
0.4.2.1 Analysis 9
0.4.2.2 Design 9
0.4.2.3 Implementation 9
0.4.2.4 Maintenance 10
0.4.3 Tools and Techniques 10
0.4.3.1 Pseudocode 10
0.4.3.2 OOP and UML 11
0.4.3.3 Debugging 11
0.5 A Brief Look at Computer Ethics 12
0.6 Summary 13
0.7 Exercises (Items Marked with an * Have Solutions in Appendix E) 14

1 Variables, Input/Output, and Arithmetic 17


1.1 Introduction 17
1.2 Java Skeleton 16
1.3 ³+HOOR:RUOG´ 17
1.3.1 Text-based Output 17
1.3.2 GUI-based Output 18
1.4 Variables and Constants 19
1.5 Assignment Statements 23
1.6 Output 26
1.6.1 Text-based 26
1.6.2 GUI-based 30
1.7 Input 31
1.7.1 Text-based 31
1.7.2 GUI-based 34
1.8 Arithmetic Statements 36
1.8.1 Binary Operators 36
1.8.2 Precedence 38
1.8.3 Unary Operators 39
1.8.4 Incrementing 40

xi
xii Contents

1.8.5 Summing 41
1.8.6 Arithmetic Functions 42
1.9 Comments 43
1.10 Complete Program: Implementing a Simple Program 44
1.11 Summary 46
1.12 Exercises (Items Marked with an * Have Solutions in Appendix E) 47

2 Objects: An Introduction 51
2.1 Introduction 51
2.2 Classes and Objects 51
2.3 Public and Private Data Members 52
2.4 Value-Returning Methods 52
2.5 void Methods and Parameters 53
2.6 Creating Objects and Invoking Methods 54
2.7 Contour Diagrams 56
2.8 Constructors 62
2.9 Multiple Objects and Classes 66
2.10 Unified Modeling Language (UML) Class Diagrams 73
2.11 Complete Program: Implementing a Simple Class and
Client Program 75
2.12 Summary 77
2.13 Exercises (Items Marked with an * Have Solutions in
Appendix E) 78

3 Selection Structures 83
3.1 Introduction 83
3.2 If-Then Structure 83
3.3 If-Then-Else Structure 88
3.4 Nested If Structures 91
3.4.1 If-Then-Else-If Structure 91
3.4.2 If-Then-If Structure 94
3.4.3 Dangling Else Problem 96
3.5 Logical Operators 99
3.6 Case Structure 105
3.7 Complete Programs: Implementing Selection Structures 111
3.7.1 Simple Program 111
3.7.2 Program with Objects 114
3.8 Summary 116
3.9 Exercises (Items Marked with an * Have Solutions in Appendix E) 116

4 Iteration Structures 121


4.1 Introduction 121
4.2 Pretest Indefinite Loop Structure 121
4.2.1 Count-Controlled Indefinite Iteration Structure 122
4.2.2 Sentinel Controlled Loop 128
4.3 Posttest Indefinite Loop Structure 134
4.4 Definite Iteration Loop Structure 137
Contents xiii

4.5 Nested Iteration Structures 140


4.6 Potential Problems 141
4.7 Complete Programs: Implementing Iteration Structures 142
4.7.1 Simple Program 143
4.7.2 Program with Objects 145
4.8 Summary 150
4.9 Exercises (Items Marked with an * Have Solutions in Appendix E) 150

5 Objects: Revisited 155


5.1 Sending an Object to a Method 155
5.2 Returning an Object from a Method 158
5.3 Overloaded Constructors and Methods 161
5.3.1 Overloaded Constructors 161
5.3.2 Default Constructors 163
5.3.3 Overloaded Methods 164
5.4 Use of the Reserved Word this 165
5.5 Class Constants, Variables, and Methods 169
5.5.1 Local, Instance, and Class Constants 169
5.5.2 Local, Instance, and Class Variables 176
5.5.3 Class Methods 178
5.6 Complete Programs: Implementing Objects 180
5.6.1 Program Focusing on Overloaded Methods 180
5.6.2 Program Focusing on Class Data Members and Class
Methods 189
5.7 Summary 193
5.8 Exercises (Items Marked with an * Have Solutions in Appendix E) 193

6 Strings 203
6.1 Introduction 203
6.2 String Class 203
6.3 String Concatenation 204
6.4 Methods in String Class 206
6.4.1 The length Method 206
6.4.2 The indexOf Method 206
6.4.3 The substring Method 207
6.4.4 Comparison of Two String Objects 209
6.4.5 The equalsIgnoreCase Method 211
6.4.6 The charAt Method 212
6.5 The toString Method 213
6.6 Complete Program: Implementing String Objects 215
6.7 Summary 219
6.8 Exercises (Items Marked with an * Have Solutions in Appendix E) 219

7 Arrays 223
7.1 Introduction 223
7.2 Array Declaration 223
xiv Contents

7.3 Array Access 224


7.4 Input, Output, Simple Processing, and Methods 226
7.4.1 Input 226
7.4.2 Output 230
7.4.3 Simple Processing 230
7.4.4 Passing an Array to and from a Method 231
7.5 Reversing an Array 232
7.6 Searching an Array 237
7.6.1 Sequential Search 237
7.6.2 Binary Search 238
7.6.3 Elementary Analysis 240
7.7 Sorting an Array 241
7.7.1 Simplified Bubble Sort 241
7.7.2 Modified Bubble Sort 244
7.8 Two-Dimensional Arrays 245
7.8.1 Declaration, Creation, and Initialization 245
7.8.2 Input and Output 247
7.8.3 Processing Data 248
7.8.4 Passing a Two-Dimensional Array to and from a Method 251
7.8.5 Asymmetrical Two-Dimensional Arrays 253
7.9 Arrays of Objects 255
7.10 Complete Program: Implementing an Array 258
7.11 Summary 261
7.12 Exercises (Items Marked with an * Have Solutions in Appendix E) 262

8 Recursion 265
8.1 Introduction 265
8.2 The Power Function 265
8.3 Stack Frames 274
8.4 Fibonacci Numbers 277
8.5 Complete Program: Implementing Recursion 289
8.6 Summary 291
8.7 Exercises (Items Marked with an * Have Solutions in Appendix E) 291

9 Objects: Inheritance and Polymorphism 293


9.1 Inheritance 293
9.2 Protected Variables and Methods 303
9.3 Abstract Classes 304
9.4 Polymorphism 306
9.5 Complete Program: Implementing Inheritance and Polymorphism 310
9.6 Summary 315
9.7 Exercises (Items Marked with an * Have Solutions in Appendix E) 316

10 Elementary File Input and Output 321


10.1 Introduction 321
10.2 File Input 321
10.3 File Output 326
Contents xv

10.4 File Input and Output Using an Array 328


10.5 Specifying the File Location 332
10.6 Complete Programs: Implementing File Input and Output 334
10.6.1 Matrix Multiplication 334
10.6.2 Sorting Data in a File 336
10.7 Summary 338
10.8 Exercises (Items Marked with an * Have Solutions in Appendix E) 338

11 Bit Manipulation 341


11.1 Introduction 341
11.2 Simple Conversions 341
11.3 Declaration and Assignments 343
11.4 Bit-wise Logic Operations 344
11.5 Testing, Clearing, Setting, and Toggling 346
11.6 Shifting 348
11.7 Precedence 350
11.8 Complete Program: Implementing Bit-wise Operators 351
11.9 Summary 355
11.10 Exercises (Items Marked with an * Have Solutions in Appendix E) 355

12 Introduction to Parallel Processing Programming 356


12.1 Multiprossor Systems 359
12.2 Programming Multicore and SharedMemory Multiprocessor
Using Pyjama 360
12.2.1 Using Pyjama to Write Multithreaded Programs 360
12.2.2 ³Hello World´ 361
12.2.3 Sorting Building Blocks 363
12.3 Analysis 368
12.4 Complete Program: Implementing Paralle Inner Product 370
12.5 Summary 372
12.6 Exercises (Items Marked with an * Have Solutions in Appendix E) 372

Appendix A Explanation and Elaboration of Concepts in Chapter 1 375


A.1 6NHOWRQ3URJUDPDQG³+HOOR:RUOG³ 375
A.2 Text-base Output: print and println 376
A.3 Text-based Input 378
A.4 Overview of Java Packages 379
A.5 More on GUI-based Output and Input 380
A.6 Confirmation Dialog Boxes 383
A.7 Option Dialog Boxes 384

Appendix B Exceptions 387


B.1 Exception Class and Error Class 387
B.2 Handling an Exception 388
B.3 Throwing Exceptions and Multiple catch Blocks 391
B.4 Checked and Unchecked Exceptions 396
xvi Contents

Appendix C Javadoc Comments 


C.1 Javadoc 
C.2 More Javadoc Tags 
C.3 Generating Javadoc Documentation from a Command Line 

Appendix D Glossary 

Appendix E Answers to Selected Exercises 

References and Useful Websites 

Index 
0
Introduction to Computing Concepts
James T. Streiba* and Takako Somaa
a
Computer Science Program, Illinois College, Jacksonville, IL, USA

Abstract
In addition to an introduction to hardware and software concepts, including the concept of compiling,
interpreting, and executing a program, there is an introduction to computational thinking, software design,
and computer ethics.

Keywords
Hardware, Software, Computational Thinking, Software Design, Computer Ethics.

0.1 Introduction

Although this chapter is labeled as Chapter 0, that does not diminish its importance. The
reason for such a numbering is to allow readers with a previous introduction to computing
concepts and programming to proceed onto Chapter 1. However, for readers with no prior
introduction or for those who would like a refresher, this chapter provides an important
overview of hardware, software, computational thinking, software design, and computer
ethics.

0.2 Overview of Hardware and Software

0.2.1 Hardware
As many readers may already know from using application software such as a word
processor, a computer system is composed of two major parts: hardware and software.
Since this book is primarily about writing software, this section on hardware is
understandably brief. The hardware is the physical computer that includes five basic
components: the central processing unit (CPU), the random-access memory (RAM) or just
memory for short, input (typically a keyboard), output (typically a monitor), and storage
(often a disk) as shown in Fig. 0.1.

© The Author(s), under exclusive license to Springer Nature Switzerland AG 2023 1


J. T. Streib and T. Soma, Guide to Java, Undergraduate Topics in Computer Science,
https://doi.org/10.1007/978-3-031-22842-1_0
2 0 Introduction to Computing Concepts

CPU

Input Output
RAM

Storage

Fig. 0.1 Computer hardware

0.2.2 Software

In order for computer hardware to perform, it is necessary that it has software.


Essentially, software (often called a program) is the set of instructions that tells the
computer what to do and when to do it. A program is typically loaded from storage into the
FRPSXWHU¶V 5$0 IRU VXEVHTXHQW H[HFXWLRQ LQ WKH FRPSXWHU¶V &38 $V WKH SURJUDP
executes or runs, it will typically ask the user to input data which will also be stored in
RAM. The program will then process the data, and various results will be output to the
monitor. This Input, Process, Output sequence is sometimes abbreviated as IPO.
The only type of instruction a computer can actually understand is low-level machine
language, where different types of CPUs can have different machine languages. Machine
language is made up of ones and zeros, which makes programming in machine language
very tedious and error-prone. An alternative to using machine language is assembly
language which is also a low-level language that uses mnemonics (or abbreviations) and is
easier to use than ones and zeros [10].
However, if the only language that the computer can directly understand is machine
language, how does the computer understand assembly language? The answer is that the
assembly language is translated into machine language by another program called an
assembler (see Fig. 0.2). Note that there is a one-to-one correspondence between assembly
language and machine language, and for every assembly language instruction, there is
typically only one machine language instruction. However, even though assembly
language is easier to program in than machine language, different types of CPUs can also
have different types of assembly languages, so the assembly language of one machine can
be different from that of another machine and needs a seperate assembler.
0.2 Overview of Hardware and Software 3

Compiler Assembler

High-Level Assembly Machine


Language Language Language

Fig. 0.2 Assemblers and compilers

0.2.3 History and Java

The solution to making programming easier and allow programs to be used on different
machines is through the use of high-level languages which are more English-like and math-
like. One of the first high-level programming languages was FORTRAN (FORmula
TRANslation), which was developed in the early 1950s to help solve mathematical
problems. There have been a number of high-level languages developed since that time to
meet the needs of many different users. Some of these include COBOL (COmmon
Business Oriented Language) developed in the 1950s for the business world, BASIC
(Beginners All-purpose Symbolic Instruction Code) developed in the 1960s for beginning
programmers, Pascal in the 1970s previously used for teaching computer science students,
C in the 1970s for systems programming, and C++ in the 1980s for Object-Oriented
Programming (OOP).

Java is also an OOP language that was developed at Sun MicroSystems (which is now
a subsidiary of Oracle Corporation) and was released in 1995. OOP is a programming
methodology that makes it more convenient to reuse software and will be discussed further
in Chaps. 2 , 5 , and 9 .

Although no prior programming experience is necessary to learn Java in this text,


programmers with experience in C or C++ will recognize a number of similarities between
Java and these languages. Conversely, programmers learning Java first will also notice a
number of similarities should they subsequently learn C or C++. The reason for this
similarity between these languages is that both Java and C++ are based on C. Since Java
does not contain some of the features of C++ (such as operator overloading and multiple
inheritance, where overloading and inheritance will be discussed in Chaps. 5 and 9 ), it
is an easier language to learn.

0.2.4 High-level Translation

If high-level languages are easier to learn and use, how can they be implemented on a
computer that can only understand machine language? Similar to assembly language
needing an assembler, the program needed to translate a high-level language to a low-level
language is a compiler or an interpreter. Although there is a one-to-one correspondence
between assembly language and machine language, there is a one-to-many correspondence
4 0 Introduction to Computing Concepts

between a high-level language and a low-level language. This means that for one high-
level language instruction, there can be many low-level assembly or machine language
instructions. Even though different CPUs need different compilers or interpreters to
convert a particular high-level language into the appropriate machine language, compilers
and interpreters allow the same high-level language to be used on different CPUs.
The difference between a compiler and an interpreter is that a compiler will translate
the high-level language instructions for the entire program to the corresponding machine
language for subsequent execution, whereas an interpreter will translate and then execute
each instruction one at a time. Further, a compiler might translate directly to machine
language, or it might translate the high-level language to assembly language, and then let
an assembler convert the assembly language program to machine language as shown in
Fig. 0.2. Once the machine language is created, it is subsequently loaded into the
FRPSXWHU¶V5$0DQGH[HFXWHGE\WKH&38
As mentioned above, an interpreter works slightly differently than a compiler. Instead
of converting an entire high-level program into machine language all at once and then
executing the machine language, an interpreter converts one line of the high-level program
to machine language and then immediately executes the machine language instructions
before proceeding on with the converting and executing of the next high-level instruction
(see Fig. 0.3). The result is that compiler-generated code executes faster than interpreted
code because the program does not need to be converted each time it is executed. However,
interpreters might be more convenient in an educational or development environment
because of the many modifications that are made to a program which require a program to
be converted each time a change is made.

Compile Interpreter

High-Level Machine High-Level Machine

Instruction1 10101010 Instruction1 10101010


01010101 01010101

Instruction2 00110011 Instruction2 00110011


11101110 11101110

Instruction3 00001111 Instruction3 00001111


11110000 11110000

1. Translate all the instructions 1. Translate one instruction at a time

2. Then execute all the machine 2. And then execute only the corresponding
instructions machine instructions

Fig. 0.3 Compilers and interpreters


0.2 Overview of Hardware and Software 5

Java is somewhat unique in that it uses both a compiler and an interpreter to convert the
high-level instructions to machine language. A compiler is used to convert the Java
instructions into an intermediate-level language known as bytecode, and then the bytecode
is converted into machine language using an interpreter.

Since the intent of Java was for portability on the World Wide Web, the advantage of
using both a compiler and an interpreter is that most of the translation process can be done
by the compiler, and when bytecode is sent to different types of machines, it can be
translated by an interpreter into the machine language of the particular type of machine that
the code needs to be run on (see Fig. 0.4).
Note that just as there can be a one-to-many relationship between high-level and low-
level instructions, there can be a one-to-many relationship between Java and bytecode.
However, unlike the one-to-one relationship between assembly language and machine
language, there can also be a one-to-many relationship between bytecode and machine
language, depending on the machine for which the bytecode is being interpreted.

Interpreter
Compiler

Java Bytecode Machine

Instruction1 Bytecode 10101010


Bytecode 01010101

Instruction2 Bytecode 00110011


11101110

Instruction3 Bytecode 00001111


Bytecode 11110000

1. Translate all the Java instructions 2. Then translate one bytecode


instruction at a time

3. And then execute only the corresponding


machine instructions

Fig. 0.4 Java instructions, bytecode, and machine language

0.3 Introduction to Computational Thinking


$FFRUGLQJWR:LQJ³&RPSXWDWLRQDOWKLQNLQJLVXVLQJFRQFHSWVIURPFRPSXWHUVFLHQFHWR
VROYHSUREOHPVDQGGHVLJQV\VWHPV´>@$VFDQEHVHHQLQWKHIROORZLQJFKDSWHUV
in order to write a good program, a number of techniques need to be used, including
decomposition, pattern recognition, abstraction, algorithms, and logical thinking.
Decomposition is used to break down problems into smaller sections, which makes
complex problems more manageable. Pattern recognition is the process of finding
similarities to previously solved problems. Then, the same solution or a slightly modified
6 0 Introduction to Computing Concepts

solution can be used to solve new problems. Abstraction is the filtering out of
unnecessary information. In other words, taking a step back from the specific details and
focusing on the big picture allows one to create a more generic solution. Algorithms are
step-by-step instructions to solve a problem. It is important to create a plan, an algorithm,
for the solution when solving a problem. Logical thinking is deductive inference of new
information on existing information. Computational thinking is a problem-solving
process that involves a number of core principles from computer science as mentioned
above.

But how can these principles be used in non-programming context, for example, solving
the Tower of Hanoi game? The Tower of Hanoi game consists of three pegs, and initially
one of the non-centered pegs contains several rings stacked in order of descending
diameter from bottom to top. The goal is to move the stack of rings to another non-
centered peg as shown in the Fig. 0.5.

Initial state Final state

Fig. 0.5 Tower of Hanoi game

During the process, only one ring can be moved at a time which means only a top ring is
removed among the towers at any given time. Consequently, several rings cannot be
moved at once. Another rule is that a bigger ring cannot be placed on the top of a smaller
one. At the start of the game, the only ring that can be moved is the smallest ring and it
may be placed on one of the two pegs. Next, there are two rings that can be moved. There
is no good reason to move the smallest one back to the original stack or to another peg.
So, the next move should be moving the second smallest ring. As it cannot be stacked on
the top of the smallest one, naturally it goes on the other peg. By understanding the rules,
logical thinking is used to determine the next step. When making a move, do not be
distracted by color of the rings or pegs, nor the sounds they make, but focus on the rings.
This is simplifying the problem using abstraction. As in Fig. 0.6 after successive moves,
there is a point where the largest ring is on one peg and rest of the rings are stacked on
another peg in order the largest to the smallest from the bottom to the top. Realize that
during the moves, a ring can be placed on the top of any ring that is bigger than itself, not
merely the next larger ring.
0.3 Introduction to Computational Thinking 7

Fig 0.6 The largest ring in the final position

Now the task is to move the stack that has one smaller number of rings. During the
process there will be a situation where the second largest ring is on the top of the largest
one and the rest of the rings are stacked in correct order on another peg as shown in Fig.
0.7.

Fig 0.7 The largest and the second largest rings in the final position

Notice that every time the largest ring of the particular stack is placed in the final
position, the next problem is to solve the same problem with one less number of rings,
which means the task to solve the Tower of Hanoi game is divided into smaller problems
using decomposition. Also realize that the same technique can be used to solve the
problem with different sizes by seeing the pattern. Making a plan of where to moving a
ring is step-by-step procedure, which is an algorithm.

Computer scientists naturally use computational thinking when writing programs,


however, as can be seen in the Tower of Hanoi example, it also allows non-computer
scientists to benefit from a computational approach to problem-solving. Many disciplines
have been influenced by computational thinking in some way, including statistics,
biology, engineering, and economics. As computational thinking can be applied in
everyday life, currently there is an initiative to introduce computational thinking skills to
primary and secondary school children as well as reinforcing them at the college level.

0.4 Essentials of Software Design

0.4.1 Syntax, Semantics, and Errors


During the process of translating a language to machine language, the translator catches
certain types of errors. Before looking at the various types of errors, a distinction should
8 0 Introduction to Computing Concepts

be made between the syntax and the semantics of a program. Simply stated, the syntax is
the grammar of the language, and the semantics is the meaning or what each instruction
does. To explain further, syntax is the spelling of the individual words, where the
semicolons go, and so on. If mistakes are made, a compiler will detect what are known as
syntax errors, generate messages to the programmer, and the program will not be compiled
or executed. Although syntax is very important, there is a tendency for first-time
programmers to spend too much time learning syntax to avoid syntax errors. However,
there must be equal time spent on semantics to ensure that the program does what the
programmer intended it to do.
Even though there might not be any syntax errors, there can be what are called execution
errors or run-time errors, such as division by zero. When these types of errors occur, the
appropriate error messages are generated and execution stops. Even worse, there can also
be logic errors, which are mistakes in the logic of the program so that the program does
not do what was intended. The unfortunate aspect of logic errors is that they do not produce
any error messages which can make them extremely difficult to find and fix.

0.4.2 Design Methodology


When writing a program for the first time, there is a tendency to want to just start keying
the program into the computer and get it to work. As a result, many beginning programmers
focus primarily on the syntax of their program because they want to avoid getting syntax
errors. Initially this method of just typing in a program appears to work fairly well when
programs are small at the beginning of a class and in the text. However, as problems get
more complex and they become more difficult to solve, the programs written this way will
tend to have not only more syntax errors but complicated logic errors which are more
difficult to correct since no error messages are provided.

As an analogy, an individual might be able to build a small storage shed by just sawing
and nailing some lumber together without worrying about the overall design of the project.
However, with a larger project such as a house, apartment building, or office building, that
methodology would not be sufficient. Instead, there are many other people who must be
consulted, including the original customer who wants the building built, the architects who
work with the customer, the contractors, and the carpenters. The same holds true in the
world of programming where a programmer and/or systems analyst works with others such
as customers, users, and managers.

What are needed are various strategies and tools to help write programs correctly to
minimize logic errors. Just as in the above example where blueprints and plans are used by
the architect, there are techniques that can be used by analysts, software engineers, and
programmers. Although the complete process for developing software might not be needed
initially with smaller programs, it does not hurt to practice the various techniques on
smaller programs to gain familiarity, so that when one advances to more difficult projects,
one is comfortable with many of the techniques. Although the following techniques are
used primarily with non-object-oriented programs, they can be augmented with object-
oriented design techniques introduced in chapter 2 and used in larger programs.
0.4 Essentials of Software Design 9

There are many different methodologies and number of stages within the various
methodologies for solving problems that can be found in different texts, but upon closer
examination, they are all rather similar. They tend to include at least four stages, and they
are usually comparable to the following:
1. Analysis
2. Design
3. Implementation
4. Maintenance
0.4.2.1 Analysis
The analysis stage is where the needs of the user or customer are first determined.
Questions concerning the form and quantity of the input, the type of processing that needs
to be done, the storage requirements of data, and the type of output needed are asked and
clarified at this stage. This would be similar to a customer in a construction project trying
to determine what type of building should be built. In a first semester programming class,
this stage may or may not be included. Sometimes a professor might have already
completed the analysis stage and included what is needed in the programming assignment.
However, at other times, they might require this stage and a number of questions will need
to be asked by the student. This might be especially true when working on a team project
in a software design or senior capstone course.

0.4.2.2 Design

The design stage is where a project begins to take shape. It is similar to the architect
creating a set of blueprints and models for the user to examine, because changes are much
easier to make on paper or with the model than once the construction of the building has
started. Various tools such as pseudocode and Unified Modeling Languge (UML) diagrams
(discussed shortly) are used by systems analysts, software engineers, and programmers to
help design the program. Again, it is much easier to make changes during the design phase
than after the programming has begun.

0.4.2.3 Implementaion

The implementation stage is where the code is actually written, entered, compiled, and
syntax errors are corrected. Once the code is free of syntax errors, it is thoroughly tested.
This includes testing various components of the program to be sure each section is working
properly. If not, the code needs to be debugged to correct any logic errors. In addition to
the various components, the entire program needs to be tested to ensure that all the
components work together as planned. Sometimes errors are a result of not following the
design, whereas other times, it is not necessarily the code but rather the design itself that
has the error, in which case one has to go back and correct the error in the design. The
result is that the stages above do not necessarily need to be rigorously adhered to, but rather
when at a stage one may need to return to a previous stage for clarification or to fix a
possible error.
10 0 Introduction to Computing Concepts

Although it is tempting to jump directly to the implementation stage, this tendency


should be avoided. It is important to take the time to properly design the algorithm first
before starting to key in a program. An algorithm is a step-by-step sequence of instructions,
not necessarily implemented on a computer. Once an algorithm is implemented in a
specific language, it is then a program. By taking the time to design a well-thought-out
algorithm, there will be fewer logic errors in the program. Although it might seem to take
longer to include the design stage, the savings will be more than made up for in less time
spent fixing logic errors later.

0.4.2.4 Maintenance

The maintenance stage is where all the modifications and updates take place. In an
industrial strength program, more time is spent in the maintenance phase than all of the
three preceding stages. This is because once a program is up and running, there can be
numerous changes that need to be made over the lifetime of a program. This is another
reason why a program should be designed well in order to facilitate modifications later in
the life of a program. Unfortunately, beginning programmers do not often experience this
stage of a program, because once the concepts are learned from one programming
assignment, the program is often not used again and another program is assigned to
introduce the next set of concepts. However, in some upper-level courses, the assignments
get longer, existing programs might be modified and reused, and students get to have some
experience with the maintenance stage of programs. Regardless, it helps even beginning
students to design well-thought-out programs to gain practice in the event that a professor
decides it might be easier to modify an existing program rather than having to design a new
program from scratch, as done in the real world.

0.4.3 Tools and Techniques

0.4.3.1 Pseudocode

One technique that can help during the design stage is the use of pseudocode.
Pseudocode is a combination of English and a programming language. Since it is not a
SURJUDPPLQJODQJXDJHWKLVLVWKHUHDVRQIRULWVQDPHDV³SVHXGR´FRGH7KHDGYDQWDJHRI
using pseudocode is that one can concentrate on the logic of an algorithm and not worry
about the syntax of a particular programming language. In fact, well-written pseudocode
should be understood by any programmer regardless of the programming language that
they use, and they should be able to convert the pseudocode into their particular
programming language. However, there can be many different versions and levels of detail
WKDWFDQEHLQFOXGHGLQSVHXGRFRGHVRLWLVEHVWWRFKHFNZLWKRQH¶VLQVWUXFWRURUFRPSDQ\
for any preferences or standards that are employed. As a simple example, consider the
following pseudocode on the left compared to the Java statement on the right:

Calculate the area of a rectangle areaRec = height * width;

At this time it is not nececessary to understand the Java code on the right. However, note
that the verbal description on the left is much easier to understand than the detailed Java
0.4 Essentials of Software Design 11

code. As a result, one does not need to concentrate on the intricate syntax, but rather the
semantics. As an alternative, notice the more specific pseudocode on the left.

areaRec height x width areaRec = height * width;

Both the pseudocode and the Java code are known as assignment statements as will be
discussed in the next chapter. Note that an arrow is used in the pseudocode instead of an
equal sign in the Java code to indicate an assignment statement. This helps illustrate the
direction of assignment, since some languages use symbols other than an equal sign to
illustrate assignment. Also notice that a mathematical symbol is used instead of an asterisk
to illustrate multiplication. Lastly, a semicolon is not used since not all other languages use
them to terminate statements.
The result is that the pseudocode in the second example is more specific than the first
example which helps with the translation to Java, but it is also more generic than the Java
statement which helps in the translation to other languages as well. Again, these are just
two samples of pseudocode, so be sure to check your local guidelines and requirements
which should be used. In this text, when pseudocode is used, it will be written with as much
detail as possible so as not to be ambiguous and to help with the translation into Java.
0.4.3.2 OOP and UML
Since the term object has been used previously, what is an object? In the past, programs
were often written with large sections of code that were not very helpful to reuse when
another program needed to be written.
It can help with the understanding of the idea of objects to think of an automobile. An
automobile has many different parts such as steering mechanisms, transmissions, brakes,
etc. Instead of designing the transmission as unique to only one type of auto, a generic plan
for a transmission can be designed first. Then particular versions of the transmission could
be built to be put into different types of automobiles. The plans for the transmission can be
thought of as a class and the differing versions of the transmission as instances of that class,
or in other words, objects. This way a whole new design for a transmission does not need
to be created for each type of auto, but rather just a different variation. The same applies to
software, where a whole new complete design does not need to be created but just a
different version of the original class. Although this is just a brief glimpse of objects, this
same idea can be applied to software and a more complete discussion will be presented in
Chapter 2.
Unified Modeling Language (UML) is a visual method used to help contruct a program
using classes and objects. One might ask since Java is an Object Oriented (OO) language
and UML is helpful in creating an OO program, why would one need pseuodocode? The
answer is because each class and instance of a class or object contains code, pseudocode
can help with the design of the class. So whereas UML helps with the creating of classes
and objects, pseudocode helps with the creation of code within classes and objects. UML
will be discussed further in Section 2.10.
12 0 Introduction to Computing Concepts

0.4.3.3 Debugging
Even when all attempts to write a logically correct program are followed, the possibility of
logic errors still exists. The process of finding and fixing logic errors is known as
debugging. When trying to debug a program, a programmer should not start to randomly
alter code in the hope that the error might be fixed. Although this might work occasionally
with smaller programs, it rarely works as programs become larger and more complex.
Instead, one should look for patterns in the output in an attempt to isolate the problem.
Further, one needs to carefully check the program by walking through the code to ensure
that it is doing what was originally intended.
To assist in this process many Integrated Development Environments (IDEs), which are
used to enter, edit, compile, and execute a program, sometimes include debuggers that can
trace the contents of various memory locations to help locate a logic error. However, do
not rely on the debugger alone to help correct the problem, but rather use it as a tool to
assist in tracing the logic of the program. If a debugger is not available, well-placed output
statements at critical points in the program can help in the debugging process. In the end,
it is the programmer reading the code carefully to see what the code is actually doing, rather
than what one thinks it is doing, that will ultimately fix logic errors in a program. [9]

0.5 A Brief Look at Computer Ethics

As one is just learning to write code in a programming language, there is a tendency to be


preoccupied with getting programs to work correctly. However, at the same time when
acquiring a lot of technical knowledge, it is also important to learn what is needed to
enter the computing profession. This includes, but is not limited to knowledge of various
ethical issues concerning property, privacy, and responsibility.
Initially one might not think this is important since they are just a beginner and not
working for a major company. Although this may not seem initially significant, these
issues become increasingly even more important as one rapidly gains new knowledge,
even during a course of a semester.
For example, when beginning programmers are working on their own individual
programming assignments in a classroom environment, they will often be turned in for a
JUDGH$VVXPLQJLWLVQRWDJURXSSURJUDPPLQJDVVLJQPHQWHDFKVWXGHQW¶VSURJUDPLV
considered to be their own property whether it is on paper or on a file in a computer. If
RQHVWXGHQWKDVDFFHVVWRDQRWKHUVWXGHQW¶VSURJUDPWKHQWKLVFRXOGbe a concern of
intellectual property rights.
In another example, one might have the opportunity to work in the Information
Technology (IT) department at the school, college, or university. This might entail
ZRUNLQJRQDQRWKHUVWXGHQW¶VVWDIIPHPEHU¶VRU IDFXOW\PHPEHU¶VFRPSXWHU,QGRLQJ
so, one might have access to programs and files that have sensitive information which
would concern the privacy of others.
Also, consider the possibility that after completing a year or two of coursework, one
might have the opportunity to work on an internship writing programs for a company.
Then the programs are no longer merely submitted for a grade but are integral to the
operation of that company. Mistakes are no longer just points taken off for a grade, but
could haYHDQLPSDFWRQILQDQFLDOPDWWHUVDQGDIIHFWSHRSOH¶VOLYHV7KHUHVXOWLVWKDWWKH
0.5 A Brief Look at Computer Ethics 13

testing and correct operation of a program is imperative and is the responsibility of the
programmers.
The field that includes these instances and other related issues is known as ethics. Entire
stand-alone courses are offered, typically from the philosophy department, and
corresponding books have been written that address the many theories and the application
of those theories to specific instances. In addition, these ethical theories have been
applied to paticular areas such as business ethics, medical ethics, environmental ethics as
well as computer ethics. With respect to the latter, many colleges offer separate courses
in computer ethics that may be given as an elective or may be required for a major in
computer science.
Since entire books have also been written on the field of computer ethics it would not be
possible to discuss all the theories here. Fortunately, various professional organizations in
many different fields provide codes of ethics. The same is true in the field of computing
where the Institute of Electrical and Electronics Engineers (IEEE) Computer Society[3]
and the Association of Computing Machinery (ACM) [1] have each developed a Code of
Ethics. These codes help provide guidance when confronting various ethical situations
within the world of computing.
These codes are provided by their respective organizations and are available online. The
reader is encouraged to look at least one of these codes as possLEO\LQGLFDWHGE\RQH¶V
instructor. It might also prove interesting to look at both codes to see the similarities and
possible differences between them.
After examining a code of ethics such as the ACM Code of Ethics, there are some
exercises at the end of the chapter based on the discussion at the beginning of this section
that can serve either as a discussion in the classroom or as an essay question in a
homework assignment. Although it is beyond the scope of this text to examine the
theories and codes in any detail, there are a number of texts that examine theories and
LVVXHVLQPRUHGHWDLOVXFKDV³(WKLFVLQ&RPSXWLQJ$&RQFLVH0RGXOH´E\-RVHSK0LJJD
Kizza. [5]

0.6 Summary
‡ Machine language and assembly language are low-level languages, where the former
uses ones and zeros and the latter uses mnemonics.
‡ High-level languages are more English-like, where C, C++, and Java are examples of
high-level languages.
‡ Compilers convert the entire high-level language program into machine language
before executing the machine language program, whereas interpreters convert a high-
level language program one instruction at a time and then execute only the
corresponding machine language instructions before converting the next high-level
instruction.
‡ Java is a hybrid system, where the Java instructions are converted into an intermediate
language called bytecode using a compiler and then the bytecode is converted into
machine language using an interpreter.
‡ Computational thinking is a problem-solving process that includes decomposition,
pattern recognition, abstraction, algorithms, and logical thinking. The above are skills
that you can apply in life in general.
14 0 Introduction to Computing Concepts

‡ Even if one is just beginning in the field of computing, it is important to understand


professional obligations.
‡ Three important areas of computer ethics include but are not limited to property,
privacy, and responsibility,
‡ Two prominent professional Codes of Ethics are provided by the IEEE Computer
Society and the ACM.
0.7 Exercises (Items Marked with an * Have Solutions in Appendix E )
1. A River Crossing puzzle involves a famer crossing a river with a wolf, a goat, and
a cabbage on the way home. After the famer bought them at the market, he rented
a boat to cross the river. The farmer could take only one of his purchases with
him, the wolf, the goat, or the cabbage, when taking the boat. If a wolf, a goat,
and cabbage are left unattended together, the wolf would eat the goat, or the goat
would eat the cabbage. The farmer's challenge is to bring himself and his
purchases to the other side of the river, leaving each purchase intact. After solving
the problem discuss how the computational thinking concepts, decomposition,
pattern recognition, abstraction, algorithm, and logical thinking, were used to
come up with the answer.

2. Sudoku is a number-placement puzzle. In original Sudoku, the objective is to fill a


9 × 9 grid with numbers so that each column, each row, and each of the nine 3 × 3
sub-grids contain all the numbers from 1 to 9. Discuss how the computational
thinking concepts, decomposition, pattern recognition, abstraction, algorithm, and
logical thinking, could be used to solve the puzzle.

3. Compare the two codes of ethics mentioned previously in Section 0.5. Identify
one or more elements that are similar. If possible, identify one element that
appears in one code but does not seem to appear in the other.

4. Using one of the code of ethics such as the ACM Code of Ethics, or the code
assigned by the instructor, analyze the following scenarios as to the proper course
of action. Be sure to indicate which element in the code applies.

a. A student in a first-year course has asked a fellow student for assistance with
their programming assignment. After starting to look over the program for the
SRWHQWLDOHUURUWKHVWXGHQWVHHNLQJDVVLVWDQFHVD\V³7KLVLVVXUHWDNLQJDORWRI
time. Might it be easier to just send me a copy of the file containing your
SURJUDPDQG,FDQMXVWFKDQJHWKHQDPHDWWKHWRS"´$FFRUGLQJWRWKHFRGHRI
ethics selected or assigned, what should the student who is providing the
assistance do? What alternatives are there?

b. A student is working in the Information Technology department and has been


asked to work on a faculty members personal computer to install a new
version of a software package. In the process, the student sees the spreadsheet
FRQWDLQLQJWKHJUDGHVIRUWKHSURIHVVRU¶VFODVVHV7KLQNLQg that it will cause
0.7 Exercises (Items Marked with an * Have Solutions in Appendix E) 15

no harm, the student worker decides to look up a grade of a friend in the


spreadsheet. According to the code of ethics selected or assigned, should the
student worker do this? Is it causing any harm?

c. An intern at a local company is having difficulty with a small section of code


being worked on which is a part of a much larger project. When testing the
section of code, the intern realizes that it works over 99% of the time and
rarely fails. Since the intern is afraid of losing the internship, the possibility of
a failure happening is very small and the code is an insignificant part of the
much larger project, the intern submits the code as being complete. Based on
the code of ethics selected or assigned, should the intern submit the code as
complete? What alternatives are there?
1
Input/Output, Variables, and Arithmetic
James T. Streiba* and Takako Somaa
a
Computer Science Program, Illinois College, Jacksonville, IL, USA

Abstract
This chapter provides an initial skeleton program from which to create subsequent programs. An introduction
to variables, constants, assignment statements, arithmetic operations, and simple input/output using the
keyboard and monitor is also provided. Further, there is a discussion concerning comments and a simple
complete program is included at the end of the chapter.

Keywords
Input/Output, Variables, Assignment Statement, Arithmetic, Comments.

1.1 Introduction
This section introduces the reader to the basics of the Java programming language and
helps get the first program up and running as quickly as possible. To that end, the
explanation of some of the more complicated aspects of a Java program are deferred until
later. Many of the OOP (Object-Oriented Programming) concepts are only briefly
introduced, but will be discussed more thoroughly in Chapters 2, 5, and 9. For those who
want a more detailed discussion and elaboration of some of the concepts presented in this
chapter, it can be found in Appendix A. However, note that for some of the sections of
Appendix A, it helps to have read at least Chapters 2, 5, and possibly 9, or have had
previous OOP programming experience.

1.2 Java Skeleton


Probably the best way to understand a programming language is to start right away with a
sample program. Although the following program does not do anything, it will serve as a
skeleton to add instructions to in the future and provide a starting point to understand the
basic layout of a Java program. At first the program in Fig. 1.1 might look a bit
intimidating, but with various explanations and with time it will become more
understandable. For now, a few of the words and symbols will be explained here and the
rest will be discussed elsewhere in the text.

© The Author(s), under exclusive license to Springer Nature Switzerland AG 2023 17


J. T. Streib and T. Soma, Guide to Java, Undergraduate Topics in Computer Science,
https://doi.org/10.1007/978-3-031-22842-1_1
18 1 Input/Output, Variables, and Arithmetic

Fig. 1.1 Java skeleton program

The first line in the program begins with the reserved word class. A reserved word is
one that has a special meaning in a program and cannot have its meaning changed by the
programmer nor can it be used for other purposes. As briefly discussed in Chapter 0, a class
is a definition of a group of objects. Although classes and objects will be discussed further
in Chap. 2 , for now think of a class as a blueprint for a house and the houses built from
the blueprint as objects.

The word Skeleton following the reserved word class, is the name of the class
that is provided by the programmer. This name is known as an identifier and the rules for
identifiers will be discussed in Section 1.4. Note that usually class names begin with a
capital letter. The entire definition of the class, Skeleton, should be placed between the
first opening brace and the last closing brace, { }.

This class has one method definition starting on the second line. A method is like a
function in mathematics which are sent values via arguments and can return a single value.
Typically, the body of the method is indented to improve the readability of the program.

The word main is the name of the method. When a program is run, the system will
search for the main method and start executing instructions in the main method. For now,
the rest of the words in this line will be discussed later throughout the text and in Appendix
A. The definition of the main method also starts with an opening brace and ends with a
closing brace. Inside the braces, a sequence of instructions would be placed. For now, the
method does not have any instructions and only contains a comment line.
Comments will not be compiled and executed when the program is run. They are used
to make programs easier for other programmers to understand. Comments can start with
// symbols and continue to the end of the line as shown in Figure 1.1, or be placed between
/* and */ symbols. The // symbols are used for a single-line comment, and /* and */
are used when the comments run over multiple lines. Comments are discussed more
thoroughly in Section 1.9, The above program should compile without any syntax errors
and run without any execution errors, except unfortunately it does not do anything.

³+HOOR:RUOG´
Unless a program performs some type of output, it is not particularly useful and it is
difficult to know whether the program has run. Output can be of many forms including
output to a screen, a printer, or a disk. In this section, only output to a screen will be
considered. Although there are several ways to output data to the screen, this section will
examine the simplest of them to get started.
1.3 “Hello World!” 19

1.3.1 Text-based Output

One of the more common first programs written when learning a new language is the
LQIDPRXV³+HOOR:RUOG´SURJUDP7KHDGYDQWDJHRIWKLVSURJUDPLVWRPDNHVXUHWKDWRQH
is writing a program correctly and using the compiler properly. This program can be written
as shown in Fig. 1.2.

Fig. 1.2 Hello World!

The program looks very similar to the original Skeleton program in Fig. 1.1, except
that the class name has been changed from Skeleton to Output and the comment line
has been replaced with the System.out.println("Hello World!"); statement.
This statement outputs the string contained within the double quotation marks to the
monitor. Java uses System.out to refer to the standard output device which by default
is the monitor. To perform output, one simply uses the println method to display a
primitive value or a string to the monitor. The println method is part of the Java
Application Programming Interface (API) which is a predefined set of classes that can be
used in any Java program. The classes and methods in the Java API provide a variety of
fundamental services that are not part of the language itself.

The method name println LVRIWHQSURQRXQFHGDV³SULQWOLQH´HYHQWKRXJKLWLVQRW


spelled that way. The print portion of println causes the information in the
parentheses to be output to the computer screen, and then the ln portion of println
causes the cursor on the screen to move down to the next line. In this case, the only
information in the parentheses is the string "Hello World!". Following the closing
parenthesis, the statement is terminated with a semicolon.

Go ahead and try typing in this program on your computer using the IDE (Integrated
Development Environment) installed in your lab, home computer, or place of employment
and then compile and execute the program. Provided there are no syntax errors, the output
should appear similar to the following, where the underscore represents the ending location
of the cursor on the screen:

Hello World!
_

Notice that the quotation marks are not output to the screen and the cursor appears on
the next line. Also note that the cursor might not appear on the screen, since there is no
input yet, but in this example, it serves to illustrate where any subsequent input or output
would appear.
20 1 Input/Output, Variables, and Arithmetic

1.3.2 GUI-based Output

Text-based output is simple and easy to implement while learning concepts of a


programming language and testing programs. However, when an application is written
for customers, a Graphical User Interface (GUI) is a user-friendly way of displaying
output.

Simple GUI based output to display a message dialog box can be accomplished by using
the showMessageDialog method as shown in Fig. 1.3.

import javax.swing.*;

class MsgBoxOutput {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hello World!");
System.exit(0);
}
}

Fig. 1.3 Message Dialog Box

The JOptionPane.showMessageDialog indicates that the


showMessageDialog method is defined in the standard class JOptionPane. The
method passes two arguments where the first argument, null, causes the dialog box to
appear in the center of the screen. The second argument is the message to be displayed in
the dialog box.
Note that since the JOptionPane class is not automatically available to Java
programs, the import javax.swing.* statement is added at the beginning of the
program. All the predefined classes and methods in the Java Aplication Program
Interface (API) are organized into packages, and the import statement identifies those
packages that are not automatically available.

Also, notice that the last statement System.exit(0) causes the program to stop
executing since a program with JOptionPane does not automatically stop when the
end of the main method is reached. When the program above is executed a dialog box
shown below appears on the screen.
1.4 Variables and Constants 21

When the user clicks the OK button, the dialog box will close. Both types of output, text-
based and GUI-based, will be used throughout the text, with text-based used more
frequently due to its simplicity.

1.4 Variables and Constants


One of the things that often needs to be added to the skeleton are data members. Another
name is a memory location so that data can be stored. Yet another name is a variable since
the contents of the memory location can vary, just as a variable in mathematics.
In order to understand variables and how data is stored in memory, it is oftentimes very
helpful to draw a picture of the memory location. A memory location can be thought of as
a mailbox that has two main parts. One part is the contents, which includes the letters that
are inside the mailbox, and the other is the address of the mailbox as shown in Fig. 1.4.

Fig. 1.4 Representation of memory

The address of the mailbox is usually a number, like the address of a memory location
in a computer. At the machine language level, the address is in ones and zeros, just like the
machine language instructions mentioned in Chapter 0. However, using numbers to
represent the address of a memory location can be quite confusing, especially if there are
hundreds of memory locations in a program. Instead, it is helpful to use characters to form
names, called symbolic addressing, to make it easier to remember what data is stored in
what memory location as shown in Fig. 1.5. In this example, the name number is used to
describe the contents of the corresponding memory location. This is one of the primary
advantages of using assembly language over machine language, and this is also true of all
high-level languages including Java.

Fig. 1.5 Using names for memory locations

Instead of a three-dimensional representation of a mailbox to represent a memory


22 1 Input/Output, Variables, and Arithmetic

location, it is much easier to draw a two-dimensional representation. Further, instead of


using ones and zeros to represent the contents of the memory location, it is easier to use
the decimal number system to represent values as follows:

Although not as crucial in high-level languages (like Java) as it is in low-level languages


(machine and assembly languages), it is important to remember that a memory location has
two features: its address and its contents. In Java, the programmer is typically concerned
about its contents.
Given the above representation of variables, how are they actually created or declared?
When a variable is declared, there are two things that must be done. First, a variable needs
to be given a name so that it can be referred to by various instructions in the program, and
second, the type of data that will be stored in the memory location needs to be indicated.
The reason for this is that although all the data is stored as ones and zeros as discussed
above, different types of data are stored using different combinations of ones and zeros. A
single one or zero is called a binary digit (abbreviated as a bit), and a group of 8 bits is
called a byte. Typically, the more bytes that make up a memory location, the larger the
number that can be stored in the location. Although how the data is actually stored is
beyond the scope of this text, Table 1.1 shows some of the types of data, the size, and the
range of values that can be stored for each type.
Table 1.1 Data types

Type Size Range


byte 1 byte í128 to 127
short 2 bytes í32,768 to 32,767
Int 4 bytes í2,147,483,648 to 2,147,483,647
long 8 bytes í9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 4 bytes íௗîௗ38 WRௗîௗ38
double 8 bytes íௗîௗ 308 WRௗîௗ 308
char 2 bytes one character
String 2 or more bytes one or more characters

Typically, the types int, double, char, and String are the ones that are used the
most frequently. For example, should one want to declare a variable named number and
have it store an integer, it would be declared as follows:

int number;

First the type is indicated, in this case int for integer, and then the identifier or name
of the variable number is given, followed by a semicolon. An identifier or the name of
the variable can be almost anything except for a reserved word as discussed in Section 1.2,
but there are certain rules that need to be followed as well as some suggestions that should
be followed. The length of the variable name can be from 1 to any number of characters
long. Further, the variable name can be composed of letters, numbers, underscores _, and
dollar signs $, but must begin with a letter. Also, the variable name is case sensitive,
meaning that cat, Cat, and CAT are separate variable names and correspond to separate
memory locations.
1.4 Variables and Constants 23

Typically, a variable name should not be too long, because they can be difficult to read,
but by the same token, they should not be too short either, for it could become difficult to
remember what it represents. For example, if the letter n were used instead of number,
then it might not be clear whether n stood for name, number, or numeral. Exceptions
to this are for variables from a mathematical expression. For example, the variables x, y,
and z are commonly used to represent the points of a Cartesian coordinate system, and i,
j, or k are used for loop control variables as will be discussed in Chap. 4 . Although most
of the time this text will avoid the use of shorter names, on occasion shorter names might
be used to save space or for the sake of simplicity to concentrate on other aspects of a code
segment. If a variable is too long, it can be difficult to read as in the following:
numberofcatsanddogs. Common practice in Java is not to capitalize the first letter of
a variable but to capitalize the first letter in all subsequent words, as in
numberOfCatsAndDogs. Notice that it is a little easier to read that way. Also on
occasion, abbreviations can be used such as num instead of number, but be sure to use
good ones. Further, this text will occasionally show some of the more commonly used
abreviations.
Variables of other types can be declared as well, such as a variable of type float or
double. Although numbers of type float WDNHXSOHVVVSDFHLQWKHFRPSXWHU¶VPHPRU\
they are less precise and can sometimes cause inaccuracy in calculations. Even though they
take up more memory, this text will use double variables to alleviate some possible
problems later. For example, should one want to declare a variable to hold a double
precision value, it would be declared as follows:

double average;

Further it could contain a value and would look like the following:

Notice that instead of showing the number zero as an integer, it is represented as a real
number with a decimal point, to indicate its type as a double.
All of the types given in Table 1.1, other than the String type, are known as primitive
data types, meaning that when they are declared, the memory needed to store the associated
data is allocated at that time. However, a String data type is a reference data type. When
a variable of type String is declared, the memory allocated is not used to store the data,
but rather only to store a reference to the data. String data types are unique in that although
they are technically objects, they can be used syntactically as if they were primitive data
types.
The first part of this text will use strings in a very limited capacity. An understanding
of strings is much easier once one has had an introduction to objects and practice with
objects, so a full description of how string objects are created and manipulated is presented
in Chap. 6 +RZHYHUIRUQRZWKLVWH[WZLOOUHSUHVHQWVWULQJV³DVLI´WKH\DUHSULPLWLYH
data types, and the following shows a character primitive data type and a simplified view
of the string data type. For example, a character and string could be declared as follows:
24 1 Input/Output, Variables, and Arithmetic

char initial; String name;


and would be represented with values as follows, respectively:

Note that the char data type is represented using single quotation marks and that the
String is represented using double quotation marks. Although a character could be
represented as a String of length one, it is usually better to use the char data type.
Further, there are also ways to extract a single char type from a String data type. Again,
a full description will be deferred until Chap. 6 .
In contrast to variables, a constant can be declared so that its value cannot be changed.
Although not nearly as useful as variables, constants have their place in a program when a
value does not need to be changed, nor should be changed. For example, if an integer N
needs to remain a 7, then it could be declared as follows, where the use of the reserved
word final indicates that N is a constant:
final int N = 7;
Typically, constant names are declared as all capital letters to help other programmers
distinguish them from variables. In another example, suppose a number like PI needs only
two digits after the decimal point, then it could be declared as follows:
final double PI = 3.14;
Although the use of a constant might not be readily apparent at this time, their use will
become clearer in subsequent examples after discussing assignment statements in the next
section.

1.5 Assignment Statements


In the previous section, all the drawings of the memory locations had values in them. How
did those values get there? By default, Java technically initializes all int variables to 0
and double variables to 0.0. Also, char variables are initialized to the empty character
indicated by two single quotation marks '' and String variables are initialized to null
as will be discussed further in Chap. 6 . Although this can be helpful in some instances, in
many other languages variables do not have a default value. The variables contain whatever
was in that memory location from the last time it was used which could be interpreted as
junk to another program, cause logic errors, and be difficult to debug. Variables with
unknown initial values are said to be indeterminate. As a result, many programmers do not
XVH -DYD¶V default values and assume instead that the initial values of variables are
indeterminate, which will also be the assumption of this text. So instead of initially showing
an integer variable with the number 0 in it, this text will show the variable as indeterminate
with a dashed line in it as shown below:

Does this mean that all variables need to be initialized to some value? Not necessarily.
As will be seen, only those variables that need an initial value for subsequent processing
1.5 Assignment Statements 25

should be initialized. Initializing a variable to a value when it does not need to be initialized
could be confusing to other programmers reading the code, as will be discussed later in this
chapter and in Chap. 4 on iteration structures.
So, if a variable is assumed not to be initialized, how does one initialize a variable to a
value such as 0 or any other value for that matter, such as 5? After a variable is declared,
it can be given a value in an assignment statement using an assignment symbol. The
assignment symbol is the equal sign. However, when one first starts to use the equal sign,
RQHPXVWUHPHPEHUWKDWLWGRHVQRWPHDQWKDWWKHYDULDEOHRQWKHOHIWLV³HTXDOWR´WKHYDOXH
on the right, but rather that the value on the right is copied into or assigned to the variable
on the left. Again, this is best shown by way of an example:

int number;
number = 5;
After the variable number is declared as type int, the second statement indicates that
the integer 5 is assigned or copied into the variable number and the memory location
would then appear as follows where green indicates a change:

number 5

Again, the assignment statement is not really saying that number is equal to 5 or equals
5, but rather that the variable number is assigned a 5 or takes on the value of 5. Although
it is tempting to say that number equals 5 and even though most people will understand
what is meant, try to avoid saying it, and there will be less difficulty in the future as shown
in Sect. 1.8 on arithmetic statements.
Note that it is possible to combine the previous two statements into one statement as
shown below. It looks similar to the definition of a constant in the previous section but
without the word final in the statement:
int number = 5;
The above syntax is perfectly legal and saves a line when writing a program. However,
when first learning a language, it helps to reinforce the distinction between the declaration
of a variable and the assignment of a YDOXHWRDYDULDEOH2IFRXUVHLIRQH¶VLQVWUXFWRUGRHV
not mind the above shortcut or if one is studying this text on their own and likes the
shortcut, then go ahead and use it. However, this text will use the previous two-line method
at least for the next few chapters to help reinforce the distinction between the declaration
of a variable and the assignment of a value to a variable.
Continuing, what if one wanted to take the contents of number, and copy it into another
memory location named answer? For example, consider the following code segment:

int number, answer;


number = 5;
answer = number;
After both number and answer have been declared in the first line, the variable
number is then assigned the value 5 in the second line and answer will still be
26 1 Input/Output, Variables, and Arithmetic

indeterminate. The memory locations would look as follows:

number 5 answer ---

The third line then takes a copy of the contents of number and places it into the
memory location answer as shown below:

number 5 answer 5

Note that the assignment statement does not remove the 5 from number and put it into
answer, but rather it takes a copy of the 5 and puts it into answer. The original 5 in
number does not disappear. Why does it copy and not move it? The reason is because it
is actually faster for the computer to copy it and not take the time to delete the original.
This is a fundamental concept in most computer languages and will become more important
in the writing of subsequent programs.
Again, the important point to notice is that the copying of values is from right to left,
not left to right. This sometimes causes confusion among beginning programmers, possibly
because they are used to reading from left to right. The reason why Java and many previous
languages go from right to left is because they are mimicking some of the assembly
languages on many machines. Ideally it would be nice if languages used an arrow to show
how values are copied as shown below:

However, most keyboards do not have an arrow character, so an equal sign was used.
Just be very careful to remember that values are copied from right to left and there should
not be any problems.
Assigning variables of type double is similar to the above and will not be shown here;
however, a couple of points need to be made concerning assigning variables of different
types. For example, what would happen if a variable of type int was assigned to a variable
of type double as shown below?

int number;
double result;
number = 5;
result = number;
As before, the contents of the memory locations after the assignment of 5 to number
would be as follows:

number 5 result ---

Then when the next assignment statement is executed, the int value of 5 would be
1.5 Assignment Statements 27

copied, converted to a double value of 5.0, and assigned to result as follows:

number 5 result 5.0

Would the value in number be converted to a 5.0? The answer is no, as shown above,
because only the variable to the left of the assignment symbol is altered by an assignment
statement. The 5 in number is not converted, but rather when it is copied, it is converted
to the proper type so that it can be assigned to result.
If an int value can be stored in a variable of type double, is the reverse true? The
answer is no, because, for example, how could the number 5.7 be stored as an integer
without the fractional part? A way around this problem is to use a typecast operator. A
typecast operator allows a value of one type to be converted to another type. In the case
below, the typecast operator (int) converts the double value in number to type int
so it can be assigned to result. As before, the value in number would not change and
would still contain a 5.7. However, what happens to the fractional part? The result is that
it is truncated and a 5 is stored in result:

double number;
int result;
number = 5.7;
result = (int) number;
What if the value needed to be rounded instead? Fortunately, Java has the Math class
which contains a method named round. As mentioned previously, a method is somewhat
like a function in mathematics. The name of the class, Math, is followed by a period and
the name of the method, round. Parentheses are placed after the method name and contain
the argument, number, which is sent to the method. The code segment from above is
rewritten below:

double number;
int result;
number = 5.7;
result = (int) Math.round(number);
Unfortunately, when the round method is sent a value of type double, it returns a
value of type long, but the typecast operator (int) can again be used to convert the
value of type long to type int. Since number initially contains 5.7, the variable
result would contain a 6. Again, the value in number would not change and would still
contain a 5.7.

number 5.7 result 6

Of course, if the precision of the type double is needed, the better solution would be
to change the type of result to double to preserve the fractional part of number. The
28 1 Input/Output, Variables, and Arithmetic

round method is one of the many methods available in the Math class which is discussed
in more detail in Sect. 1.8 on arithmetic statements.

1.6 Output

1.6.1 Text-based
Recall from Section 1.3 that the following:
System.out.println("Hello World!");
output the following:
Hello World!
_
where the cursor appeared on the next line. However, what if one wanted to split the string
so that it appears on two separate lines? This can be accomplished by using two separate
System.out.println statements as follows:

System.out.println("Hello");
System.out.println("World!");
As one might suspect, the output would appear as follows:

Hello
World!
_

The string "Hello" is output and the cursor moves down to the next line. Then, the
string "World!" is output, and again the cursor moves down to the next line in
preparation for the subsequent line to be output.

In another example, what if one wanted to output the following with a blank line
between the two words and the cursor at the bottom?

Hello

World!
_

The following code segment would accomplish this task:


System.out.println("Hello");
System.out.println();
System.out.println("World!");

The first statement outputs the word Hello and moves the cursor down to the second
line. The second statement does not output anything, so the ln of the
System.out.println statement causes the cursor to move down to the third line and
the blank line to appear on output. Lastly, the word World! is output and the cursor moves
1.6 Output 29

down to the fourth line. Note that usually a System.out.println() indicates that a
blank line will be output, but there are exceptions that are discussed further in Appendix
A.
Although the above is useful for outputting strings and vertically formatting output, how
does one output integers and real numbers? Combining the information learned in the
previous two sections, one can then have a program as shown in Fig. 1.6.

Fig. 1.6 Outputting an int

This program declares the variable num to be of type int, assigns the value 5 to num,
and then outputs the contents of the variable num. Note that the variable num is not
enclosed in quotation marks, so the word num is not output, but rather the contents of the
variable num are output. Unfortunately, only the integer 5 would be output to the screen
which would not be very useful. Instead, it is helpful to output some other information for
the user to identify and understand the information on the screen.
The output statement in the program in Fig. 1.6 can be modified to include the string
"The number is " followed by a plus sign prior to the variable num as shown in Fig.
1.7. A plus sign between two strings or between a string and any other type of data means
concatenation. In other words, the string "The number is " and the contents of num
are output as if they are one string. It should be noted that one needs to be careful should
only two integers be separated by a plus sign, because then it would mean addition as will
be discussed in Sect.1.8. However, provided a string or a concatenated string appears to the
left, then the item to the right of the plus sign will be concatenated instead of added. Note
that there is a space within the quotes at the end of the string so that the contents of the
variable num are separated from the word is in the string. The result is that the output of
this program would appear as follows:

The number is 5
_

Fig. 1.7 Outputting an int with description of output


30 1 Input/Output, Variables, and Arithmetic

What happens if one outputs a number of type double using the same format shown
in Fig. 1.7? For example, Fig.1.8 outputs the contents of the variable num of type double.

Fig. 1.8 Outputting a double precision number without formatting

As will be discussed further in Sect.1.8, the / means division and num will take on the
value of one third. When the above program is compiled and executed, the screen displays
The number is 0.3333333333333333
Although using high precision is necessary during computation, it may not be needed
when a number of type double is displayed. How can one limit the number of digits after
the decimal point in a floating-point number? A predefined method in the Java API called
printf can be used. The general syntax of the printf method is as follows:

printf(control string, expr, expr, …)

where control string is a string that may consist of substrings and format specifiers
and an expr represents a variable, expression, or constant value. A format specifier
indicates how an expr should be displayed. A specifier %d is used for a decimal integer,
%f for a floating-point number, %c for a character, and %s for a string. For numbers, the
total width and precision can be indicated in a specifier. For example, the specifier %10d
outputs an integer value with a width of at least 10. The specifier %10.2f outputs a
floating-point number with a width of at least 10 including a decimal point and two digits
after the decimal point. The width of character and string values can also be indicated. For
example, the specifier %3c outputs a single character and adds two spaces before it, and
%10s outputs a string with a width at least 10 characters. If there is more than one expr
to be output, they must match the specifiers within the control string in order, number, and
type. Using the formatting information described above, the program in Fig. 1.8 can be
rewritten as in Fig. 1.9.

Fig. 1.9 Formatting a double precision number


Discovering Diverse Content Through
Random Scribd Documents
M. d'Egmont, whom everybody called "the good gentleman,"
dwelt in a cottage on the Trois Saumons River, about three quarters
of a league from the manor house. With him there lived a faithful
follower who had shared alike his good and his evil fortunes. André
Francœur was of the same age as his master, and was also his
foster-brother. Having been the playfellow of his childhood, and the
trusted friend rather than the valet of his riper years, André
Francœur had found it as natural to follow D'Egmont's fortunes in
adversity as in prosperity.
D'Egmont and his servant were living on the interest of a small
capital which they had in common. One might even say that the
savings of the valet were even greater than those of the master. Was
it consistent with D'Egmont's honor to be thus, in a way, dependent
on his own servant? Many will answer no; but "the good gentleman"
argued otherwise.
"When I was rich I spent my wealth for my friends, and how have
my friends rewarded me? André, alone, has shown himself grateful
and noble-hearted. In no way, therefore, do I lower myself by
associating my fortune with his, as I would have done with one of
my own station had one been found as noble as my valet."
When Jules arrived, the good gentleman was busy weeding a bed
of lettuce in his garden. Entirely absorbed, he did not see his young
friend, who overheard the following soliloquy:
"Poor little insect! I have wounded you, and lo! all the other ants,
just now your friends, are falling upon you to devour you. These tiny
creatures are as cruel as men. I am going to rescue you; and as for
you, my good ants, thanks for the lesson; I have now a better
opinion of my kind."
"Poor fellow!" thought Jules, "with a heart so tender, how he must
have suffered!"
Withdrawing noiselessly, he entered by the garden gate.
M. d'Egmont uttered an exclamation of delight on seeing his
young friend, whom he loved as a son. Although, during the thirty
years that he had lived on Captain D'Haberville's estate, he had
constantly refused to take up his abode at the manor house, he yet
was a frequent visitor there, often remaining a week at a time when
there were no strangers present. Without actually shunning society,
he had suffered too much in his relations with men of his own class
to be able to mingle cordially in their enjoyments.
Although poor, M. d'Egmont was able to do a great deal of good.
He comforted the afflicted; he visited the sick, whom he healed with
herbs whose virtues were revealed to him by his knowledge of
botany; and if his alms-giving was not lavish, it was accompanied by
such sympathy and tact that it was none the less appreciated by the
poor, who had come to know him by no other title than that of le
bon gentilhomme.
When D'Egmont and his young friend entered the house, André
set before them a dish of fine trout and a plate of broiled pigeons,
garnished with chives.
"It is a frugal supper, indeed," said D'Egmont, "I caught the trout
myself in yonder brook, about an hour ago, and André bagged the
doves this morning at sunrise, in yonder dead tree, half a gunshot
from the cottage. You see that, without being a seigneur, I have a
fish-pond and dove-cote on my estate. Now for a salad of lettuce
with cream, a bowl of raspberries, a bottle of wine—and there is
your supper, friend Jules."
"And never fish-pond and dove-cote supplied better meal to a
hungry hunter," exclaimed Jules.
The meal was a cheerful one, for M. d'Egmont seemed to have
recovered something of the gayety of his youth. His conversation
was no less instructive than amusing; for, although he had mingled
much with men in his early days, he had found in study a refuge
from his unhappiness.
"How do you like this wine?" said he to Jules, who was eating like
a hungry wolf, and had already quaffed several bumpers.
"It is capital, upon my word."
"You are a connoisseur, my friend," went on M. d'Egmont. "If it is
true that wine and men improve with age, that wine must indeed be
excellent; and as for me, I must be approaching perfection, for I am
very nearly ninety."
"Thus it is," said Jules, "that they call you 'the good gentleman.'"
"The Athenians, my son, sent Aristides into exile, and at the same
time called him the Just. But let us drop men and speak of wine. For
my own part, I drink it rarely. As with many other useless luxuries, I
have learned to do without it, and yet I enjoy perfect health. This
wine is older than you are; its age, for a man, would not be much,
but for wine it is something. Your father sent me a basket of it the
day you were born. In his happiness he made gifts to all his friends.
I have kept it with great care, and I only bring it out on such rare
occasions as this. Here is a health to you, my dear boy. Success to
all your undertakings; and when you come back to New France,
promise that you will come and sup here with me, and drink a last
bottle of this wine, which I will keep for you. You look astonished.
You think it likely that when you return I shall have long since paid
that debt which is paid even by the most recalcitrant debtor. You are
mistaken, my son; a man like me does not die. But come, we have
finished supper, let us go and sit sub tegmine fagi, which may be
interpreted to mean, under that splendid walnut-tree whose
branches are reflected in the river."
The night was magnificent. The ripple of running water was the
only sound that broke the moonlit stillness. M. d'Egmont was silent
for some moments, and Jules, not caring to disturb his reverie,
began tracing hieroglyphics with his finger in the sand.
"I have greatly desired," said "the good gentleman," "to have a
talk with you before your departure, before you go out into the
world. I know that we can profit little by the experience of others,
but that each must purchase his own. No matter, I shall at least have
the consolation of having opened my heart to you, a heart which
should have been dried up long since, but which yet beats as warmly
as when I led the joyous troops of my companions more than half a
century ago. Just now you looked at me with surprise when I said
that a man like me does not die; you thought I spoke in metaphor,
but I was sincere at the moment. So often on my knees have I
begged for death that I have ended by almost doubting Death's
existence. The heathen have made of him a divinity, doubtless that
they might call him to their aid in time of heavy sorrow. If it is as
physiology teaches us, and our sufferings depend upon the
sensitiveness of our nerves, then have I suffered what would have
killed fifty strong men." M. d'Egmont was silent once more, and Jules
flung some pebbles into the river.
"See," resumed the old man, "this stream which flows so quietly
at our feet. Within an hour it mingles with the troubled waters of the
St. Lawrence, and in a few days it will be writhing under the scourge
of the Atlantic storms. Behold therein an image of our life! Thy days
hitherto have been like the current of this stream; but soon you will
be tossed on the great river of life, and will be carried into the ocean
of men, whose waves rage ceaselessly. I have watched you from
child-hood up; I have studied your character minutely, and that is
what has caused me to seek this conversation. Between your
character and mine I have found the closest resemblance. Like you,
I was born kind-hearted, sympathetic, generous to a fault. How has
it come that these virtues, which should have secured me happiness,
have rather been the cause of all my ills? How comes it, my son,
that these qualities, so applauded among men, have risen against
me as my most implacable enemies and beaten me to the dust? I
can not but think that I deserved a kindlier fate. Born, like you, of
rich and loving parents, I was free to follow my every inclination.
Like you, I sought nothing so much as the love of those about me.
Like you, in my childhood I would not willingly injure the most
insignificant of God's creatures, and to the beggar child I gave the
very clothes I wore. Needless to add that, again like you, my hand
was ever open to all my comrades, so that I was said to have
'nothing of my own.' It is curious to consider that, at the hands of
my playfellows, I never tasted ingratitude. Is ingratitude the
attribute only of the full-grown man? Or is it a snare which this
human nature casts about the feet of generous childhood, the better
to despoil the prey when grown to be a richer prize! But, no; it is
impossible that youth could be so depraved.
"And you, Jules," continued the old man after this semi-soliloquy,
"have you yet experienced the ingratitude of those you have
befriended, the ingratitude which pierces the heart like a blade of
steel?"
"Never," said the young man.
"It is self-interest, then, bitter fruit of civilization, which causes
ingratitude; the more a man needs, the more ungrateful he
becomes. This reminds me of a little story. About twenty years ago a
poor savage of the Huron tribe came to me in a pitiable state. It was
spring. He had made a long and painful march, he had swum the icy
streams when overheated, and as a result he was seized with a
violent attack of pleurisy, accompanied by inflammation of the lungs.
I judged that only a copious bleeding could save him, and I made
shift to bleed him with my penknife. In a word, with care and simple
remedies, I effected a cure; but his convalescence was slow, and he
stayed with me more than two months. In a little while André and I
could talk to him in his own tongue. He told me that he was a great
warrior and hunter, but that fire-water had been his ruin. His thanks
were as brief as his farewells:
"'My heart is too full for many words,' said he; 'the Huron warrior
knows not how to weep like a woman. I thank you, my brothers,'
And he vanished in the forest.
"I had entirely forgotten my Indian, when about four years later
he arrived at my door, accompanied by another savage. I could
scarcely recognize him. He was splendidly clad, and everything
about him bespoke the great hunter and the mighty warrior. In one
corner of my room he and his companion laid down two bundles of
merchandise of great value—the richest furs, moccasins splendidly
embroidered with porcupine quills, and exquisite pieces of work in
birch bark, such as the Indians alone know how to make. I
congratulated him upon the happy turn his affairs had taken.
"'Listen to me, my brother,' said he. 'I owe you much, and I am
come to pay my debt. You saved my life, for you know good
medicine. You have done more, for you know the words which reach
the heart; dog of a drunkard as I was, I am become once more a
man as I was created by the Great Spirit. You were rich when you
lived beyond the great water. This wigwam is too small for you; build
one large enough to hold your great heart. All these goods belong to
you,' The gratitude of this child of the forest brought tears to my
eyes; for in all my long life I had found but two men who could be
grateful—the faithful André, my foster-brother, and this poor Indian,
who, seeing that I was going to accept nothing but a pair of deer-
hide moccasins, struck three fingers rapidly across his mouth with a
shrill cry of 'houa,' and took himself off at top speed with his
companion. Never after could I find a trace of him. Our good curé
undertook the sale of the goods, the product of which, with interest,
was lately distributed among his tribe."
The good gentleman sighed, reflected a moment, then resumed
his speech:
"I am now going to tell you, my dear Jules, of the most happy
and most wretched periods of my life. Five years of happiness! Five
years of misery! O God! for one single day of the joy of my youth,
the joy as keen as pain, which could make me forget all that I have
suffered! Oh, for one of those happy days when I believed in human
friendship, when I knew not the ingratitude of men!
"When I had completed my studies, all careers were open to me.
That of arms seemed most suitable, but I hated to shed blood. I
obtained a place of trust under the government. For me such a place
was ruin. I had a great fortune of my own, my office was a lucrative
one, and I scattered by handfuls the gold which I despised.
"I do not accuse others in order to palliate my own follies. But
one thing is sure, I had more than enough for all my own expenses,
though not for those of my friends and my friends' friends, who
rushed upon me like hungry wolves. I bear them no grudge; they
but acted according to their nature. As for me, my hand was never
shut. Not only my purse, but my signature was at everybody's
disposal. There was my greatest mistake; for I may say in all
sincerity that ninety-nine times out of a hundred, in my times of
greatest embarrassment, I had to meet their liabilities with my own
cash in order to save my credit. A great English poet has said:
"Neither a borrower nor a lender be,
For borrowing dulls the edge of husbandry,
And loan oft loses both itself and friend.
"Give, my dear boy, with both hands; but be chary of your
signature.
"My private affairs were so mingled with those of my office that it
was long before I discovered how deeply I was involved. The
revelation came upon me like a thunderbolt. Not only was I ruined,
but I was on the verge of a serious defalcation. At last I said to
myself, 'what matters the loss of the gold, so long as I pay my
debts? I am young, and not afraid to work, and I shall always have
enough. Moreover, my friends owe me considerable sums. When
they see my difficulties, not only will they hasten to give back what
they owe, but they will do for me as I have so often done for them.'
What a fool I was to judge others by myself! For me, I would have
moved heaven and earth to save a friend from ruin. How innocent
and credulous I was! They had good reason, the wretches, to laugh
at me.
"I took account of what was owed me and of the value of my
property, and then perceived that with these affairs settled up there
would remain but a small balance, which I could cover with the help
of my relations. The load rolled off my heart. How little I knew of
men! I told my debtors, in confidence, how I was situated. I found
them strangely cold. Several to whom I had lent without written
acknowledgment had even forgotten that they owed me anything.
Those whose notes I held, declared it was ungenerous of me to take
them unawares. The greater number, who had had business at my
office, claimed boldly that I was in debt to them. I did, indeed, owe
them a trifle, while they owed me considerable sums. I asked them
for a settlement, but they put me off with promises; and meanwhile
undermined my credit by whispering it about that I was on the verge
of ruin. They even turned me into ridicule as a spendthrift fool. One
wag of a fellow, whom but eighteen months before I had saved not
only from ruin but from disgrace (his secret shall die with me), was
hugely witty at my expense. His pleasantries had a great success
among my old friends. Such measureless ingratitude as this
completely crushed me. One only, and he a mere acquaintance,
hearing that I was in difficulties, hastened to me with these words:
"'We have had some little transactions together; I think you will
find here the correct balance in your favor. Please look up the matter
in your books and see if I am right.'
"He is dead long since. Honor to his memory, and may the
blessings of an old man descend upon his children!
"The inevitable day was close at hand, and even had I had the
heart to make further struggle nothing could save me. My friends
and enemies alike were intriguing for the spoils. I lowered my head
before the storm and resigned.
"I will not sadden you with the story of all I suffered; suffice to
say that, fallen into the claws of pitiless creditors, I drank the cup of
bitterness to the dregs. Apart from the ingratitude of my friends, I
was not the sort of man to grieve greatly over my mere personal
misfortunes. Even within the walls of the Bastille my gayety would
not have deserted me; I might have danced to the grim music of the
grating of my bolts. But my family! my family! Oh, the gnawing
remorse which harasses the day, which haunts the long sleepless
night, which suffers you neither forgetfulness nor rest, which
wrenches the nerves of one's heart as with pincers of steel!
"I believe, my boy, that with a few exceptions every man who can
do so pays his debts; the torments he endures at the sight of his
creditor would constrain him to this, even without the terrors of the
law. Glance through the ancient and modern codes, and you will be
struck with the barbarous egotism which has dictated them all alike.
Can one imagine, indeed, any punishment more humiliating than
that of a debtor kept face to face with his creditor, who is often a
skinflint to whom he must cringe with fearful deference? Can
anything be more degrading than to be obliged to keep dodging a
creditor?
"It has always struck me that civilization warps men's judgment,
and makes them inferior to primitive races in mere common sense
and simple equity. Let me give you an amusing instance. Some years
ago, in New York, an Iroquois was gazing intently at a great,
forbidding structure. Its lofty walls and iron-bound windows
interested him profoundly. It was a prison. A magistrate came up.
"'Will the pale face tell his brother what this great wigwam is for?'
asked the Indian. The citizen swelled out his chest and answered
with an air of importance:
"'It is there we shut up the red-skins who refuse to pay the furs
which they owe our merchants.'
"The Iroquois examined the structure with ever-increasing
interest, walked around it, and asked to see the inside of this
marvelous wigwam. The magistrate, who was himself a merchant,
was glad to grant his request, in the hope of inspiring with
wholesome dread the other savages, to whom this one would not
fail to recount the effective and ingenious methods employed by the
pale faces to make the red-skins pay their debts.
"The Iroquois went over the whole building with the minutest
care, descended into the dungeons, tried the depth of the wells,
listened attentively to the smallest sounds, and at last burst out
laughing.
"'Why,' exclaimed he, 'no Indian could catch any beaver here.'
"In five minutes the Indian had found the solution of a problem
which civilized man has not had the common sense to solve in
centuries of study. This simple and unlearned man, unable to
comprehend such folly on the part of a civilized race, had naturally
concluded that the prison had subterranean canals communicating
with streams and lakes where beaver were abundant, and that the
savages were shut up therein in order to facilitate their hunting of
the precious animals, and the more prompt satisfaction of their
creditors' claims. These walls and iron gratings seemed to him
intended for the guarding of the treasure within.
"You understand, Jules, that I am speaking to you now on behalf
of the creditor, who gets all the sympathy and pity, and not on
behalf of the debtor who, with his dread and suspicion ever before
his eyes, gnaws his pillow in despair after watering it with his tears.
"I was young, only thirty-three years of age. I had ability, energy,
and a sturdy faith in myself. I said to my creditors, take all I have
but leave me free, and I will devote every energy to meeting your
claims. If you imprison me you wrong yourselves. Simple as was this
reasoning, it was incomprehensible to civilized man. My Iroquois
would have understood it well enough. He would have said: 'My
brother can take no beaver if the pale face ties his hands.' My
creditors, however, took no account of such simple logic as this, and
have held the sword of Damocles over my head for thirty years, the
limit allowed them by the laws of France."
"What adorable stupidity!" cried Jules.
"One of them, however," continued M. d'Egmont, "with a
delightful ingenuity of torture, obtained a warrant for my arrest, and
with a refinement of cruelty worthy of Caligula himself, did not put it
in execution till eighteen months later. Picture me for those eighteen
months, surrounded by my family, who had to see me trembling at
every noise, shuddering at the sight of every stranger who might
prove to be the bearer of the order for my imprisonment.
"So unbearable was my suspense that twice I sought out my
creditor and besought him to execute his warrant without delay. At
last he did so, at his leisure. I could have thanked him on my knees.
From behind my bars I could defy the malice of men.
"During the first month of his captivity the prisoner experiences a
feverish restlessness, a need of continual movement. He is like a
caged lion. After this time of trial, this feverish disquiet, I attained in
my cell the calm of one who after being tossed violently by a storm
at sea, feels no longer anything more than the throb of the subsiding
waves; for apart from the innumerable humiliations of imprisonment,
apart from my grief for my family, I was certainly less wretched. I
believed that I had drunk the last drop of gall from the cup which
man holds to his brother's fevered lips. I was reckoning without the
hand of God, which was being made heavy for the insensate fool
who had wrought his own misfortune. Two of my children, at two
different periods, fell so dangerously ill that the doctors gave them
up and daily announced to me that the end was near. It was then I
felt the weight of my chains. It was then I learned to cry, like the
mother of Christ, 'Approach and see if there be any sorrow like unto
my sorrow.' I was separated from my children only by the breadth of
a street. During the long night watches I could perceive the stir
about their couch, the lights moving from one room to another; and
I trembled every moment lest the stillness should fall which would
proclaim them no longer in need of a mother's care. I blush to
confess that I was sometimes tempted to dash my life out against
the bars.
"Meanwhile my persecutor knew as well as I what was passing in
my family. But pity is fled from the breast of man to take refuge in
brute beasts that have no understanding. The lamb bleats sadly
when one of his companions is slaughtered, the ox bellows with rage
and pain when he smells the blood of his kind, the horse snorts
sharply and utters his doleful and piercing cry at the sight of his
fellow struggling in the final agony, the dog howls with grief when
his master is sick; but with whisperings and gossip and furtive
pleasantry man follows his brother to the grave.
"Lift up your head in your pride, lord of creation! You have the
right to do so. Lift your haughty head to heaven, O man whose heart
is as cold as the gold you grasp at day and night! Heap your
slanders with both hands on the man of eager heart, of ardent
passions, of blood burning like fire, who has fallen in his youth! Hold
high your head, proud Pharisee, and say, 'As for me, I have never
fallen!'" "The good gentleman" pressed his hands to his heart, kept
silent for some minutes, and at length resumed:
"Pardon me, my son, that, carried away by the memory of my
sufferings, I have spoken the whole bitterness of my heart. It was
but seven days after the coming of his friends when the great
Arabian poet Job, the singer of so many sorrows, broke out with this
heart-rending cry, 'Pereat dies in quâ natus sum!' As for me, these
fifty years have I buried my lamentations in my heart, and you will
pardon me if I have spoken now with bitterness, if I have
calumniated mankind.
"As I had long ago given up to my creditors all that I possessed,
and had sold my real estate and personal property for their benefit,
after four years' imprisonment I petitioned the King for my release.
The Government was of the opinion that I had suffered enough, but
there remained one great difficulty—when a debtor has given up
everything, does anything yet remain? The question was a knotty
one. Nevertheless, after long debate, it was decided in the negative,
and very politely they showed me the door.
"My future was broken, like my heart, and I had nothing to do but
vegetate without profit to myself or others. But observe the fatality
that pursued me. When making my surrender to my creditors I
begged them to leave me a certain property of very small immediate
value, which I foresaw that I might turn to good account. I promised
that whatever I could make out of it should go to wiping out the
debt. They laughed me in the face; and very naturally, for there was
a beaver to catch. Well, Jules, this same property, which brought
hardly enough to cover costs of sale, sold ten years later for a sum
which would have covered all my debts and more.
"Europe was now too populous for me, and I embarked with my
faithful André for New France. I chose out this peaceful dwelling
place, where I might have lived happily could I have drunk the
waters of Lethe. The ancients, our superiors in point of imagination,
knew the needs of the human heart when they created that stream.
Long tainted with the errors of the sixteenth century, I used once to
cry in my pride, 'O men, if I have shared your vices, I have found
few among you endowed with even one of my virtues.' But religion
has taught me to know myself better, and I have humbled myself
beneath God's hand, convinced at length that I could claim but little
credit for merely following the inclinations of my nature.
"You are the only one, Jules, to whom I have hinted the story of
my life, suppressing the cruelest episodes because I know the
tenderness of your heart. My end is attained; let us now go and
finish the evening with my faithful André, who will keenly appreciate
this attention on the eve of your departure."
When they re-entered the house André was making up a bed on a
sofa, a piece of furniture which was the result of the combined skill
of master and man. This sofa, of which they were both very proud,
had one leg shorter than the others, but this little inconvenience was
remedied with the aid of a chip.
"This sofa," said "the good gentleman," with an air of pride, "has
cost André and me more elaborate calculations than Perrault
required for the construction of the Louvre; but we accomplished it
at last to our satisfaction. One leg, to be sure, presents arms to all
comers. But what work is perfect? You must have remembered, my
André, that this camp-bed was to be a soldiers' couch."
André, though not quite relishing this pleasantry, which jarred a
little on his vanity, nevertheless could not help laughing.
Late in the evening M. d'Egmont handed Jules a little silver
candlestick exquisitely wrought.
"There, my dear boy, is all that my creditors have left me of my
ancient fortune. They intended it, I suppose, to solace my sleepless
nights. Good-night, dear boy; one sleeps well at your age; and
when, after my prayers beneath the vault of that great temple which
is forever declaring the glory of God, I once more come under my
roof, you will be deep in your slumbers."
CHAPTER X.
MADAME D'HABERVILLE'S STORY.

Saepè malum hoc nobis, si mens non læva fuisset,


De cœlo tactas memini praedicere quercus.
Virgil.
All was silence and gloom at D'Haberville Manor; the very
servants went about their work with a spiritless air, far unlike their
usual gayety. Madame D'Haberville choked back her tears that she
might not add to her husband's grief, and Blanche, for her mother's
sake, did her weeping in secret; for in three days the vessel was to
set sail. Captain D'Haberville had bidden his two friends, the priest
and M. d'Egmont, to meet Jules and Archie at a farewell dinner. At
this meal every one strove to be cheerful, but the attempt was a
conspicuous failure. The priest, wisely concluding that a sober
conversation would be better than the sorrowful silence into which
the party was continually dropping, introduced a subject which was
beginning to press on all thoughtful minds.
"Do you know, gentlemen," said he, "that a storm is gathering
dark on the horizon of New France. The English are making
tremendous preparations, and everything seems to indicate an early
attack."
"And then?" exclaimed Uncle Raoul.
"Then, whatever you like, my dear chevalier," answered the curé;
"but it must be acknowledged that we have hardly forces enough at
our command to long resist our powerful neighbors."
"My dear abbé," exclaimed Uncle Raoul, "I think that in your
reading this morning you must have stumbled on a chapter of the
lamentations of Jeremiah."
"I might turn your weapon against yourself," retorted the priest,
"by reminding you that those prophecies were fulfilled."
"No matter," almost shouted Uncle Raoul, clinching his teeth. "The
English, indeed! The English take Canada! By heaven, I would
undertake to defend Quebec with my crutch. You forget, it seems,
that we have always beaten the English; that we have beaten them
against all odds—five to one—ten to one—sometimes twenty to one!
The English, indeed!"
"Concedo," said the curé; "I am ready to grant all you claim, and
more too if you like. But mark this. We grow weaker and weaker
with every victory, while the enemy, thanks to the foresight of
England, rises with new strength from each defeat; meanwhile,
France leaves us to our own resources."
"Which shows," exclaimed Captain D'Haberville, "the faith our
King reposes in our courage."
"Meanwhile," interposed M. d'Egmont, "he sends us so few
soldiers that the colony grows weaker day by day."
"Give us but plenty of powder and lead," answered the captain,
"and a hundred of my militia will do more in such a war as that
which is coming upon us—a war of reconnoitrings, ambuscades, and
surprises—than would five hundred of the best soldiers of France. I
speak from experience. For all that, however, we stand in great need
of help from the mother country. Would that a few of those
battalions which our beloved monarch pours into the north of Europe
to fight the battles of Austria, might be devoted to the defense of
the colony."
"You might rather wish," said "the good gentleman," "that Louis
XV had left Maria Theresa to fight it out with Prussia, and had paid a
little more attention to New France."
"It is perhaps hardly becoming in a young man like me," said
Lochiel, "to mix myself up in your arguments; but, to make up for
my lack of experience, I will call history to my aid. Beware of the
English, beware of a government ever alive to the interests of its
colonies, which it identifies with the interests of the empire; beware
of a nation which has the tenacity of the bull-dog. If the conquest of
Canada is necessary to her she will never swerve from her purpose
or count the sacrifice. Witness my unhappy country."
"Bah!" cried Uncle Raoul, "the Scotch, indeed!"
Lochiel began to laugh.
"Gently, my dear Uncle Raoul," said "the good gentleman"; "and,
to make use of your favorite maxim when you are collecting the
rents, let us render unto Cæsar that which is Cæsar's. I have studied
the history of Scotland, and I can assure you that neither in valor
nor in patriotism need the Scotch yield place to any other nation,
ancient or modern."
"Oh, you see, I only wanted to tease this other nephew of mine,"
exclaimed Uncle Raoul, swelling his chest; "for we know a little
history ourselves, thank God. No one knows better than Archie my
esteem for his fellow-countrymen, and my admiration for their
dashing courage."
"Yes, dear uncle, and I thank you for it," said Archie, grasping him
by the hand; "but distrust the English profoundly. Beware of their
perseverance, and remember the Delenda est Carthago of the
Romans."
"So much the better," said Jules. "I will be grateful to their
perseverance if it brings me back to Canada with my regiment. May
I do my first fighting against them here, on this soil of Canada,
which I love and which holds all that is dearest to me! You shall
come with me, my brother, and shall take revenge in this new world
for all that you have suffered in your own country."
"With all my heart," cried Archie, grasping the handle of his knife
as if it were the terrible claymore of the Camerons. "I will serve as a
volunteer in your company, if I can not get a commission as an
officer; and the simple soldier will be as proud of your exploits as if
he had a hand in them himself."
The young men warmed into excitement at the thought of heroic
deeds; the great black eyes of Jules shot fire, and the old warlike
ardor of the race suddenly flamed out in him. This spirit was
infectious, and from all lips came the cry of Vive le Roi! From the
eyes of mother, sister, and aunt, in spite of all their efforts to restrain
them, there escaped a few tears silently.
The conversation became eager. Campaigns were planned, the
English were beaten by sea and land, and Canada was set upon a
pinnacle of splendor and prosperity.
"Fill up your glasses," cried Captain D'Haberville, pouring himself
out a bumper. "I am going to propose a health which everybody will
drink with applause: 'Success to our arms; and may the glorious flag
of the fleur-de-lys float forever over every fortress of New France!'"
Just as they were raising the glasses to their lips a terrific report
was heard. It was like a stupendous clap of thunder, or as if some
huge body had fallen upon the manor house, which shook to its very
foundations. Every one rushed out of doors. The sun was shining
with all the brilliance of a perfect day in July. They scaled the roof,
but there was no sign anywhere that the house had been struck.
Every one was stupefied with awe, the seigneur himself appearing
particularly impressed. "Can it be," he exclaimed, "that this
phenomenon presages the fall of my house!"
In vain did M. d'Egmont, the priest, and Uncle Raoul endeavor to
refer the phenomenon to ordinary causes; they could not remove
the painful impression it had left. The glasses were left unemptied in
the dining-room, and the little company passed into the drawing-
room to take their coffee.
What took place afterward only confirmed the D'Haberville family
in their superstitious fears. Who knows, after all, whether such
omens, to which the ancient world lent implicit belief, may not
indeed be warnings from heaven when some great evil threatens us?
If, indeed, we must reject all that our feeble reason comprehends
not, we should speedily become Pyrrhonists, utter skeptics, like
Molière's Marphorius. Who knows? But one might write a whole
chapter on this "who knows."
The weather, which had been so fine all day, began to cloud up
toward six o'clock in the evening. By seven the rain fell in torrents;
the thunder seemed to shatter the vault of heaven, and a great
mass of rock, struck by a thunder-bolt, fell from the bluff with terrific
noise and obliterated the highway.
Captain D'Haberville, who had carried on an immense deal of
forest warfare along with his Indian allies, had become tinctured
with many of their superstitions; and when the disasters of 1759 fell
upon him, he was convinced that they had been foretold to him two
years before.
Jules, seated at supper between his mother and sister and
holding their hands in his, shared in their depression. In order to
turn their thoughts into another channel, he asked his mother to tell
one of those stories with which she used to amuse his childhood.
"It would give me," said he, "yet another memory of the
tenderest of mothers to take with me to Europe."
"I can refuse my boy nothing," said Madame D'Haberville; and
she began the following story:
"A mother had an only child, a little girl, fair as a lily, whose great
blue eyes wandered from her mother to heaven and back from
heaven to her mother, only to fix themselves on heaven at last. How
proud and happy was this loving mother when every one praised the
beauty of her child! Her cheeks like the rose just blown, her tresses
fair and soft as the beaten flax and falling over her shoulders in
gracious waves! Immeasurably happy was this good mother.
"At last she lost the child she idolized; and, like Rachel, she would
not be comforted. She passed her days in the cemetery embracing
the little grave. Mad with grief, she kept calling to the child with
ceaseless pleadings:
"'My darling! my darling! listen to your mother, who is come to
carry you to your own bed, where you shall sleep so warmly! Oh,
how cold you must be under the wet sod!'
"She kept her ear close to the earth, as if she expected a
response. She trembled at every slightest noise, and sobbed to
discover that it was but the murmur of the weeping willow moved by
the breeze. The passers-by used to say: 'This grass, so incessantly
watered by her weeping, should be always green; but her tears are
so bitter that they wither it, even like the fierce sun of midday after
a heavy shower.'
"She wept beside a brook where the little one had been
accustomed to play with pebbles, and in whose pure stream she had
so often washed the little feet. The passers-by used to say:
"'This mother sheds so many tears that she swells the current of
the stream!'
"She nursed her grief in every room wherein the little one had
played. She opened the trunk in which she kept religiously all the
child's belongings—its clothes, its playthings, the little gold-lined cup
of silver from which she had last given it to drink. Passionately she
kissed the little shoes, and her sobs would have melted a heart of
steel.
"She went continually to the village church to pray, to implore
God to work one miracle in her behalf, and give her back her child.
And the voice of God seemed to answer her:
"'Like David you shall go to her, but she shall not return to you.'
"Then she would cry:
"'When, Lord, when shall such joy be mine?'
"She threw herself down before the image of the blessed Virgin,
our Lady of Sorrows; and it seemed to her that the eyes of the
Madonna rested upon her sadly, and that she read in them these
words:
"'Endure with patience, even as I have done, O daughter of Eve,
till the day when your mourning shall be turned into gladness.'
"And the unhappy mother cried anew:
"'But when, when will that blessed day come, O Mother of God?'
"One day the wretched mother, having prayed with more than her
usual fervor, having shed, if possible, more tears than was her wont,
fell asleep in the church, exhausted with her grief. The sexton shut
the doors without noticing her. It must have been about midnight
when she awoke. A ray of moonlight illuminating the altar revealed
to her that she was yet in the church. Far from being terrified, she
rather rejoiced at her situation, if such a thing as joy could be said to
find any place in her sad heart.
"'Now,' said she, 'I can pray alone with God, alone with the
Blessed Virgin, alone with myself!'
"Just as she was going to kneel down a low sound made her raise
her head.
"She saw an old man, who, entering by one of the side doors of
the sacristy, made his way to the altar with a lighted taper in his
hand. She saw with astonishment that it was the former sexton,
dead twenty years before. She felt no fear at the sight, for every
sentiment of her breast had been swallowed up in grief. The specter
climbed the altar steps, lighted the candles, and made the
customary preparations for the celebration of a requiem mass. When
he turned she saw that his eyes were fixed and expressionless, like
those of a statue. He re-entered the sacristy, but reappeared almost
at once, followed this time by a venerable priest bearing a chalice
and clothed in full vestments. His great eyes, wide open, were filled
with sadness; his movements were like those of an automaton. She
recognized the old priest, twenty years dead, who had baptized her
and given her her first communion. Far from being terrified by this
marvel, the poor mother, wrapped up in her sorrow, concluded that
her old friend had been touched by her despair, and had broken the
bonds of the sepulchre for her sake.
"All was somber, grim, and silent in this mass thus celebrated and
ministered by the dead. The candles cast a feeble light like that of a
dying lamp. At the moment when the bell of the 'Sanctus,' striking
with a dull sound, as when a bone is broken by the grave-digger in
some old cemetery, announced the descent of Christ upon the altar,
the door of the sacristy opened anew and admitted a procession of
little children, marching two and two, who traversed the choir and
filed into the space to the right of the altar. These children, the
oldest of whom had had scarce six years of life upon earth, wore
crowns of immortelles and carried in their hands, some of them
baskets of flowers, some of them little vases of perfume, others cups
of gold and silver filled with a transparent liquid. They stepped
lightly, and a celestial rapture shone upon their faces. One only, a
little girl at the end of the procession, appeared to follow the others
painfully, loaded down as she was with two great jars which she
could hardly drag. Her little feet, reddening under the pressure, were
lifted heavily, and her crown of immortelles seemed withered. The
poor mother strove to reach out her arms, to utter a cry of joy on
recognizing her own little one, but she found that she could neither
move nor speak. She watched all the children file past her into the
place to the left of the altar, and she recognized several who had but
lately died. When her own child, bending under her burden, passed
before her, she noticed that at every step the two jars besprinkled
the floor with the water that filled them to the brim. When the little
one's eyes met those of her mother, she saw in their depths a
mingling of sadness, tenderness, and reproach. The poor woman
strove to clasp her in her arms, but sight and consciousness alike
fled from her. When she recovered from her swoon the church was
empty.
"In a monastery about a league from the village, dwelt a monk
who was renowned for his sanctity.
"This old man never left his cell, save to listen with sympathy to
the bitter confessions of sinners, or to succor the afflicted. To the
first he said:
"'I know the corruptness of man's nature, so be not cast down;
come to me with confidence and courage every time you fall, and
my arms shall ever be open to lift you up again.'
"To the second he said: 'Since God, who is so good, lays this
burden upon you now, he is reserving you for infinite joys hereafter.'
"To all he said: 'If I should confess to you the story of my life, you
would be astonished to behold in me a man who has been the sport
of unbridled passion, and my misfortunes would melt you to tears.'
"The poor mother threw herself sobbing at his feet, and told him
the marvelous thing she had seen. The compassionate old man, who
had sounded the depths of the human heart, beheld here a
favorable opportunity to set bounds to this excessive anguish.
"'My dear child,' said he, 'our overwrought imagination often
cheats us with illusions which must be relegated to the realms of
dream. Nevertheless, the Church teaches us that such marvels can
really take place. It is not for us in our ignorance to set limit to the
power of God. It is not for us to question the decrees of Him who
took the worlds into his hand and launched them into space. I
accept, then, the vision, and I will explain it to you. This priest,
coming from the tomb to say a mass, doubtless obtained God's
permission to fulfill part of his sacred ministry which he had left
undone; and the sexton, by forgetfulness or negligence, was
probably the cause of his omission. The children crowned with
immortelles are those who died with their baptismal grace
unimpaired. They who carried baskets of flowers or vases of
perfume are those whose mothers gave them up to God with holy
resignation, comforted by the thought that they were exchanging
this world of pain for the celestial country and the ineffable light
about the throne. In the little cups of gold and silver were the tears
of mothers who, though torn by the anguish of their loss yet taught
themselves to cry: "The Lord gave and the Lord hath taken away;
blessed be the name of the Lord."'
"On her knees the poor mother drank in the old man's words. As
Martha exclaimed at the feet of Christ, 'Lord, if thou hadst been
here, my brother had not died. But I know that even now, whatever
thou wilt ask of God, God will give it thee,' even so the poor mother
cried in her ardent faith, 'If thou hadst been with me, my father, my
little one would not have died; but I know that even now,
whatsoever thou wilt ask of God, God will give it thee.'
"The good monk reflected a moment and prayed God for wisdom.
It was a sentence of life or of death that he was about to pronounce
upon this mother who appeared inconsolable. He was about to strike
a blow which should either restore her to reason or break her heart
forever. He took her hands in his withered and trembling clasp, and
said gently:
"'You loved, then, this child whom you have lost?'
"'Loved her? My God, what a question!' And she threw herself
moaning at his feet. Then, raising herself suddenly, she grasped the
skirt of his cassock and besought him through her sobs: 'You are a
saint, my father; oh, give me back my child—my darling!'
"'Yes,' said the monk, 'you loved your little one. Doubtless you
would have done much to spare her even the lightest grief?'
"'Anything, everything, my father!' exclaimed the poor woman; 'I
would have been rolled on the hot coals to spare her a little burn.'
"'I believe you,' said the monk; 'and doubtless you love her yet?'
"'Do I love her? Merciful Heaven!' cried the wretched mother,
springing to her feet as if bitten by a serpent; 'I see, priest, that you
know little of a mother's love if you imagine death can efface it.' And
trembling from head to foot, she burst again into a torrent of tears.
"'Begone, woman,' said the old man, forcing himself to speak with
sternness; 'begone, woman, who hast come to impose upon me;
begone, woman, who liest to God and to his priest. Thou hast seen
thy little one staggering under the burden of thy tears, which she
gathers drop by drop, and thou tellest me that thou lovest her! She
is near thee now, toiling at her task; and thou sayest that thou
lovest her! Begone, woman, for thou liest to God and to his
minister!'
"The eyes of the poor woman were opened as if she were
awaking from a frightful dream. She confessed that her grief had
been insensate, and she besought the pardon of God.
"'Go in peace,' said the old man; 'resign yourself to God's will, and
the peace of God will be shed upon your soul.'
"Some days after, she told the good monk that her little one,
radiant with joy and carrying a basket of flowers, had appeared to
her in a dream and thanked her for having ceased from her tears.
The good woman, who was rich in this world's goods, devoted the
rest of days and her substance to charity. To the children of the poor
she gave most loving attention, and adopted several of them. When
she died they wrote upon her tomb, 'Here lies the mother of the
orphans.'"
All were deeply moved by Madame D'Haberville's story, and some
were even in tears. Jules embraced his mother, and left the room to
hide his emotion.
"O God," he cried, "guard this life of mine! for if evil should befall
me, my loving mother would be as inconsolable as the mother in the
story she has just told us."
A day or two later Jules and Archie were tossing upon the
Atlantic; and at the end of two months, after a prosperous voyage,
they reached the shores of France.
CHAPTER XI.
THE BURNING OF THE SOUTH SHORE.

They came upon us in the night,


And brake my bower and slew my knight:
My servant a' for life did flee
And left us in the extremitie.

They slew my knight, to me so dear;


They slew my knight, and drove his gear;
The moon may set, the sun may rise,
But a deadly sleep has closed his eyes.

Waverley.
The trees were once more clothed in their wonted green after the
passing of a northern winter. The woods and fields were enameled in
a thousand colors, and the birds were raising their cheerful voices to
greet the spring of the year 1759. All Nature smiled; only man
seemed sorrowful and cast down; and the laborer no more lifted his
gay song, and the greater portion of the lands lay fallow for lack of
hands to till them. A cloud hung over all New France, for the mother
country, a veritable step-mother, had abandoned her Canadian
children. Left to its own resources, the Government had called to
arms every able-bodied man to defend the colony against the
invasion that menaced it. The English had made vast preparations.
Their fleet, consisting of twenty ships of the line, ten frigates, and
eighteen smaller vessels, accompanied by a number of transports,
and carrying eighteen thousand men, was ascending the St.
Lawrence under the command of General Wolfe; while two land
armies, yet more numerous, were moving to effect a junction under
the very walls of Quebec.
The whole adult population of Canada capable of bearing arms
had responded with ardor to their country's appeal; and there
remained at home none but the old and feeble, the women and the
children. To resist an army more numerous than the entire
population of New France the Canadians had little but the memory
of past exploits, and of their glorious victory at Carillon in the
preceding year. Of what avail their proved courage against an enemy
so overpowering and sworn to their defeat?
You have long been misunderstood, my brethren of old Canada!
Most cruelly have you been slandered. Honor to them who have
lifted your memory from the dust! Honor, a hundred times honor, to
our fellow-countryman, M. Garneau, who has rent the veil that
covered your exploits! Shame to us who, instead of searching the
ancient and glorious annals of our race, were content to bow before
the reproach that we were a conquered people! Shame to us who
were almost ashamed to call ourselves Canadians! Dreading to
confess ourselves ignorant of the history of Assyrians, Medes, and
Persians, that of our own country remained a sealed book to us.
Within the last few years there has come a glorious reaction.
Every one sets his hand to the work and the Canadian can now say
with Francis I, "All is lost save honor." I am far from believing,
however, that all is lost. The cession of Canada was, perhaps, a
blessing in disguise; for the horrors of '93 failed to touch this
fortunate colony which was protected by the flag of Britain. We have
gathered new laurels, fighting beneath the banner of England; and
twice has the colony been saved to England by the courage of her
new subjects. In Parliament, at the bar, upon the field of battle,
everywhere in his small sphere, the French Canadian has proved
himself inferior to none. For a century have you struggled, O my
countrymen, to preserve your nationality, and you behold it yet
intact. The future perhaps holds for you another century of effort

You might also like