100% found this document useful (1 vote)
16 views

Guide To Java A Concise Introduction To Programming Streib James Tsoma download

The document is a guide to learning Java programming, focusing on the fundamentals and providing numerous examples and illustrations. It aims to bridge the gap between comprehensive texts and shorter introductions, making it accessible for beginners without prior programming experience. The text includes exercises, chapter summaries, and a glossary to reinforce learning and facilitate self-study.

Uploaded by

tuyetarkin5k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
16 views

Guide To Java A Concise Introduction To Programming Streib James Tsoma download

The document is a guide to learning Java programming, focusing on the fundamentals and providing numerous examples and illustrations. It aims to bridge the gap between comprehensive texts and shorter introductions, making it accessible for beginners without prior programming experience. The text includes exercises, chapter summaries, and a glossary to reinforce learning and facilitate self-study.

Uploaded by

tuyetarkin5k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

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

Explore and download more ebooks at ebookbell.com


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

Guide To Java A Concise Introduction To Programming 2nd Edition 2nd


James T Streib

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

Guide To Data Structures A Concise Introduction Using Java 1st Edition


James T Streib

https://ebookbell.com/product/guide-to-data-structures-a-concise-
introduction-using-java-1st-edition-james-t-streib-6842356

Learn Java With Projects A Concise Practical Guide To Learning


Everything A Java Professional Really Needs To Know 1st Edition Dr Sen
Kennedy

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

Learn Java With Projects A Concise Practical Guide To Learning


Everything A Java Professional Really Needs To Know 1st Edition
Anonymous

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

The Java Workshop A Practical Nononsense Guide To Java 1st Edition


David Cuartielles

https://ebookbell.com/product/the-java-workshop-a-practical-
nononsense-guide-to-java-1st-edition-david-cuartielles-10557360

A Programmers Guide To Java Scjp Certification A Comprehensive Primer


3rd Ed Mughal

https://ebookbell.com/product/a-programmers-guide-to-java-scjp-
certification-a-comprehensive-primer-3rd-ed-mughal-22041020

Mastering Java A Comprehensive Guide To Development Tools And


Techniques Lena Neill

https://ebookbell.com/product/mastering-java-a-comprehensive-guide-to-
development-tools-and-techniques-lena-neill-55886820

Chatgpt For Java A Handson Developers Guide To Chatgpt And Open Ai


Apis 1st Edition Bruce Hopkins

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.

For further volumes:


http://www.springer.com/series/7592
James T. Streib • Takako Soma

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

ISSN 1863-7310 ISSN 2197-1781 (electronic)


Undergraduate Topics in Computer Science
ISBN 978-1-4471-6316-9 ISBN 978-1-4471-6317-6 (eBook)
DOI 10.1007/978-1-4471-6317-6
Springer London Heidelberg New York Dordrecht
Library of Congress Control Number: 2014931850

© Springer-Verlag London 2014


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of
the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations,
recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or
information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar
methodology now known or hereafter developed. Exempted from this legal reservation are brief excerpts
in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being
entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication
of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the
Publisher’s location, in its current version, and permission for use must always be obtained from
Springer. Permissions for use may be obtained through RightsLink at the Copyright Clearance Center.
Violations are liable to prosecution under the respective Copyright Law.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this
publication does not imply, even in the absence of a specific statement, that such names are exempt
from the relevant protective laws and regulations and therefore free for general use.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for
any errors or omissions that may be made. The publisher makes no warranty, express or implied, with
respect to the material contained herein.

Printed on acid-free paper

Springer is part of Springer Science+Business Media (www.springer.com)


Preface

Purpose

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

Comparison to Other Texts

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

Need

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

v
vi Preface

Features of This Text

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

Overview of the Chapters

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

As mentioned previously, this text concentrates on the fundamentals of the Java


programming language such as input/output, object-oriented programming, arith-
metic and logic instructions, control structures, strings, arrays including elementary
sorting and searching, recursion, and files. As a result, it might not cover all the
details that are found in some other texts, and if necessary, these topics can be
supplemented by the instructor or reader, or covered in a subsequent text and/or
second semester course.

Audience

This text is intended primarily for readers who have not had any previous 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

Illinois College James T. Streib


Jacksonville, IL, USA james.streib@jtstreib.com
October 21, 2013 Takako Soma
tsoma@mail.ic.edu
Contents

1 Variables, Input/Output, and Arithmetic . . . . . . . . . . . . . . . . . . . . 1


1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Java Skeleton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.3 Variables and Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 Assignment Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.5 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.6 Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.7 Arithmetic Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.8 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.9 Program Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
1.10 Complete Program: Implementing a Simple Program . . . . . . . . 33
1.11 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
1.12 Exercises (Items Marked with an * Have Solutions
in Appendix E) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2 Objects: An Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.2 Classes and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
2.3 Public and Private Data Members . . . . . . . . . . . . . . . . . . . . . . 41
2.4 Value-Returning Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
2.5 Void Methods and Parameters . . . . . . . . . . . . . . . . . . . . . . . . . 42
2.6 Creating Objects and Invoking Methods . . . . . . . . . . . . . . . . . 44
2.7 Contour Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
2.8 Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
2.9 Multiple Objects and Classes . . . . . . . . . . . . . . . . . . . . . . . . . 53
2.10 Universal Modeling Language (UML) Class Diagrams . . . . . . . 60
2.11 Complete Program: Implementing a Simple Class
and Client Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
2.12 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
2.13 Exercises (Items Marked with an * Have Solutions
in Appendix E) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

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

5.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179


5.8 Exercises (Items Marked with an * Have Solutions
in Appendix E) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
6 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
6.2 String Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
6.3 String Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
6.4 Methods in String Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
6.4.1 The length Method . . . . . . . . . . . . . . . . . . . . . . . . . . 188
6.4.2 The indexOf Method . . . . . . . . . . . . . . . . . . . . . . . . . 188
6.4.3 The substring Method . . . . . . . . . . . . . . . . . . . . . . . 189
6.4.4 Comparison of Two String Objects . . . . . . . . . . . . . . 191
6.4.5 The equalsIgnoreCase Method . . . . . . . . . . . . . . . 194
6.4.6 The charAt Method . . . . . . . . . . . . . . . . . . . . . . . . . . 195
6.5 The toString Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
6.6 Complete Program: Implementing String Objects . . . . . . . . . 198
6.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
6.8 Exercises (Items Marked with an * Have Solutions
in Appendix E) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
7 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
7.2 Array Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
7.3 Array Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
7.4 Input, Output, Simple Processing, and Methods . . . . . . . . . . . . . 206
7.4.1 Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
7.4.2 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
7.4.3 Simple Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
7.4.4 Passing an Array to and from a Method . . . . . . . . . . . . . 212
7.5 Reversing an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
7.6 Searching an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
7.6.1 Sequential Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
7.6.2 Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
7.6.3 Elementary Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
7.7 Sorting an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
7.7.1 Simplified Bubble Sort . . . . . . . . . . . . . . . . . . . . . . . . . 222
7.7.2 Modified Bubble Sort . . . . . . . . . . . . . . . . . . . . . . . . . . 224
7.8 Two-Dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
7.8.1 Declaration, Creation, and Initialization . . . . . . . . . . . . . 226
7.8.2 Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
7.8.3 Processing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
7.8.4 Passing a Two-Dimensional Array to
and from a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
7.8.5 Asymmetrical Two-Dimensional Arrays . . . . . . . . . . . . . 234
7.9 Arrays of Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
xii Contents

