Guide To Java A Concise Introduction To Programming Streib James Tsoma download
Guide To Java A Concise Introduction To Programming Streib James Tsoma download
https://ebookbell.com/product/guide-to-java-a-concise-
introduction-to-programming-streib-james-tsoma-21986274
https://ebookbell.com/product/guide-to-java-a-concise-introduction-to-
programming-2nd-edition-2nd-james-t-streib-47712444
https://ebookbell.com/product/guide-to-data-structures-a-concise-
introduction-using-java-1st-edition-james-t-streib-6842356
https://ebookbell.com/product/learn-java-with-projects-a-concise-
practical-guide-to-learning-everything-a-java-professional-really-
needs-to-know-1st-edition-dr-sen-kennedy-54083380
https://ebookbell.com/product/learn-java-with-projects-a-concise-
practical-guide-to-learning-everything-a-java-professional-really-
needs-to-know-1st-edition-anonymous-55322716
A Concise Guide To Technical Communication 2nd Canadian Ed Seijts
https://ebookbell.com/product/a-concise-guide-to-technical-
communication-2nd-canadian-ed-seijts-11961816
https://ebookbell.com/product/the-java-workshop-a-practical-
nononsense-guide-to-java-1st-edition-david-cuartielles-10557360
https://ebookbell.com/product/a-programmers-guide-to-java-scjp-
certification-a-comprehensive-primer-3rd-ed-mughal-22041020
https://ebookbell.com/product/mastering-java-a-comprehensive-guide-to-
development-tools-and-techniques-lena-neill-55886820
https://ebookbell.com/product/chatgpt-for-java-a-handson-developers-
guide-to-chatgpt-and-open-ai-apis-1st-edition-bruce-hopkins-55822518
Undergraduate Topics in Computer Science
James T. Streib
Takako Soma
Guide to Java
A Concise Introduction to Programming
Undergraduate Topics in Computer Science
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 include fully worked solutions.
Guide to Java
A Concise Introduction to Programming
James T. Streib Takako Soma
Department of Computer Science Department of Computer Science
Illinois College Illinois College
Jacksonville, IL, USA Jacksonville, IL, USA
Series Editor
Ian Mackie
Advisory Board
Samson Abramsky, University of Oxford, Oxford, UK
Karin Breitman, Pontifical Catholic University of Rio de Janeiro, Rio de Janeiro, Brazil
Chris Hankin, Imperial College London, London, UK
Dexter Kozen, Cornell University, Ithaca, USA
Andrew Pitts, University of Cambridge, Cambridge, UK
Hanne Riis Nielson, Technical University of Denmark, Kongens Lyngby, Denmark
Steven Skiena, Stony Brook University, Stony Brook, USA
Iain Stewart, University of Durham, Durham, UK
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.
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.
v
vi Preface
This text provides many examples and illustrations. It further has an early introduc-
tion to object-oriented programming and uses contour diagrams to illustrate various
object-oriented concepts. The contour model was originally developed by John
B. Johnson [1]. The model was elaborated on by Organick, Forsythe, and Plummer
to illustrate subprograms, parameter passing, and recursion in procedural and
functional languages [2]. 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 [3]. As discussed in that paper, it was shown that the use of
contour diagrams can be an effective tool in 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 paragraphs of the text, questions are asked of the reader to help them
interact with the material and think about the subject matter just presented. Hope-
fully the reader will take a few moments to try to answer these questions on their
own before proceeding to the answer that immediately 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 these features is 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
This text first 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. The appendices include infor-
mation on graphical input/output, exception processing, Javadoc, a glossary, and
Preface vii
answers to selected exercises. Lastly there are references and useful websites and an
index. The following provides a brief synopsis of the chapters and appendices:
• 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.
• Appendix A gives an introduction to 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.
Scope
Audience
This text is intended primarily for readers who have not had any previous program-
ming 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.
viii Preface
Acknowledgments
The authors would like to thank the reviewers Mark E. Bollman of Albion College,
James W. Chaffee of the University of Iowa, Naomi E. Hahn of Illinois College,
Carroll W. Morrow of Augustana College, and Curt M. White of DePaul Univer-
sity. Also, the authors would like to acknowledge the students of Illinois College
who have read and used various sections of the text in the classroom. On a personal
note, James Streib would like to acknowledge his father William J. Streib for their
numerous conversations, and thank his wife Kimberly A. Streib and son Daniel
M. Streib for their continued patience. 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.
Website: http://www.jtstreib.com/GuideJavaProgramming.html
ix
x Contents
3 Selection Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
3.2 If-Then Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
3.3 If-Then-Else Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
3.4 Nested If Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
3.4.1 If-Then-Else-If Structure . . . . . . . . . . . . . . . . . . . . . . . . 78
3.4.2 If-Then-If Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
3.4.3 Dangling Else Problem . . . . . . . . . . . . . . . . . . . . . . . . . 82
3.5 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
3.6 Case Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
3.7 Complete Programs: Implementing Selection Structures . . . . . . . 98
3.7.1 Simple Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
3.7.2 Program with Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 101
3.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
3.9 Exercises (Items Marked with an * Have Solutions
in Appendix E) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
4 Iteration Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
4.2 Pretest Indefinite Loop Structure . . . . . . . . . . . . . . . . . . . . . . . . 108
4.2.1 Count-Controlled Indefinite Iteration Structure . . . . . . . . 109
4.2.2 Sentinel Controlled Loop . . . . . . . . . . . . . . . . . . . . . . . . 116
4.3 Posttest Indefinite Loop Structure . . . . . . . . . . . . . . . . . . . . . . . 120
4.4 Definite Iteration Loop Structure . . . . . . . . . . . . . . . . . . . . . . . . 124
4.5 Nested Iteration Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
4.6 Potential Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
4.7 Complete Programs: Implementing Iteration Structures . . . . . . . 130
4.7.1 Simple Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
4.7.2 Program with Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 133
4.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
4.9 Exercises (Items Marked with an * Have Solutions
in Appendix E) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
5 Objects: Revisited . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
5.1 Sending an Object to a Method . . . . . . . . . . . . . . . . . . . . . . . . . 143
5.2 Returning an Object from a Method . . . . . . . . . . . . . . . . . . . . . 146
5.3 Overloaded Constructors and Methods . . . . . . . . . . . . . . . . . . . 148
5.4 Use of the Reserved Word this . . . . . . . . . . . . . . . . . . . . . . . 153
5.5 Class Constants, Variables, and Methods . . . . . . . . . . . . . . . . . . 157
5.5.1 Local, Instance, and Class Constants . . . . . . . . . . . . . . . 157
5.5.2 Local, Instance, and Class Variables . . . . . . . . . . . . . . . . 162
5.5.3 Class Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
5.6 Complete Programs: Implementing Objects . . . . . . . . . . . . . . . . 167
5.6.1 Program Focusing on Overloaded Methods . . . . . . . . . . . 167
5.6.2 Program Focusing on Class Data Members
and Class Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Contents xi
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
Variables, Input/Output, and Arithmetic
1
1.1 Introduction
As many readers may already know from using applications software such as
word processing, a computer system is composed of two major parts: hardware
and software. 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. 1.1.
In order for computer hardware to perform, it is necessary that it has a 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 computer’s RAM for subsequent execution in the computer’s CPU.
As the program 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 program-
ming 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 [4].
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 converted into machine language by another program
called an assembler (see Fig. 1.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
Input Output
RAM
Storage
languages, so the assembly language of one machine can be different from that
of another machine.
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.
The program needed to convert or translate a high-level language to a low-level
language is either 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 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, compliers 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 inter-
preter 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
1.1 Introduction 3
Compiler Interpreter
2. Then execute all the machine 2. And then execute only the corresponding
instructions machine instructions
high-level language to assembly language, and then let an assembler convert the
assembly language program to machine language as shown in Fig. 1.2. Once the
machine language is created, it is subsequently loaded into the computer’s RAM
and executed by the CPU.
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. 1.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 education 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.
The Java programming language was developed at Sun MicroSystems (which is
now a subsidiary of Oracle Corporation) and was released in 1995. The intent of the
language was for portability on the World Wide Web. It 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), so it is an easier
language to learn. Object-Oriented Programming (OOP) is a programming meth-
odology that makes it more convenient to reuse software as 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. Con-
versely, 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.
4 1 Variables, Input/Output, and Arithmetic
Compiler Interpreter
Java Bytecode Machine
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
and 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. The process of finding and fixing logic errors is
known as debugging. When learning to program, one must be attentive not only to
the syntax of the language but also to the semantics of the language. Both are
stressed in this text, and with time and practice, a beginning programmer can get
better at both.
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 in the future and provide a starting
point to understand the basic layout of a Java program. At first the program in
Fig. 1.5 might look a bit intimidating, but examining and discussing each of the
statements should help one understand it better. Although some of the descriptions
discussed below might be a little advanced and confusing now, it helps to realize
that each of the words in the program has an important purpose and each of them
will be discussed later in detail throughout the text. As one learns more about Java
and starts to fill in the skeleton with other instructions, it will become less
intimidating.
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 used for identifiers (or names) of packages, classes,
variables, or methods. A package is like a folder in which classes can be stored.
A class is a definition of a group of objects that includes data members (places to
store data) and methods (places to put the program logic). 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
is a name of the class that is provided by the programmer. Usually class names
begin with a capital letter. Braces are used to identify blocks of code and data and
require matching opening and closing braces. 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. Typically the
method is indented to improve the readability of the program. The first three words in
the second line are reserved words. The word public is one of the access or
visibility modifiers which will also be discussed further in Chap. 2. The main
method is always defined using public visibility, so that the program can be
executed by the interpreter. The word static means this is a class method, and
the main method is always declared static so that it can be executed without
creating an object of the class as will be discussed further in Chap. 5. The word void
means that main is a non-value-returning method as will be discussed further in
Chap. 2. Next, 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 first. Inside of the parentheses after the name of the method, parameters are
listed along with their types to allow the method to receive values as will be discussed
further in Chap. 2. The main method has a parameter called args which is an array
of type String, and the square brackets indicate args is an array where strings and
arrays will be discussed further in Chaps. 6 and 7, respectively. The definition of
the main method 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 other than 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, 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. The above program should
compile without any syntax errors and run without any execution errors, except
it does not do anything.
Again the above description should give the reader some insight into the
meaning of various words in the skeleton program. As should be noticed, there
were several references to subsequent chapters. What might be helpful to the reader
is to return to this section later after reading the subsequent chapters and see that
the above is more understandable. For now it should be understood that each of
the words has a particular meaning and that the program serves as a skeleton in
which to insert code as will be done in the following sections.
One of the first things that need to be added to the skeleton are memory locations
so that data can be stored, and another name for a memory location is a variable.
Since the contents of the memory location can vary, just as a variable in mathe-
matics, these two terms can be used interchangeably.
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
1.3 Variables and Constants 7
address contents
name contents
contents, which includes the letters that are inside the mailbox, and the other is
the address of the mailbox as shown in Fig. 1.6.
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 the first section of
this chapter. 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.7. 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.
Instead of a three-dimensional representation of a mailbox to represent a mem-
ory 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:
number 0
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.
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. The name of the
variable can be almost anything except for a reserved word, 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 should 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.
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, or 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.
1.3 Variables and Constants 9
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 abbreviations,
and this text will occasionally show some of the more commonly used ones.
Variables of other types can be declared as well, such as a variable of type float
or double. Although numbers of type float take up less space in the computer’s
memory, 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:
average 0.0
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.
10 1 Variables, Input/Output, and Arithmetic
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, 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 use Java’s 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:
number ---
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 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
1.4 Assignment Statements 11
symbol. The assignment symbol is the equal sign. However, when one first starts to
use the equal sign, one must remember that it does not mean that the variable on the
left is “equal to” the value 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:
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.7 on arithmetic statements.
Note that it is possible to combine the previous two statements into one state-
ment 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 value to a variable.
Of course if one’s instructor does 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 indeterminate. The memory locations would look as follows:
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 later 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:
answer number;
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:
Then when the next assignment statement is executed, the int value of 5 would
be copied, converted to a double value of 5.0, and assigned to result as
follows:
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. 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 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. 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 round method is one
of the many methods available in the Math class which is discussed in more detail
in Sect. 1.7 on arithmetic statements.
1.5 Output
Unless a program performs some type of output, it is not particularly useful. Output
can be of many forms including output to a screen, a printer, a disk, or even some
form of movement such as a robot on an assembly line. In this section, only output
to a screen will be considered. Although there are several ways to output data to the
14 1 Variables, Input/Output, and Arithmetic
screen, this section will examine the simplest of them to get started. More advanced
methods of output will be examined in Chap. 10 and Appendix A, and one can jump
to these locations and learn these methods if one is reading this text independently
or at the discretion of one’s instructor. However, this text will use the methods
introduced in this chapter for the sake of simplicity.
One of the more common first programs written when learning a new language
is the infamous “Hello World!” program. The advantage of this program is to make
sure that one is writing a program correctly and using the compiler properly. This
program can be written as shown in Fig. 1.8.
This program looks very similar to the original Skeleton program in Sect. 1.2,
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 console output and the standard output device by default is the monitor.
To perform console 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 is often pronounced as “print line,” even though it
is not 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!".
Of course, the statement is terminated with a semicolon just as the declaration
statements and assignment statements were in Sects. 1.3 and 1.4, respectively.
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 under-
score represents the 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,
1.5 Output 15
since there is no input as of yet, but in this example, it still serves to illustrate where
any subsequent output would appear. However, what would happen should one
leave off the ln portion of the println, as shown below?
System.out.print("Hello World!");
Given the previous description concerning the println above, the output
would be as follows:
Hello World!_
At first glance, this does not appear to be much different than the original sample
output. However, if one looks carefully, note the location of the cursor. It is not on
the second line but rather at the end of the string. The statement outputs the string to
the screen, but with the absence of the ln, the cursor does not move down to the
next line. In fact, if the cursor does not show up on the screen, one could not notice
the difference. Even though it might not be detected on the screen, it is important to
know where the cursor is located, so that subsequent output is correct. For example,
what if one 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. However, what if one accidently
used two separate System.out.print statements instead?
System.out.print("Hello");
System.out.print("World!");
The output would appear as given below:
HelloWorld!_
Note that this output appears similar to using a single System.out.print
statement as shown previously. Why are they similar? After the first System.
out.print output the word Hello, the cursor stayed on the same line and did
not move to the second line. So when the second System.out.print was
executed, the word World! was output on the same line, and since there was no
ln in the second statement, the cursor stayed on the same line. One might also
notice there is no space between the two words. Why did this happen? Since there is
no space at the end of the first string within the double quotes, nor a space at the
beginning of the second string, a space did not appear in the output.
16 1 Variables, Input/Output, and Arithmetic
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 down to the fourth line. What if one wanted to output two blank
lines, would the following code segment work?
System.out.print("Hello");
System.out.println();
System.out.println();
System.out.println("World!");
At first glance, it might appear to work, but look carefully. Notice that the first
statement does not contain a println but rather only a print. The result would
1.5 Output 17
be exactly the same as the previous code segment since the first statement outputs
the word Hello, but does not move the cursor down to the next line on the screen.
The second statement is a System.out.println, and it moves the cursor down
from the first line to the second line of output. The second System.out.
println creates a single blank line.
Unfortunately, this is a mistake that is sometimes made by beginning Java
programmers, where they assume that anytime there is a System.out.
println(); a blank line is produced. The only time a blank line is produced is
when there is not a preceding System.out.print statement. This is yet another
reason why one should tend to avoid using the System.out.print statement
unless under special circumstances, again discussed in the next section and Chap. 3.
The correct code segment to produce two blank lines is given below. Note that
the first statement is a System.out.println:
System.out.println("Hello");
System.out.println();
System.out.println();
System.out.println("World!");
Although the above code segments are useful for outputting strings and format-
ting 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.9.
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.9 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.10. 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.7. However,
18 1 Variables, Input/Output, and Arithmetic
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
_
What happens if one outputs a number of type double using the same format
shown in Fig. 1.10? For example, Fig. 1.11 outputs the contents of the variable num
of type double.
As will be discussed further in Sect. 1.7, 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
1.5 Output 19
%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.11 can
be rewritten as follows in Fig. 1.12.
The floating-point number stored in the variable num will be output with two
digits after the decimal point. Since a space is included before the specifier in
the string after the word is, there will be a space between is and the number as
shown below:
The number is 0.33
Also notice that since the printf method does not move the cursor to the next
line, just like a print method. A System.out.println(); statement needs
to be added at the end of the program in order to have the same effect as the program
in Fig. 1.11.
Some characters cannot be simply included between double quotes for output. In
order to output a double quotation mark, two characters, a backslash and a double
quote, need to be used, \". The following statement
System.out.println("He said \"Hello\".");
will output
He said "Hello".
Similarly, a backslash can be output by placing an extra backslash in front of one
as shown below:
System.out.println("How to output a backslash, \\");
This will produce an output of
How to output backslash, \
20 1 Variables, Input/Output, and Arithmetic
1.6 Input
The ability to declare variables, assign values to them, and output strings and
variables is very important but does not allow for many useful programs. As it stands,
anytime one wants to change the output of a program, one has to edit the program and
recompile it before executing the program. What is needed is a way to input data into
a program. As with output, input can come from a variety of sources such as the
keyboard, mouse, a disk, or even from sensors such as those that might be on a robot
on an assembly line. Although other methods for input can be found in Chap. 10 and
Appendix A, this section will deal with the simplest form of input.
As in the last section, it is best to start with a simple example based on the
previous program in Fig. 1.10 and modified as shown in Fig. 1.13. Although
the description of the first few lines of the following program might be a little
complicated due to the nature of input in Java, the actual statements that perform
the input are less complicated as will be seen shortly.
Notice the addition of the import statement in the first line. The import
statement is added in order to use a predefined method for input. All the predefined
classes and methods in the Java API are organized into packages, and the import
statement identifies those packages that will be used in a program. For example, the
following statement imports the Scanner class of the java.util package:
import java.util.Scanner;
A second option uses an asterisk to indicate that any class inside the package
might be used in the program. Thus, the statement
import java.util.*;
allows any of the classes in the java.util package to be referenced in the
program. The second option is used in the program shown in Fig. 1.13.
Remember when the System.out.println, System.out.print, and
System.out.printf statements were used in the previous section for output,
the java.lang package which includes the System class was not imported at
the beginning of the program. This is because the java.lang package, which
includes the System and Math classes, is used extensively, and it is automatically
imported into all Java programs.
Returning back to Fig. 1.13, in order for input to work properly, one needs a
place to store the data entered. The first statement in the body of the main method
declares the variable num as type int. The next statement is the declaration of the
variable scanner of type Scanner as shown below:
Scanner scanner;
Scanner is not a primitive data type like int or double, but rather it is a
class. As discussed briefly at the beginning of Sect. 1.2 and will be discussed further
in Chap. 2, a class is like the set of blueprints for a building. The following
statement
scanner ¼ new Scanner(System.in);
creates a new instance of the Scanner class, or in other words a Scanner object.
This can be thought of as how an individual building might be constructed from a
set of blueprints. Java uses System.in to refer to the standard input device, which
is the keyboard. Unlike output, input is not directly supported in Java; however,
the Scanner class can be used to create an object to get input from the keyboard.
The above statement then assigns a reference to the new object to the variable
scanner. Again, although this might be a little confusing at this point, the
important thing is be sure to include the import statement and the above two
statements in any program that needs to input data.
The next statement below shows how the Scanner object is used to scan the
input for the next integer. The method nextInt will make the system wait until an
integer is entered from the keyboard, and then the integer input is assigned to the
variable num:
num ¼ scanner.nextInt();
The last statement in the program is the same as before where the value of num is
output to the computer screen. However, if one were to enter, compile, and run this
program as given, the result might be a little confusing. The reason is that there
would only be a blinking cursor on the screen as the system is waiting for input and
there would be no indication of what should be input without having to look at the
program. To solve this problem, it is usually best to provide a prompt to let the user
know what should be input. A prompt is just an output of a message to the user to
help them understand what is expected to be input. The program in Fig. 1.14
includes a prompt just prior to the input.
As can be seen, the prompt is nothing more than the output of a string to indicate
what the program is expecting in terms of input. Notice that a System.out.
print(); is used to cause the input to stay on the same line. Further, a prompt
should be formatted well. Note that there is a space after the colon so that the cursor
is separated from the prompt. After entering the data and when the user presses the
enter key, the cursor then moves to the next line.
22 1 Variables, Input/Output, and Arithmetic
The ability to input data, copy data from one memory location to another, and
output data is fundamental to almost every computer program. However, unless
there is the capability to manipulate and process data to convert it into information
that can be output and used, the power of the computer has hardly been tapped. One
of the first things computers were used for and continue to be used for is arithmetic
computation, which is the subject of this section.
The four basic operations of arithmetic, addition, subtraction, multiplication, and
division can be accomplished in Java by the use of the binary operators +, -, *,
and /, respectively. The word binary in this case does not mean the binary number
1.7 Arithmetic Statements 23
system, but rather that these operators have two operands (such as variables and
constants) that are manipulated by the operators. As before, the best way to
illustrate this is through an example. Consider the following code segment:
int num1, num2, sum;
num1 ¼ 5;
num2 ¼ 7;
sum ¼ num1 + num2;
After the variables of num1 and num2 have been assigned the values 5 and 7,
respectively, the contents of the memory locations would appear as follows:
What occurs next is that the expression on the right side of the last assignment
statement is evaluated. The contents of num1 are brought into the CPU, and then
the contents of num2 are added to it in the CPU. Once the expression on the right
side of the assignment symbol has been evaluated, the result of the expression in the
CPU is then copied into the variable to the left of the assignment symbol. As in
Sect. 1.4, the copying goes from right to left, so the expression is always on the right
side of the equal sign and there can only be one variable on the left side. The results
of this evaluation and assignment can be seen below:
Of course the values for num1 and num2 in the above segment could have been
input from the keyboard, and the result in sum could be output to the screen, but for
now simple assignment statements are used to initialize num1 and num2, and the
value of sum is not output to keep the segment simple. The examples following will
use this same pattern; however, a complete program using input and output will be
shown in Sect. 1.10.
Similar equations can be made using subtraction, multiplication, and division,
and examples incorporating these operators will follow later in this section. Still, a
few comments need to be made about mixing variables of different types. As shown
above, when two variables of the same type are used, the result is of that type.
However, should one or both of these operands be of type double, then the result
will also be of type double. For example, if num1 is of type int and num2 is
of type double, then the result of the expression would be of type double.
Of course, if the result of the expression is of type double, then it could not be
assigned to the variable sum of type int. Either the round method would need to
be used or the type of sum would need to be changed to double.
There is also a unique aspect to the division operation depending on the types of
its operands. As with the other operators, if either or both of the operands are of type
double, then the result of the division is also of type double. So, for example,
7.0 divided by 2 would be 3.5. If both operands are of type int, the result will of
course be of type int. Although this does not pose a problem with the other
24 1 Variables, Input/Output, and Arithmetic
arithmetic operators, the result of division when performing arithmetic often has a
fractional component, and one would write it as 3½, 3.5, or possibly 3 with a
remainder of 1. However, if the result of the division operation in Java is of type
int, the fractional part is discarded and the result is simply 3. Although one does
not get the fractional part with integer division, what if one wanted to determine
the remainder? That can be done with the mod operator which is represented by
the percent sign, %. To illustrate, consider the following code segment, where all
variables are of type int:
int num1, num2, quotient, remainder;
num1 ¼ 7;
num2 ¼ 2;
quotient ¼ num1 / num2;
remainder ¼ num1 % num2;
Upon completion of the segment, the respective memory locations would con-
tain the following:
num1 7 quotient 3
num2 2 remainder 1
Although it is relatively easy to create some simple instructions that contain only
one operator, what about expressions with more than one operator? In that case, an
awareness of the precedence of the various operators is needed. The precedence in
Java is the same as in mathematics, on a calculator, or in a spreadsheet application
program. First, the multiplication and division operators have precedence over
addition and subtraction. For example, given the following code segment, what
are the contents in answer?
int answer, x, y, z;
x ¼ 2;
y ¼ 3;
z ¼ 4;
answer ¼ x + y * z;
Unfortunately if one guessed 20, that would be wrong. Remember that multi-
plication has precedence over addition so the result of the multiplication of y and z,
which contain 3 and 4, would be 12, plus the contents of x, which is 2,
would be 14.
However, what if one wanted to perform the addition first? As in arithmetic,
one can always use parentheses to override the precedence of the operators, so that
answer ¼ (x + y) * z;
would result in answer containing a 20. If there are more than one set
of parentheses, then the innermost nested ones are evaluated first, and if the
1.7 Arithmetic Statements 25
parentheses are not nested, the parentheses are evaluated from left to right. In fact,
if there is a tie of any sort, such as two addition symbols, or an addition symbol and
a subtraction symbol, the order is also from left to right.
Given all this information, what would be the answers in the following segment?
int answer1, answer2, x, y, z;
x ¼ 3;
y ¼ 4;
z ¼ 5;
answer1 ¼ x - y + 6 / z;
answer2 ¼ (x * (y + 2)) % 2 – 1;
First, note that there are some constants in the mathematical expressions on the
right side of the assignment statement and this is perfectly acceptable. In the first
expression, the 6 / z is evaluated first and the result would be 1. After that, which
operation is performed second? Since there is a tie in the precedence between the
subtraction and the addition, and the subtraction is on the left, it is performed first,
where 3 minus 4 is -1. Lastly, the 1 from the division is added to the -1 from the
subtraction, so the answer is 0.
In the second expression, which operation is performed first? Since there
are nested parentheses, the y + 2 is performed first with an answer of 6. Then
the 3 in x is multiplied by the 6 for a value of 18. Then the 18 is divided by 2,
where the remainder is 0, and lastly the 1 is subtracted from the 0 for a final answer
of -1.
When trying to evaluate expressions, it is sometimes helpful to draw a line
underneath each of the sub-expressions to help one remember which parts of the
expression have been evaluated and remember their respective values. For example,
in the first expression above, it would appear as follows:
x - y + 6 / z
-1 1
Since parentheses override the order of precedence, why can’t one just use
parentheses all of the time and avoid having to remember the order of precedence?
One could do that, but the resulting expressions would have an inordinate number
of parentheses and they could be quite difficult to read. Further, since the prece-
dence rules in most languages are fairly similar and most programmers use
parentheses sparingly, it is to one’s advantage to learn and use them correctly.
For further practice, see the exercises at the end of this chapter.
Just as there are binary operators that have two operands, there also exist unary
operators that have only one operand. The two most common are the plus sign
26 1 Variables, Input/Output, and Arithmetic
and the minus sign, where the latter is used more frequently as in the following
example:
z ¼ -x + y;
The thing to remember about unary operators is that they have a higher priority
than binary operators. So in the above statement, the negative of the value contained
in x is added with the value in y and the result placed in the variable z. Should one
want to negate the entire quantity, then parentheses would need to be used as in the
following example, where the values in x and y are added together first, then
negated, and the result placed in z.
z ¼ -(x + y);
There are of course other arithmetic expressions to be learned, including how the
contents of a variable can be incremented or decremented by 1 or more. There are a
couple of ways to do this, and the method that is applicable in most programming
languages will be examined first. One way is to first get the contents of a variable,
add or subtract 1, and then copy the new number back to the variable as follows:
int x, y;
x ¼ 0;
y ¼ 0;
x ¼ x + 1;
y ¼ y - 1;
At first the fourth and fifth statements above might appear unusual to the
beginning programmer. The fourth statement seems to be saying that x is equal
to x + 1, which would be impossible in algebra. How could a value in x be equal to
itself plus 1? The answer is that it cannot. The reason why this might look unusual
is that one might be mistaking the equal sign in Java as an equal sign in algebra,
which it is not. If one recalls from Sect. 1.4, the equal sign in Java is the assignment
symbol which takes a copy of the result on the right side and places it in the variable
on the left.
In this case, the value in x, which is a 0 as shown above, plus a 1 is 1, and that is the
value placed into x. So prior to execution of the fourth statement, the value in x is a 0,
and after the execution of the fourth statement, the value in x is a 1. The same sort of
process occurs with the statement using subtraction where the final value in y would
be a -1. Also note that since both variables appear on the right side of the assignment
symbol, they must be initialized to some value and should not be indeterminate.
At first these statements might be a little confusing, but with time they become second
nature. Statements like these are often used to increment and decrement variables that
are used as counters and will be discussed in detail in Chap. 4.
Since these operations are fairly commonplace, the languages C, C++, and Java
have shortcuts for these as follows:
þþ x; or xþþ;
!! y; or y !!;
1.7 Arithmetic Statements 27
These operators are very convenient. The operators on the left side work
the same way as those on the right when they are used as standalone statements.
The style on the right is seen more often and will be used again extensively in
Chap. 4. However, when used as part of a larger expression, the two styles have
entirely different meanings. For example, consider the following two statements:
a ¼ þþ x; b ¼ y þþ;
x 2 y 2
a --- b ---
At first it might seem that all four variables would contain a 3, but that would be
incorrect. When the ++ ( or !! ) appears prior to a variable, the increment is
performed before the assignment or any other operation that might be in the
expression. On the other hand, if the ++ (or again !! ) appears after the variable,
then any other operations are performed first, including the assignment operation.
The result is that in the example on the left, the value of x is incremented by 1,
which makes x contain a 3, and then the new value of x would be assigned to a,
which would then also contain a 3. In the example on the right, the value in the
variable y, which is a 2, is first assigned to b. Then the value in y would be
incremented to 3 and the value in b would still be a 2 as shown below:
x 3 y 3
a 3 b 2
find a total, one variable is added to another variable. For example, consider the
following segment:
int total, num;
total ¼ 0;
num ¼ 5;
total ¼ total + num;
where the initial contents of the respective memory locations would appear as
follows:
num 5 total 0
num 5 total 5
Just as with the increment operation, the ability to find a total also has a shortcut.
This shortcut is as follows and has the same effect as the instruction above.
total +¼ num;
Similar shortcuts can also be used with the subtraction, multiplication, and
division operators, but they are used less frequently than addition. As with the
previous shortcuts, this is only possible in languages like C, C++, and Java and does
not appear in all languages. Likewise, since they do not appear in all languages and
do not illustrate as readily how values can be totaled, this text will tend not to use
these shortcuts as often.
Although all the basic arithmetic operation are available in the Java program-
ming language, there are a number of other functions that would be helpful to have
available. In addition to the constants PI and E for pi and e, respectively, many
extra functions are in the Math class. Including the round method previously
introduced in Sect. 1.4, some of the other methods include square root, the power
function, and the trigonometric functions. These methods along with some others
are shown in Table 1.2. To illustrate a few of these functions, examine the program
segment in Fig. 1.15.
The methods should be fairly straightforward given their descriptive names and
the reader’s requisite mathematical background. After execution of the segment,
the answers stored in the variables power, sqRoot, sine, and cosine would
1.8 Comments 29
be 8.0, 2.0, 0.0, and -1.0, respectively. Note that the value in z is in terms of
PI, because the trigonometric functions work with radians instead of degrees. If the
initial value in z was in degrees, the method toRadians could be used.
1.8 Comments
Although comments were discussed briefly in Sect. 1.2, there are few more items
that should be discussed. As mentioned previously, comments are either preceded
by two slashes //, and the remainder of the line is considered a comment by the
compiler, or a comment can begin with a slash and an asterisk /* and end with an
asterisk and a slash */ which allows a comment to extend over multiple lines in a
program. Single-line comments are helpful in explaining an individual line or
multiple lines of code. Although a single-line comment can be placed off to the
right-hand side of the statement it is describing, it can sometimes get crowded once
code is indented as shown in Chaps. 3 and 4. As a result, this text will usually place
comments just prior to a line of code or code segment being documented. For
example, the following comment helps the reader of the program understand what
the subsequent statement accomplishes:
// calculate the area of a rectangle
areaRect ¼ base * height;
Multiple-line comments are also helpful to create what are called headings at the
beginning of programs and methods in class definitions. The format of these headings
30 1 Variables, Input/Output, and Arithmetic
can vary in different computer courses and companies, so be sure to determine your
local requirements. An example of one such heading might be as follows:
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. Initially this method
appears to work fairly well when programs are small at the beginning of a text and
in a class. As mentioned previously, many beginning programmers focus primarily
on the syntax of their program, and they want to avoid getting syntax errors.
However, as problems get more complex, they become more difficult to solve,
1.9 Program Design 31
and 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
carpenters. The same holds true in the world of programming which involves
customers, users, and managers.
What are needed are various strategies and tools to help write programs
correctly. 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 the
next chapter and used in larger programs.
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
The analysis stage is where the needs of the user or customer are first deter-
mined. 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 senior capstone course.
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 UML diagrams
(discussed in the next chapter) and pseudocode (discussed later in this section) are
32 1 Variables, Input/Output, and Arithmetic
used by analysts, software engineers, and programmers to help design the program.
Again it is much easier to make changes during the design phase than once the
programming has begun.
The implementation stage is where the code is actually written, compiled, and
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, then 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 each of the stages above is not a step
that needs to be rigorously adhered to, but rather one stage may need to return to a
previous stage for clarification or to fix a possible error.
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 debugging
logic errors later.
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 mainte-
nance 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.
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
really not a programming language, this is the reason for its name as “pseudo” code.
The advantage of 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 regard-
less of the programming language that they use, and they should be able to convert
1.10 Complete Program: Implementing a Simple Program 33
the pseudocode into their particular programming language. However, there can be
many different versions and levels of detail that can be included in pseudocode, so it
is best to check with one’s instructor or company if there are any preferences or
standards that are employed. 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. As a simple example, consider the following pseudocode on
the left and the Java statement on the right:
Note first that an arrow is used instead of an equal sign 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 mathe-
matical 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 is more generic and helps in the translation to other
languages and not just the Java programming language. Again, this is just one sample
of pseudocode, so be sure to check your local guidelines and requirements.
Even when all attempts to write a logically correct program are followed, the
possibility of logic errors still exists. When this occurs, 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 IDEs 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.
Combining all the material from Chap. 1, one can now write a simple program to
prompt for and input various numbers, perform a wide variety of calculations, and
output answers as needed. In this section, a program that calculates two roots of a
quadratic equation ax2 + bx + c ¼ 0 will be developed and implemented. As might
be recalled from mathematics, the following is the definition of the two roots:
pffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffi
!b þ b2 ! 4ac
r1 ¼
2a
34 1 Variables, Input/Output, and Arithmetic
and
pffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffi
!b ! b2 ! 4ac
r2 ¼
2a
Problem statement: Write a program to calculate the two roots of a quadratic
equation. Assume that a 6¼ 0 and the relationship b2 % 4ac holds, so there will be
real number solutions for x.
Once a problem statement has been given, the requirements can be determined
by analyzing the problem. The program will:
• Prompt a user to enter values for a, b, and c
• Compute the two roots
• Display the two roots
During the design stage, pseudocode can be used to outline the program. At this
point, one does not need to be concerned with the details of the implementation,
such as the name of the class or the parameters in the main method. It lists the steps
that need to be taken to accomplish the task. The following is the pseudocode for a
program calculating two roots of a quadratic equation:
declare a, b, c, root1, root2
input (a)
input (b)
input (c)
" pffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffi#
root1 !b þ b2 ! 4ac =ð2aÞ
" pffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffi#
root2 !b ! b2 ! 4ac =ð2aÞ
Observe in the formulas for the roots that the expression in the square root is called
the discriminant and is used in calculating both roots. Therefore, the square root of
discriminant can be calculated prior to the computation of root1 and root2, so
that it does not need to be calculated twice. The augmented pseudocode is
declare a, b, c, root1, root2, sqrtDiscr
input (a)
input (b)
input (c)
pffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffi
sqrtDiscr b2 ! 4ac
root1 (-b + sqrtDiscr)/(2a)
root2 (-b ! sqrtDiscr)/(2a)
After the design phase comes the implementation phase. Consider the following
program that is derived from the pseudocode above:
Observe the formula for the discriminant for root1 and root2. The methods
sqrt and pow are defined in the Math class and are used to calculate the square
root of the discriminant and the number b raised to the power of 2. All the
parentheses are necessary to obtain the answer, which is accurate to at least two
decimal places. In the output section of the program, println is called at the
beginning in order to have a blank line between the input and output. The specifiers
for root1 and root2 do not include the width to avoid any extra space before the
roots are output since an extra space is included in the string. Given the above
program, sample input and output are shown below:
Enter a: 2.0
Enter b: -5.0
Enter c: -3.0
1.11 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 lan-
guage 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.
• System.out.print leaves the cursor on the same line, whereas System.
out.println moves the cursor to the next line.
• Just because there are no arguments in a System.out.println, it does not
mean a blank line is output. A blank line is output with a System.out.
println when there are no preceding System.out.print statements.
• Remember that multiplication and division have a higher precedence than
addition and subtraction and that unary operators have an even higher
precedence.
• Parentheses can override any operator precedence, where the innermost nested
parentheses have the highest precedence. It is also good practice not to use
unnecessary parentheses.
• Whenever there is a tie at any level of precedence, the operators or parentheses
are evaluated from left to right.
• The ++ or !! operators are an easy shortcut when used as standalone
statements. However, great care must be taken when they are used in assignment
statements or with other operators. In that case, if the ++ or !! precede a
variable, it is performed first, but if they appear after the operand, they are
performed last.
Title: Punch, or the London Charivari, Vol. 108, May 25, 1895
Author: Various
Editor: F. C. Burnand
Language: English
Uncle Toby and the Widow Wadman, as they might have been.
["Uncle Toby and Widow Wadman." C. R. Leslie, R.A. Exhibited at the Royal
Academy in 1831.]
Hercules (Prince Bismarck). "I believe that Female sympathy with our Political
Institutions is a much stronger Bulwark against Social Democracy than our Revolution
Bill would have been if it had been passed." (See Daily Papers.)
New Assistant (after hair-cutting, to Jones, who has been away for a couple of
weeks). "Your 'Air is very thin be'ind, Sir. Try Singeing!"
Jones. "Please."
Manager (who has just sighted his man, in Stage whisper). "You Idiot! He's a
Subscriber!!"
WAITING FOR NASRULLA.
["The original arrangements for Nasrulla Khan's reception in London have
undergone considerable alteration."—Daily Paper.]
"Of course we ought to act on precedent." said Wise Man Number One. "We
can't be far out if we do that."
"I am not so sure," replied Number Two of the Series. "When the Shah came
over we gave him a prize-fight at Buckingham Palace, and the entertainment
subsequently caused much hostile criticism in Clapham."
"No doubt," put in the initial speaker; "but something of the same effect
might be obtained by conducting Nasrulla either to the Museum of Mines in
Jermyn Street or the Diploma Gallery at Burlington House."
"Quite so. And what do you say to the Natural History Museum, and a special
visit in semi-state to the top of the Monument?"
This suggestion was well received. Then a trip to Kew, and a ride on the
Elephant at the Zoo were considered not unfavourably.
Then a Wise Man (less sage than the majority of his fellows) proposed a little
"slumming."
"He might visit the East End, and pass a night in a Casual Ward."
Fortunately for the honour of the British Empire the proposal was negatived
without the formality of a division.
Again there was a shout of "No." The visit of the Representative of the Ameer
was not to be made a source of income to the Imperial, or, if it came to that,
any other Exchequer.
"Besides," said the initial speaker, "the British Public does not care for paying
for its raree-show. When we do get hold of a native, we like to find him on
view free, gratis and for nothing."
Then it was agreed that Nasrulla should appear at the Queen's Birthday
Parade, and other "features" were discussed with animation.
"But what the Khan will ultimately do, Sir," murmured an experienced official
at the conclusion of the confab, "only Time can show—with the assistance of
the Government."
The New Coins.—It was announced that the reverse was to have been altered.
On the contrary, it is quite the reverse.
Ye will find the doorsteps freshly scoured, and the door-handle brightly
polished—which ye will make a note of after ye have rung the bell.
They are exactly like those of everybody else, so they are sure to be pleasing
to an art-loving Public.
I know ye; ye will convey a totally false impression of my views, which I shall
have to write to all the leading journals to correct. Ye will force me into the
publicity and self-advertisement from which my sensitive soul shrinks. Ye will
describe the insides of my rooms, for the benefit of the buzzing swarm which
has hitherto shown no overwhelming curiosity concerning the insides of my
works.
"Peace!" Now the light shallop trembled to the stroke of ASPASIA'S sculls, and
the brawny muscles lifted beneath her flannel suiting. Myself so frail, I adore
the pride and prowess of womanhood, that moves through the world
conquering and to conquer. This life of the open air, so free, so expansive,
that despises the thought of
the world, while we sit at home and tattle over the tea-things and marry when
we're asked. And, à propos, how I longed to tell Aspasia that my heart is hers!
But I am a man; it was for her to speak.
At last she pulled herself together with the self-assurance of a woman who
knows that
the weaker sex is at her mercy. "Dear Ariel," she began, and her deep
mulierile notes vibrated through my fluttering chest; "dear Ariel, this halcyon
eve, this ethereal air that breathes the subtle incense of eucalyptus—all, all,
invite me to offer you
There was a gas explosion the other day in Dublin at the house of a
Mr. Atock. The report states that Mr. Atock's injuries were dressed and
he and his family afterwards left for the house of Mr. Atock senior, at
Phibsborough. Phœbus, what a name! As the capital city of the
regions of, shall we say, perverted veracity, nothing could be fitter. In
any case, condolences to Mr. Atock. Is the Blarney stone in
Phibsborough?
LEEDS LEADS!
Or, Welcome News from the North.
AN EMBARRASSING QUESTION.
"I'm going to a Dance, Darling. One has to dress like this for a Dance!"
"Do the Ladies dance in one Room, and the Gentlemen in another, Mummie?"
THE PREMIER'S CRUISE.
Portsmouth, Monday.—Thank heaven! Got rid of politics for a season. Off to
Cowes, as guest of Spencer, on board Enchantress. Admirable institution, an
Admiralty yacht; reconciles one to Naval Estimates, almost. But there!—must
not think of Estimates now. Must try and remember this is a holiday, to get
ozone and sleep—especially sleep.
Scilly Islands, Wednesday.—Blue sea, lovely weather. Delightful to have left all
worries, all politics, far behind, and to—— Boat seen approaching from land.
Man says he has a telegram for me! Oh, hang telegrams! Wish I were well out
at sea. What can it be about? Japan? Siam? Chitral? No. Only to tell me result
of Walworth and West Dorset elections! Hem! Seems I am at sea—politically.
Thoughtless of Asquith to have wired me on the subject. Homer handsomely
beaten. Why didn't he stick to his Iliad? And Reade—deserves the Old Bailey
for being licked by the new one! Question now is—where's our majority? Ask
Spencer. Spencer replies it's "as plain as a marlinspike." Says Walworth lost
because not enough money spent on Navy. Assures me Navy "much more
important than Army; in fact, it's the Predominant Partner." This is too much!
Ask Spencer, as a favour, to maroon me on some desolate isle—say Lundy.
Won't do it. Bribe a sailor. Landed at Lizard. Off to town! Next time I want sea
air, shall run down to Clacton on the "Belle."
Muriel (embroidering). It is a marvel to me, Viola, that you can ever have a
discontented moment in a house so Elizabethan as this.
Viola. It is lovely, Muriel; a background for mystery and romance. And I have
no romance. I have everything else; but I have not a romance.
Muriel. Once——
Viola. Ah, when everyone opposed our marriage. I married him for love, and
because he was poor and "unsuitable." How could I know that his uncle would
die and leave him money and a country house? Everything has turned out so
well! It is rather hard to have made "a good match," as they say, without
intending it. Of course, I never reproach him.
Muriel. I am sure you would, dear. You have dropped your handkerchief.
(Muriel picks up handkerchief, book, and paper-knife,
and gives them to Viola.)
Viola. Dear Muriel, it is so nice to have you here. You are so calm, and
soothing, and decorative, and you never take anyone away from anyone else!
Muriel. I think I have been rather unfortunate lately, Viola. No one seems to
like me but middle-aged married men—often, too, with whiskers!
Viola. You mean poor Mr. Averidge? He has been married so long that he has
forgotten all about it. To-night Claude Mignon is coming to stay with us. He is
the most accomplished idiot in London. He sings, plays, paints, plays games,
flirts—I think his flirting, though, has rather gone off. It is getting mechanical.
By the way, have you an ideal, Muriel? I wonder what is your ideal?
Muriel (promptly and cheerfully). A man past his first youth, who has suffered;
with iron-grey hair and weary eyes, who knows everything about life and
could guide me, and would do exactly what I told him.
Viola. And mine is a young man of genius, just beginning life, with the world
before him, who would look up to me as an inspiration—a guiding star!
Muriel. You have dropped your handkerchief again, Viola. Who is this coming
out?
Viola. It is only Dr. Roberts. He has been to see Jane, the housemaid. She has
been rather ill.
Viola. You are quite wrong. She had writer's cramp, poor thing!
Dr. Roberts. Oh yes; she is quite out of the wood now, Mrs. Travers. In fact, I
don't think I need see her anymore. (Muriel looks up.) Perhaps though, I had
better just look in—say—on Thursday?
Muriel (watching him drive away). Dr. Roberts admires you dreadfully. Is that a
romance?
Viola. Oh, how delightful! Alan Roy, the wonderful boy harpist, is coming
down! He's coming by the early train! He'll be here directly!
Muriel. You never told me you had asked him! I suppose you forgot it—or
remembered it. Doesn't he profess to be even younger than he is? I mean,
when he was four, didn't he say he was three? I wonder if he'll come down in
a sailor-suit.
Viola. He's quite nineteen. Here are those tiresome Averidges again! I thought
I got rid of them for a long drive. (Aloud.) Ah! Here is dear Mr. Averidge!
Mr. Averidge (ponderously, to Muriel). And how is Miss Vane to-day? Looking
as she always does, like a rose in June.
Viola (to Mrs. Averidge and Albert, who are coming up the steps of the
terrace). Alan Roy is coming down, the Alan Roy. He will be here directly.
Albert. All right, though I don't approve of child artists. Poor little chap!
Viola. He is very nearly quite grown up, Albert! He has golden hair and any
amount of usage du monde.
Albert. I hope he'll bring his halo in a hat-box. What is that text about "Young
lions do lack——"
Alan (smiling). It was dreadful of me! But I have been keeping the poor thing
up so late; I thought a rest——
[Lunch is announced. Muriel stoops to collect Viola's
handkerchief, &c.
(To be continued.)
CYNIC TO POET.
[The great lack of the Age is its want of distinction."
Coventry Patmore.]
O. A. (keen for local tradition). "You don't know exactly how old, I
suppose?"
"Well, noa, Sir; but Old it be! Whoi, I'se knowed it meself these noine
Years!"
ODE TO AN OVERCOAT.
(By a Shivery Person, in Spring-time.)
TO A COUNTRY HOST.
(A Candid Answer to a Hospitable Invitation.)
ebookbell.com