7.10 Complete Program: Implementing an Array . . . . . . . . . . . . . . . 238


7.11 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
7.12 Exercises (Items Marked with an * Have Solutions
in Appendix E) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
8 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
8.2 The Power Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
8.3 Stack Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
8.4 Fibonacci Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
8.5 Complete Program: Implementing Recursion . . . . . . . . . . . . . . 264
8.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
8.7 Exercises (Items Marked with an * Have Solutions
in Appendix E) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
9 Objects: Inheritance and Polymorphism . . . . . . . . . . . . . . . . . . . . 267
9.1 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
9.2 Protected Variables and Methods . . . . . . . . . . . . . . . . . . . . . . 276
9.3 Abstract Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
9.4 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
9.5 Complete Program: Implementing Inheritance
and Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
9.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
9.7 Exercises (Items Marked with an * Have Solutions
in Appendix E) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
10 Elementary File Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . 293
10.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
10.2 File Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
10.3 File Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
10.4 File Input and Output Using an Array . . . . . . . . . . . . . . . . . . . 300
10.5 Specifying the File Location . . . . . . . . . . . . . . . . . . . . . . . . . . 303
10.6 Complete Programs: Implementing File Input and Output . . . . . 305
10.6.1 Matrix Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . 305
10.6.2 Sorting Data in a File . . . . . . . . . . . . . . . . . . . . . . . . . 307
10.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
10.8 Exercises (Items Marked with an * Have Solutions
in Appendix E) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309

Appendix A Simple Graphical Input and Output . . . . . . . . . . . . . . . . 311


A.1 Message Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
A.2 Input Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
A.3 Converting String Input from Input Dialog Boxes
to Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
A.4 Confirmation Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
A.5 Option Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
Contents xiii

Appendix B Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321


B.1 Exception Class and Error Class . . . . . . . . . . . . . . . . . . . . . . . . . 321
B.2 Handling an Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
B.3 Throwing Exceptions and Multiple catch Blocks . . . . . . . . . . . 325
B.4 Checked and Unchecked Exceptions . . . . . . . . . . . . . . . . . . . . . . 330

Appendix C Javadoc Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335


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

Appendix D Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341

Appendix E Answers to Selected Exercises . . . . . . . . . . . . . . . . . . . . . 345

References and Useful Websites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353

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

J.T. Streib and T. Soma, Guide to Java: A Concise Introduction to Programming, 1


Undergraduate Topics in Computer Science, DOI 10.1007/978-1-4471-6317-6_1,
© Springer-Verlag London 2014
2 1 Variables, Input/Output, and Arithmetic

Fig. 1.1 Computer hardware


CPU

Input Output

RAM

Storage

Fig. 1.2 Assemblers and


compilers Compiler Assembler

High-Level Assembly Machine


Language Language Language

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

High-Level Machine High-Level Machine

Instruction1 10101010 Instruction1 10101010


01010101 01010101

Instruction2 00110011 Instruction2 00110011


11101110 11101110

Instruction3 00001111 Instruction3 00001111


11110000 11110000

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

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

Fig. 1.3 Compilers and interpreters

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

Instruction1 Bytecode 10101010


Bytecode 01010101

Instruction2 Bytecode 00110011


11101110

Instruction3 Bytecode 00001111


Bytecode 11110000

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


instruction at a time

3. And then execute only the corresponding


machine instructions

Fig. 1.4 Java instructions, bytecode, and machine language

Java is somewhat unique in that it uses both a compiler and an interpreter


to convert the high-level instructions to machine language. A compiler is used to
convert the Java instructions into an intermediate-level language known as
bytecode, and then the bytecode is converted into machine language using an
interpreter. The advantage of using both a compiler and an interpreter is that most
of the translation process can be done by the compiler, and when bytecode is sent to
different types of machines, it can be translated by an interpreter into the machine
language of the particular type of machine the code needs to be run on (see Fig. 1.4).
Note that just as there can be a one-to-many relationship between high-level and
low-level instructions, there can be a one-to-many relationship between Java and
bytecode. However, unlike the one-to-one relationship between assembly language
and machine language, there can be a one-to-many relationship between bytecode
and machine language, depending on the machine for which the bytecode is being
interpreted.
When learning a new programming language, one should distinguish between
the syntax and the semantics of a program. Simply stated, the syntax is the grammar
of the language, and the semantics is the meaning or what each instruction does.
To explain further, syntax is the spelling of the individual words, where the
semicolons go, and so on. If mistakes are made, the compiler will detect what are
known as syntax errors, generate messages to the programmer, and the program
will not be compiled or executed. Although syntax is very important, there is a
tendency for first-time programmers to spend too much time learning syntax to
avoid syntax errors. However, there must be equal time spent on semantics to
ensure that the program does what the programmer intended it to do. Even though
there might not be any syntax errors, there can be what are called execution errors
1.2 Java Skeleton 5

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.

1.2 Java Skeleton

Probably the best way to understand a programming language is to start right away
with a sample program. Although the following program does not do anything,
it will serve as a skeleton to add instructions 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.

Fig. 1.5 Java skeleton


program
6 1 Variables, Input/Output, and Arithmetic

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.

1.3 Variables and Constants

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

Fig. 1.6 Representation of


memory
00000000 00000000

address contents

Fig. 1.7 Using names for


memory locations
number 00000000

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

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


languages (machine and assembly languages), it is important to remember that a
memory location has two features: its address and its contents. In Java, the
programmer is typically concerned about its contents.
Given the above representation of variables, how are they actually created or
declared? When a variable is declared, there are two things that must be done. First,
a variable needs to be given a name so that it can be referred to by various
instructions in the program, and second, the type of data that will be stored in the
8 1 Variables, Input/Output, and Arithmetic

Table 1.1 Data types


Type Size Range
byte 1 byte !128 to 127
short 2 bytes !32,768 to 32,767
int 4 bytes !2,147,483,648 to 2,147,483,647
long 8 bytes !9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 4 bytes !3.40282347 " 1038 to 3.4028347 " 1038
double 8 bytes !1.79769313486231570 " 10308 to 1.79769313486231570 " 10308
char 2 bytes one character
String 2 or more bytes one or more characters

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

Notice that instead of showing the number zero as an integer, it is represented as a


real number with a decimal point, to indicate its type as a double.
All of the types given in Table 1.1, other than the String type, are known as
primitive data types, meaning that when they are declared, the memory needed to
store the associated data is allocated at that time. However, a String data type is a
reference data type. When a variable of type String is declared, the memory
allocated is not used to store the data, but rather only to store a reference to the data.
String data types are unique in that although they are technically objects, they can
be used syntactically as if they were primitive data types.
The first part of this text will use strings in a very limited capacity.
An understanding of strings is much easier once one has had an introduction to
objects and practice with objects, so a full description of how string objects are
created and manipulated is presented in Chap. 6. However, for now, this text will
represent strings “as if” they are primitive data types, and the following shows
a character primitive data type and a simplified view of the string data type.
For example, a character and string could be declared as follows:
char initial; String name;
and would be represented with values as follows, respectively:

initial 'T' name "John"

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 contrast to variables, a constant can be declared so that its value cannot be


changed. Although not nearly as useful as variables, constants have their place in a
program when a value does not need to be changed, nor should it be changed. For
example, if an integer N always needs to remain a 7, then it could be declared as
follows, where the use of the reserved word final indicates that N is a constant:
final int N ¼ 7;
Typically constant names are declared as all capital letters to help other
programmers distinguish them from variables. In another example, suppose a
number like PI needs only two digits after the decimal point, then it could be
declared as follows:
final double PI ¼ 3.14;
Although the use of a constant might not be readily apparent at this time, their
use will become clearer in subsequent examples after discussing assignment
statements in the next section.

1.4 Assignment Statements

In the previous section, all the drawings of the memory locations had values in
them. How did those values get there? By default, Java technically initializes all
int variables to 0 and double variables to 0.0. Also, char variables are
initialized to ", the empty character, 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:

number 5 answer ---


12 1 Variables, Input/Output, and Arithmetic

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:

number 5 result ---

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:

number 5 result 5.0


1.5 Output 13

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

Fig. 1.8 Hello World!

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

Although this is similar to the example using the System.out.print, could


it be changed to mimic the first example in this section? The answer is yes, as in the
following example:
System.out.print("Hello ");
System.out.print("World!");
System.out.println();
In this case, the word Hello followed by a space would be output, and then the
word World! would be output. The last line would output nothing, because there
is no string in the parentheses, but the ln would cause the cursor to move down to
the next line as shown below:
Hello World!
_
Although the above three line code segment produces the same output as the
original single-line statement, why would one want to use this latter example?
Usually one would not and the single line is preferable to using multiple lines.
However, there are instances where one needs to break up an output line into
multiple lines for the sake of convenience as will be illustrated in the next section
on input and in Chap. 3 on selection statements.
As a further example of formatting output, what if one wanted to output the
following with a blank line between the two words and the cursor at the bottom?
Hello

World!
_
The following code segment would accomplish this task:
System.out.println("Hello");
System.out.println();
System.out.println("World!");
The first statement outputs the word Hello and moves the cursor down to the
second line. The second statement does not output anything, so the ln of the
System.out.println statement causes the cursor to move down to the third
line and the blank line to appear on output. Lastly, the word World! is output and
the cursor moves 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

Fig. 1.9 Outputting an int precision number

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

Fig. 1.10 Outputting an int precision number with description of output

Fig. 1.11 Outputting a double precision number without formatting

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

Fig. 1.12 Formatting a double precision number

%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

Fig. 1.13 Program to input an integer


1.6 Input 21

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

Fig. 1.14 Prompting a user to input a number

Furthermore, a prompt should be user friendly. A user-friendly prompt is one


that clearly describes what the user should input, as in the case above where it
asks for an integer. A user-friendly prompt can be polite such as “Please enter a
number: ”, but typically a prompt should avoid the use of first person words like “I”
and “you”, as in “I would like you to. . .”, since the computer is a machine, not
a human.
Now would be a good time to enter, compile, and run the program in Fig. 1.14
to see how it works. The results should be similar to the following:
Enter an integer: 5
The integer is 5
_
In addition to nextInt, the method nextDouble reads a number of type
double, the method next reads a word of type String that ends prior to a
space, and the method nextLine reads an entire line of text of type String,
including all the spaces until the user presses the enter or return key. All of these
methods work similarly to the method nextInt.

1.7 Arithmetic Statements

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:

num1 5 num2 7 sum ---

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:

num1 5 num2 7 sum 12

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 þþ;

If x and y originally contain a 2, their respective memory locations would


initially appear as follows:

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

As mentioned above, as standalone operators, the ++ and !! can be fairly


useful and easy to use, and this text will use them more frequently in Chap. 4.
However, using the more simple initial approach such as x ¼ x + 1; is common in
almost all languages, so this text will tend to use this initially to help reinforce how
an expression like this works. Further, when these operators are used in more
complicated expressions, their use becomes much more difficult to understand,
and it is for this reason that this text will tend to avoid the use of the ++ or !!
operators in this fashion. However, be aware that intermediate and advanced texts
often use these operators more frequently in complicated expressions, so one needs
to know how they work and also be careful when reading code containing them.
As shown at the beginning of this section, when two variables are added
together, the sum is often stored in a third variable. However, similar to counting,
when a constant such as a 1 is added to a variable in the process of trying to
28 1 Variables, Input/Output, and Arithmetic

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

As with previously incrementing by 1, it might look a little odd to see the


variable total on both sides of the equal sign. Again the equal sign does not
mean equality but assignment, where the expression on the right is evaluated first
and the results are then stored in the variable on the left. Also, since the variable
total appears on both sides of the assignment symbol, it needs to be initialized
with a value prior to the statement. After the 0 and 5 are added together, the results
are then placed back into total as follows:

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

Table 1.2 Various methods in the Math class


Method Function performed Arguments Value returned
cos(x) cosine double (in radians) double
pow(x,y) x to the power of y double double
round(x) round float (or double) int (or long)
sin(x) sine double (in radians) double
sqrt(x) square root double double
tan(x) tangent double (in radians) double
toDegrees(x) convert radians to degrees double double
toRadians(x) convert degrees to radians double double

Fig. 1.15 Sample Math


class constants and methods

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:

/* name: your name


class : cs 1xx
prog : one
date : mm/dd/yyyy
*/
Once filled with the corresponding information, this heading identifies the
author of the program, which class it was written for, the program number, and
the date written. As can be seen, comments are good for documenting what various
sections of code do in a program and identify who wrote a program, among other
things. Having comments within a program explaining what a program does
is known as internal documentation, whereas having explanations that appear in
manuals (whether online or in physical manuals) is known as external documen-
tation. Internal documentation tends to be more specific and is helpful to
programmers, whereas external documentation tends to be more general and is
useful to users, customers, and managers who may not understand programming.
Although at first some of the simpler programs will not appear to need
comments, it becomes imperative to include comments as programs become larger
and more complex. If the original programmer is on vacation or is no longer with a
company, documentation is essential to help other programmers understand how
the program works. Although many of the programs written in a first programming
course might not be too complex, it is helpful to include comments to gain practice
in good commenting techniques. To that end, the complete programs at the end of
each chapter will include comments to help the reader understand the program and
learn some commenting techniques.
There is also another way to document a program using Javadoc. This technique is
very useful with larger programs that have many classes and methods, and an
introduction is presented in Appendix C. Again, many computer science departments
and computer science professors have different documentation standards, as do many
different companies. Although they share some commonalities, there can also be a
number of differences. Find out what your professor’s or company standards are and
be sure to follow them closely.

1.9 Program Design

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:

areaRec height x width areaRec = height * width;

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.

1.10 Complete Program: Implementing a Simple 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Þ

output (root1, root2)

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)

output (root1, root2)


1.10 Complete Program: Implementing a Simple Program 35

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

Two roots of the equation, 2.0*x*x + -5.0*x + -3.0 ¼ 0, are


3.00 and -0.50.
36 1 Variables, Input/Output, and Arithmetic

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.

1.12 Exercises (Items Marked with an * Have Solutions


in Appendix E)

1. Indicate whether the following statements are syntactically correct or incorrect.


If incorrect, indicate what is wrong with the statement:
A. integer num1, num2;
*B. double num3;
C. 7.8 ¼ num3; Assume that a variable num3 has been declared correctly.
*D. int j;
j ¼ 5.5;
Exploring the Variety of Random
Documents with Different Content
The Project Gutenberg eBook of Punch, or the
London Charivari, Vol. 108, May 25, 1895
This ebook is for the use of anyone anywhere in the United States and
most other parts of the world at no cost and with almost no restrictions
whatsoever. You may copy it, give it away or re-use it under the terms of
the Project Gutenberg License included with this ebook or online at
www.gutenberg.org. If you are not located in the United States, you will
have to check the laws of the country where you are located before using
this eBook.

Title: Punch, or the London Charivari, Vol. 108, May 25, 1895

Author: Various

Editor: F. C. Burnand

Release date: February 9, 2014 [eBook #44850]


Most recently updated: October 24, 2024

Language: English

Credits: Produced by Malcolm Farmer, Lesley Halamek and the Online


Distributed Proofreading Team at http://www.pgdp.net

*** START OF THE PROJECT GUTENBERG EBOOK PUNCH, OR THE LONDON


CHARIVARI, VOL. 108, MAY 25, 1895 ***
PUNCH, OR THE LONDON
CHARIVARI.
Volume 108, May 25th, 1895.

edited by Sir Francis Burnand

STUDIES IN ANIMAL LIFE.

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.]

A Mark against Denmark.—At the beginning of last week it was midsummer


weather, and not to have cast off winter clothing and donned light attire
would have been deemed "Midsummer madness." But by Thursday "on a
changé tout cela," except the clothes, and we were in midwinter! The Daily
Telegraph's weather-clerk observed, that all "this resulted from a deep
depression in Denmark." It certainly caused deep depression here; and there
must be "something rotten in the State of Denmark" which ought to be looked
to immediately. Ere these lines appear we hope—sincerely hope—that we
shall have retraced our steps towards summer.

Query Suggested.—We read in the Financial Times that "A corner in


camphor is, it is stated, being arranged." Is to be in "a corner in
camphor" as good as being "laid up in lavender"?
A CENTURY OF CENTURIES.
[By scoring 288 in the match Gloucester v. Somerset at
Bristol, on May 17, Mr. W. G. Grace, now nearing his
47th birthday, made his hundredth innings of 100 runs
or over in first-class matches.]

"O frabjous day! Callooh! Callay!"


Sang Punch on the seventeenth instant May,
With a true Jabberwockian chortle,
As he saw the swipe, on the Bristol ground,
Which worked Grace's hundred of centuries round;
A record ne'er equalled by mortal.

"My beamish boy"—of nigh forty-seven—


There isn't a cheerier sight under heaven
Than W. G. at the wicket.
When your "vorpal" bat "goes snicker-snack,"
Punch loves to lie, with a tree at his back,
And watch what he calls Cricket.

And now, as a topper of thirty years,


After many hopes, and a few faint fears.
(Which Punch never shared for a jiffy.)
You've done the trick! Did your pulse beat quick
As you crept notch by notch within reach of the nick?
Did even your heart feel squiffy?

Punch frankly owns his went pit-a-pat


While he followed the ball and watched your bat
As the nineties slowly tottled;
And the boys of the Bristol Brigade held breath,
In an anxious silence as still as death.
But oh! like good fizz unbottled,

We all "let go" with a loud "hooray"


As the leather was safely "put away"
For that hundredth hundred. Verily,
Now you're the "many centuried" Grace!
And for many a year may you keep top place,
Piling three-figure innings right merrily!

Game from the Highlands.—A "Scotch Golfer of Twenty Years' Standing"


(poor man! he certainly ought to be invited to take the chair at any
Golf meeting!) writes to the Liverpool Daily Post complaining that
novices in England will persist in sounding the letter "l" in the title of
the sport, "although on every green from John o' Groats to Airlie it
remains silent in the mouth of player and caddie alike." As the Golfer
"puts" it, the name should be "goff," or even "gowf." As long as there
is plenty of acreage for the game, an "ell" is not worth mentioning.

Musical Note of "Herr Willy Burmester"—or "Our" Willy. "Bless


you!" as the old salt said; "he fiddles like a angel!" Of course,
like all violinists, the hair of his head is peculiar, but his airs on
his violin are marvellous in execution.

University Privilege not generally known.—When a


resident Oxonion is suffering from a bronchial attack he
is entitled to the professional attendance (gratis) of
"The Curators of the Chest."

Extra-ordinary Self-annihilating Cannibals.—Children, when they over-eat


themselves.

THE WAIL OF THE WALWORTH WOTER.


["Many of our men have certainly been got at."—Walworth Liberal Agent.]

"Got at," my boy? Well, that's a fack;


Yet not by Lansbury, Reade, or Bailey.
But by the burdens on our back,
As seem a-gettin' heavier daily.
Trade's bloomin' bad, and rents is high;
Yet more and more the Guv'ment axes.
Progress, old man, is all my heye,—
As means raised rents, and rates, and taxes.
School Boards, Free Liberies, an' such,
With County Council schemes, look proper;
When they too 'ard poor pockets touch
On them the poor must put a stopper.
Fust we 'ave got to live, I say;
To pay our way, and grub our young 'uns.
Will Rads make that more easier, hay,
Than wot you call "Bible and Bung'uns"?
By Jingo, if you want our wotes,
You'll git 'em, not by playing peeper,
Or wetoing beer from our poor throats;
But—making life easier and cheaper!
Got at? Wy, yus, by want o' grub,
And rents an' taxes too extensive;
And so we'll weto—not the Pub,
But "Progress" wot comes too expensive!

Parties in the House of Commons.—Besides the usual number of parties, there


will always be, during the fine summer weather, Tea-parties.

Contradiction.—Tremendous "Crushing Reports" come in from the mines, and,


in spite of this, mining shares are better than ever.
HERCULES AND OMPHALE; OR, PETTICOAT GOVERNMENT.

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 (after a pause). "Yes, I think I will."

N. A. (after singeing). "Shampoo, Sir? Good for the 'Air, Sir."

Jones. "Thank you. Yes."

N. A. "Your Moustaches curled?"

Jones. "Please."

N. A. "May I give you a Friction?"

Jones. "Thank you."

N. A. "Will you try some of our——"

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."

"It is to be regretted," sighed the Third, "that the Polytechnic Institution no


longer exists. It would have amused his Highness to have descended in the
diving bell."

"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.

"Shall he go to any of the theatres?" was the next question.

"It may be a little dangerous to his morals if he understands English," seemed


to be the popular answer.

Then a visit to a music-hall under the immediate supervision of the London


County Council was proposed.

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.

"Could he be exhibited at a side show, either at Sydenham, Earl's Court, or


West Kensington?"

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."

A New Terror.—Politics on the stage. In Enry Hauthor Jones's Bauble


Shop at the Criterion we were taken into the House of Commons and
got somehow mixed up with Party Politics; but in The Home
Secretary, Mr. Carton, it appears, has attempted to drag his
audience, with Mr. Charles Wyndham, into the inner circle of
Parliamentary life. What next? A debate on the Budget in Four Acts?
Or shall we have, in five Parliamentary Acts, with a Prologue and
Epilogue, the Comedy with a short Jonesian title called Home Rule
for Ireland: or, how the O'Reillys, the Maguires, and the Kellys went
into the Opposition Lobby, and how one Government came in and
the other went out, &c. &c.? Save us from politics on the stage!
There was just enough of the political element in Dora to give it a
peculiar interest. But then Dora was written by Victorien Sardou.

Royal Military Tournament.—The initials being "R. M. T." will not


be descriptive of the state of the seats in the Agricultural Hall
during the performance. The announcement will be "Are Quite
Full," not "R. M. T."
Quotation for Londoner last week, on seeing the Duke of York in Pall Mall.—"I
know that man, he comes from Sheffield."

The New Coins.—It was announced that the reverse was to have been altered.
On the contrary, it is quite the reverse.

CLASSIC QUOTATIONS ILLUSTRATED.

(For the Use of Schools.)

Example II.—"Palmam qui meruit ferat."


THE POET AND HIS INTERVIEWERS.
I do not dwell in a back-attic with the windows pasted up with brown paper,
neither do I wallow up to my eyes in a litter of manuscript with flue on the
carpet and dust on all the furniture. If ye, or the Public, have any such
impression, ye are very much mistaken. I may be a literary person and a
prose-poet; but I live quite respectably, and have everything handsome about
me. Come and see!

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.

A trim parlourmaid—whom ye will allude to as "a neat-handed Phyllis"—will


open the door, and request ye to wipe your dirty boots upon the doormat in
the passage—which ye are expected to mention as the "spacious entrance
hall."

I shall stand on the threshold of my dining-room, and receive ye with as much


surprise as if the visit were not by previous appointment; shall accompany ye
through all my rooms, and tell ye interesting facts about the china and the
chimney ornaments. I shall not object to your bringing a camera and taking
views of my "cosy corner" and my hat and umbrella-stand.

They are exactly like those of everybody else, so they are sure to be pleasing
to an art-loving Public.

Ye will find in the drawing-room the perfume of many flowers—provided I do


not forget to send out for some penny bunches of violets beforehand—and ye
can take a photograph of the cottage piano and my pet canary (which usually
has its habitation in the kitchen, as I loathe all birds—but this is not for
publication).

I will show ye the stand of wax-flowers fashioned by my maternal


grandmother—which will give ye an opportunity of commenting upon the
heredity of genius in my talented family—and ye may peer into the silver
épergne that was presented to my Uncle at the Cattle Show for a prize pig. Ye
will probably think it necessary to make a copy of the inscription.
In the study—to which I shall humorously allude as my "den"—there is little of
general interest except my old carpet slippers. Mayhap ye will point to a few
pipes that lie on the mantelpiece; but they are merely "properties," for the
public expects all striking literary personalities to write with pipes in their
mouths.

Come to me! I fear ye not. It is ye who confer celebrity. I know ye so well. I


shall follow ye out into the garden, and ye shall carry stylographs in your
waistcoat pockets, and I will relate to ye my early literary experiences, give ye
my theories on the Social Question, and let ye kodak my child in its
perambulator.

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.

Still, I do not mind your coming, provided that ye give me an opportunity of


revising a proof of the interview. Ye are necessary nuisances.
BETWEEN THE LINES.
["The insertion of advertisements at enhanced prices in the very body of
a magazine is the noblest achievement of journalistic enterprise. This
intrinsically beautiful idea, however, admits of considerable development
in the near future, unless, as is improbable, the reading public declines to
take its romantic literature in piebald strata."—The Type Worm.]

A TWENTIETH CENTURY IDYLL.


Lazily, dreamily, we floated down the pellucid stream,
Aspasia at the single thwart, I, her loved one, at the tiller.
The last gleaner had left the fields. Over the grave of the
dead sun I saw the eye of Hesperus, early and
thoughtful. The words of the Poet Laureate came back to
me; it seemed that "in yonder Orient star a hundred
spirits whispered

[KEEP YOUR HAIR ON! Try our own Fertiliser.


The Next-of-Kin-but-One to the
Hohenpfefferkorn dynasty writes:—"I have
tried your lotion for a vacancy in the crown,
and should in all human probability have succeeded,
but for the birth of an infant in the direct line. Make
what use of this you like. It has been none to me."]

"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

[COHESIVE CORSETS.—Supply the want, or disguise


the existence, of adipose deposit. Send immediately a
plaster cast of your bust. Insure against fracture in the
Parcel Post.]
control or seclusion, how different from that of men, studiously repressed in a
hothouse atmosphere of fashion and traditional proprieties. We only guess of
their world from hearsay or from books. And most of these are by women for
women, and Papa says they are not fit for innocent men to read. And so we
have to be content to study dress and the lures that fascinate the other sex.
But they—they go forth to fight our battles, make our laws, have their part in
the stir and excitement of

[THE BENEFICENT COVER SYSTEM.—You pay your


money and we pocket it. No further liabilities whatever.]

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

[OUR MATCHES STRIKE ONLY ON THE TROUSERS.]

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

[LITTLE TEASERS.—For the liver. As used in the Russo-


Japanese negotiations. The Arch-Prince General von
Schplitviski sends us the following despatch:
—"Plenipotentiary Ita Bino had a difference with me on
the question of a peninsula. Two of your LITTLE
TEASERS, however, came home to him, and he is now
more amenable. You have my authority for stating that
your system of internal adjustment has averted a
disastrous and even stupid war."
[Left advertising.
OPERATIC NOTES.
Opening of Opera. Monday, May 13.—Crowded house. Grand Otello Co.
unlimited. The Orchestra has been sunk four feet, thus giving Stalls clear view
of stage. Druriolanus proposes a puzzler "Orchestra lowered," he says, "yet all
performers in it hired!" Royal Highnesses present. Druriolanus, taking happy
musical publishers' points of view, looks towards Royal Box and murmurs
"'Royalties' on music." Albani surpasses herself as Desdemona: quite wonder
that Otello-Tamagno has the heart to smother her with pillow after her song
about the willow. Signor Pessina as Iago: rather a ponderous villain. Pecuniary
operatic prospects exceptionally good: at all events, possessing Jean de Reszke,
Tamagno, and Bertran, Druriolanus has "three tenners" in hand to start with.

Tuesday.—Boïto's Mefistofele. "An opera


that 'grows on you,'" says Lounger in the
Lobby. "If there were a probability of
many such growing on you, my dear
Lounger," quoth Sir Druriolanus, with
satirical affability, "you would be worth
cultivating." The advantage of a long
opera, with disconnected acts, is, that
you can "pick 'em where you like," as
the coster says of the walnuts, and
come in anywhere for something good.
Maggie Macintyre is "getting a big girl
now." Charming as Margherita and La
Vocal and Orchestral. Marguerite and
Strauss.
belle Hélène. Signor de Lucia a rather
timorous and bashful Faust, with one
eye for Maggie and the other for Nelli
(short for Mancinelli), as if praying the latter to conduct him safely and keep
him from temptation to go wrong. Faust in situation of Toole in The
Houseboat, when he used to exclaim, "Sarah! I'm slipping!" Plançon equally
good as Jupiter or Mefistofele; this time it is Mefisto.

Wednesday.—Le Prophète. In spite of name, unprofitable opera. Signor


Tamagno (or familiarly Tam Agno), as Jean of Leyden, rather over-laden, but
bearing burthen bravely. Tam receives big encore in Star-spangled Banner
Hymn. The two Corsis and Castelmary ably represent Liberator Firm of Jonas,
Zaccaria, Mathisen & Co., always ready to draw on their false prophet in order
to save their own credit. Two Corsis and dessert to follow. Beaming Bevignani
conducts invisible orchestra.

Thursday.—Sudden change from summer to winter. Comparatively thin house.


Ladies as wrapperees in furs. Everyone welcoming Pagliacci, or the Mummers,
as pantomime suitable to season. In spite of this, warm welcome to Pagliacci
and to Madame Fanny Moody as Nedda. She is quite the character: Moody yet
lively. Ancona and De Lucia good and dramatic as ever as Tonio and Canio.
Début of Miss Marie Engle, who, whether German or French, will be a favourite
with the Engle-ish, starting uncommonly well as Little Bo-Peep-Baucis. King
Jove-Plançon and Vulcan-Castelmary, the limping Olympian, excellent as
usual. Everyone suffering from wintry blasts in stalls envies Vulcan rubbing his
hands and warming himself at Bonnard-Philémon's fire. Such a night in May is
enough to knock any piece to shivers. The conductors of the operatic 'bus
were, for the first journey, Soothing Seppilli; and for the second, Beaming
Bevignani.

Friday.—Still wintry. Italian-German opera Lohengrin, with Cosmopolitan


Caste, going stronger than ever. House full and fully satisfied. Hard to please
if it had not been so, with Albani as Elsa,—(says Wagstaff, affecting a drawl,
"Nobody else-a can touch her in this"),—Jupiter-Plançon as a King, not of
gods but men, and Bertran, from La Scala, as a First-Knight Lohengrin. As to
intruder Ortruda and Terrible Telramonda, these heavy weights are lifted by
Mlle. Olitzka and Signor Ancona. Monarchical Mancinelli treats Time like a dusty
carpet, beating it strongly.

Saturday.—Crowded house to welcome old friend Trovatore. Pessina as the


wicked nobleman; and Tamagno—now known as "Tam"—in splendid voice for
the Trovatore himself. "Tam" doubly encored after "Di quella pira." Julia Ravogli
not quite the Azucena. Mlle. Bauermeister's first appearance this season: as
heroine's sympathetic companion Bauermeister combines the "utile" with the
"dulce." Maggie Macintyre vocally good, dramatically puzzling. House happy:
Druriolanus delighted. Fine finish to first week.
ROUNDABOUT READINGS.
There is only one Parish Council in England which is
presided over by a lady. Her name is Jane
Shakespeare, and she rules the parochial
deliberations of Netherseal in Leicestershire. No
doubt it will be found by her councillors that Jane
hath a way with her, and thus she will be brought
into line with her illustrious namesake.

[At Gamlingay, in Cambridgeshire, Mr. Dew


declined to undertake the duties of cemetery
superintendent for a salary of £5, and Mr.
Howe was consequently appointed to the
post.]

Mr. Dew, when he heard of the offer, looked blue;


He considered a fiver was less than his due.
How do it? The question gave rise to no row,
For Miss Echo replied, and her answer was Howe.

Congratulations to Mr. F. Mitchell, of Cambridge University, on his innings of


191 runs against Somerset.

The men of the county had studied their pitch ill;


They did what they could, but they couldn't bowl
Mitchell.
His masterly cutting the bowlers appals,
For the grass being short, he makes hay of their balls.

A writer in The Manchester Guardian declares that the main road


between Bolton and Bury is in a shocking condition. What is the road
between Bolton and Bury? Bolton suggests that he who fights and
runs away lives to fight another day, but Bury seems to indicate a
path of glory leading to the grave—which things are a paradox. In
any case, I endorse the writer's suggestion—

That Alderman Hulton should harness his colt on,


And drive o'er the road between Bury and Bolton.
The chock-holes and paving are terrible—very,
And he may find his tomb e'er he comes back to Bury.

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?

What is "dockisation"? Whatever it is, they have been


debating upon it at Bristol, and the proceedings are
described as "decidedly lively." The protagonists were
Mr. de Ridder and Alderman Proctor Baker.

Dockisation, I think, is a question of docks,


And at Bristol it lately gave rise to hard knocks.
"Let's be rid of a scheme which is bad for the town,"
Said de Ridder, whose statements excited a frown.
But they smiled on beholding this argument-maker
By a Proctor well caught and done brown by a Baker.

LEEDS LEADS!
Or, Welcome News from the North.

["The tenor of market reports concerning all the main


industries out of which the citizens of Leeds make their
living ... suggests the advent of a turn for the better,
commercially, that may almost claim to rank as an
industrial revolt."—The Yorkshire Post.]
Hooray! Food for hope the Tyke Town surely yields.
The "Sun of York" shines on the Cardigan Fields
(Which now should be called the Elysian).
The Capitalist and the Builder unite
To throw light upon Leeds. Let's sing, "Leeds! kindly light!"
(Which we hope will not shock the precisian.)
Oh! Bradford and Huddersfield, Dewsbury, Batley!—
(These Yorkshire names fall into rhythm most patly)—
Your returns and reports Trade is heeding,
In hope that the storm, like the North, we may weather,
With Walker and Sons (there is nothing like leather!),
Those great "Men of (Leeds) Light and Leading!"

Appropriate.—Fixed service for "Tied Houses" should be the bounden duty of


Tide-waiters.

AN EMBARRASSING QUESTION.

"Why have you got such a Bare Neck, Mummie?"

"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.

Cowes.—Spencer really very nautical. Talks of fast cruisers and water-tube


boilers all the time. Great on torpedo-destroyers. Says the Havoc "goes
twenty-five knots an hour." Well then, why can't Harcourt get up the same
pace with our Bills? Wish he'd turn into a Parliamentary Havoc. Mention this to
Spencer, who laughs, and says, "It's the Opposition who indulge in twenty-five
Nots an hour." Believe Spencer means it as a joke. Turn in, and think of
Harcourt and Spencer's joke and Twin-Screw Cabinets and Water-veto-boiler
Bills. Wretched night!

Portland, Tuesday Morning.—Rather unfair of Spencer. Now he's got me safely


on board, he's always trying to persuade me that Navy wants more money
spent on it. More money! Refer him to Harcourt, the "inexorable Jorkins." Try
to hide from Spencer. No good. He finds me behind a coil of rope on half-
quarter-deck—is it half-quarter-deck? Not sure, and don't like to ask—and
begins again. Seems he would like a few more millions for guns. Thought we
had heaps of guns. Talks about a ship he calls The Hecckler. What a name!
Reminds me of every political meeting I've ever attended. Why will Lords of
Admiralty give such names? Spencer explains—seems it's Hecla, not Hecckler.
Oh! All right. Fear Spencer begins to think me rather a land-lubber. Got me at
an advantage here. Wait till I take him to Newmarket Heath!

Off Plymouth.—Down in engine-room. Tell head stoker that House of Lords is


an effete institution. Stoker winks. Can he be a Tory? Tell him it's a "gilded
prison." Stoker seems surprised, and asks, "Why I don't chuck it up, then?"
Curious—no repartee handy. And I am so good at them, generally. Must
consult "Fridoline," traduit de l'Anglais de "Happy Thoughts," to see what
would be a "repartee to a stoker." Bed. Spencer won't hear of it as bed; talks of
"turning-in to his bunk." What an enthusiastic "First Lord" Spencer does make!
Thinking of First Lord, wonder who'll be Last Lord? Go on wondering till dawn.
What a noise swabbing the deck makes! Wish I were back at the Durdans!

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."

Oxford Degrees.—Certainly Messrs. Dan Leno and Albert Chevalier


should have Masterships of Arts conferred on them. The "Voces
Stellarum" at the Oxford Observatory (otherwise Music Hall) are well
worth hearing. Mr. Burnett (J. P.) has just issued a brochure on this
Music-Astronomical subject, chiefly remarkable for a brief essay on
"The Pantomimic Art," by Paul Martinetti, whose right to speak on
such a theme, as an authority, may be arrived at by any one who
sees this most artistic pantomimist in a short melodramatic piece—a
piece which thoroughly tells its own tale without words—now being
performed nightly at the Oxford. It is admirable. If action can do so
much, then why not a Shakspearian play in action, and "the student"
could read the words to himself at home? We recommend the idea to
Mr. Paul Martinetti, and should advise him to re-arrange Don Quixote,
as "a piece without words," for Mr. Henry Irving, who now looks and
acts the part to perfection; the piece itself might then be of the
actor, that is,—if action were substituted for its very poor dialogue.

Politics à la Perkyn Middlewick.—The Radical wire-pullers now


regard the middle-class Walworth voters (for Mr. Bailey) as "Shop
'uns," and the county division which returned Colonel Williams as
"inferior Dosset"!
"GREAT CRY AND LITTLE WO(O)L-MER!"
Bathing Woman. "COME ALONG, MASTER SELBORNE, AND
TAKE YOUR DIP LIKE A LITTLE NOBLEMAN!"
THE SCARLET PARASOL.
Scene I.—Terrace in front of quaint old country house. Viola Travers and Muriel
Vane on garden-chairs. Viola is twenty, dark-eyed, and animated; she holds a
scarlet parasol. Muriel is eighteen; she has very fair hair, parted with
puritanical precision; the naïve innocence of her manner is not without a
suggestion of artistic premeditation.

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. You have Albert.

Viola. You know that Albert is 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. No; you have been very nice about it.

Viola. Albert is perfectly happy, playing at being a country gentleman. He was


so amazed to find there were real ducks and fowls in the country—and
buttercups! He tells me everything. He boasts we tell each other everything.
Oh! I should so like to have some little thing to conceal from him—some
secret, just for fun! Of course I should tell him all about it afterwards, you
know.

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.

Muriel. I suppose she had a housemaid's knee.

Viola. You are quite wrong. She had writer's cramp, poor thing!

Muriel. How absurd, Viola! How are you, Dr. Roberts!


[Dr. Roberts has iron-grey hair and dark eyes. As he
joins them Muriel leans down to pat a dog with all the
graceful self-consciousness of youth. Dr. Roberts looks
at Viola admiringly.

Viola. I hope poor Jane is better?

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?

Viola. Do; and stay and have some tennis.


[Dr. Roberts accepts with evident enthusiasm, and
takes leave with obvious regret.

Muriel (watching him drive away). Dr. Roberts admires you dreadfully. Is that a
romance?

Viola. For him perhaps—not for me! And it isn't a mystery!


[A telegram is brought in.

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.

Muriel (coldly). Yes, Mr. Averidge?

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.

Muriel. Albert will call it cheek—I daresay!

Mrs. Averidge. He is most amusing. I met him at Lady Bayswater's. He looks


quite an angel playing the harp.

Albert. I hope he'll bring his halo in a hat-box. What is that text about "Young
lions do lack——"

Muriel. Oh, Albert!


Servant. Master Alan Roy!

Albert (aside). Now, don't make the poor child


shy.
Enter Alan Roy. Tall young man, in light grey
suit. He wears a turned-down collar, a pink
button-hole, and carries a little stick.

Alan. How are you, Mrs. Travers? So sweet of


you to ask me! Isn't it a dear day!
[Greetings.

Mr. Averidge. And how did the infant prodigy


manage to get here all alone?

Alan. I pushed myself in a perambulator. Miss


Vane, you look like a Botticelli in a Paris dress.
I didn't bring my harp, does it matter?
[Chorus of sham disappointment and real
"Enter Alan Roy." relief.

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.

Alan (to Viola). Oh, what a sweet scarlet parasol!

Curtain. End of Scene 1.

(To be continued.)

Neither Free Nor Easy.—The Larne Town Commissioners cannot make


up their minds whether they shall acquire the McGarel Town Hall
which apparently (to judge from a report in the Northern Whig)
appears to be in the market. The room, it seems, would be used for
a free library. The Committee, after a very lengthy discussion, have
adjourned the consideration of the question to some distant date for
further information. In the meanwhile, no doubt, they will
appropriately adopt for the municipal motto "Live and Larne."

CYNIC TO POET.
[The great lack of the Age is its want of distinction."
Coventry Patmore.]

Alas, our poor Age! How against it we rage!


In the seat of the scorner the critics ne'er sat more.
If the pessimist bore would master her lore,
We've only to send him to Coventry—Patmore!
The bards do not love it. But how to improve it?
That question the poets, like that of the Sphinx,
shun.
Distinction my lad? If the Age is so bad,
I think its "great lack" is not that, but extinction!
'Tis easier far to abuse it than mend it,
Must we try Morley's other alternative—end it?

A Musical Note.—Such has been the success of Mlle. Yvette Guilbert,


that, on dit (French must be used when speaking of this lionne
comique), it is not improbable she will be engaged to appear in a
part in the forthcoming Sullivan Savoy Opera, in which the relation of
librettists to composer is to be as two to one. If this be so, then once
more at the Savoy will there be a Sullivan-and-Guilbert Combination.
"WHITAKER."
[Mr. Joseph Whitaker, founder and chief proprietor of Whitaker's Almanack, died
on the 15th May, aged 75.]

Gone! His praises to rehearse


Might engage a friendly verse.
Time, for whom he did so much,
Surely dealt with gentle touch
With this man, of lucky star,
Who the famous calendar,
Schemed on an ingenious plan,
Gave to ever-grateful man.
Millions now would feel the lack
Of the wondrous Almanack.
To adapt Ben Jonson's phrase
To a worthy of our days,
One might say of our lost brother,
Death; ere thou hast slain another
Good and useful as was he,
"Time shall throw his dart at thee."

Champions.—Sir Edward Grey, M.P., ought to be a great acquisition at a


dance if his prowess as a tennis champion is any indication. "The
power with which he often finished the ball" was recently highly
praised. His opponent, Mr. Gribble, seems a dangerous man among
the ladies, having at Cambridge "won the singles." Quite a Pasha
among the "Love sets!" But he could only take one single out of the
singles he won.

Odd.—"Doctor Greef" is advertised to give three pianoforte


recitals. If his performance is equal to what we hear of his
promise, then those will experience considerable pleasure who
"come to Greef."
Small but Harmonious Football Team for Summer.—"The Shinner Quartette."

WHAT OUR ARCHITECT HAS TO PUT UP WITH.

Our Architect (spotting Sixteenth Century gables). "That's an old bit of


work, my friend!"

"Oi, Sir, yeu be roight theer, that you be!"

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.)

"Cast ne'er a clout till May be out,"


The old Scotch proverb says.
Thee, did I doff, "Immensikoff,"
For three most sultry days.
But wind and dust, in gruesome gust,
Search bosom, back and throat;
And to my nose I button close
My fur-lined Overcoat.
The Merry May has such a way
Of blowing hot and cold,
That fur and cloth I'm always loth
Away, in Spring, to fold.
Gr-r-r! There's a blast! I'll hold thee fast
Dear friend on whom I doat;
Nor lay thee by till—say—July,
My own, my Overcoat!

Legal Note.—It is presumably unfortunate for the prisoner-at-the-bar


when, as is constantly announced in the papers, "Mr. So-and-So,
Q.C., will appear to defend Snooks." Hard on Snooks when his Counsel
only appears to defend him. But what a sweet surprise for the
unhappy Snooks should the Counsel, who only "appears to defend
him," really defend him and be victorious!

"Vox Clamantis."—The voice of the Claimant is heard once again.


No joke; no Wagga-Waggery. He is publishing his "Entire Life
and Full Confession" in the People newspaper. According to his
own statement, his claim to the Tichborne estates might be
described, not only as a fraud, but as a "Wapping" one.

TO A COUNTRY HOST.
(A Candid Answer to a Hospitable Invitation.)

You're kind enough to bid me spend


The "week-end" at your country seat,
You offer tennis and a friend
You feel I'm sure to like to meet.
I hope you will not think me rude—
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

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


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

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


personal growth every day!

ebookbell.com

You might also like