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

Guide To Java A Concise Introduction To Programming 2nd Edition 2nd James T Streib download

The document is a guide to the second edition of 'Guide to Java: A Concise Introduction to Programming' by James T. Streib and Takako Soma, aimed at helping beginners quickly learn Java programming fundamentals. It emphasizes concise explanations, numerous examples, and interactive questions to reinforce learning, while also introducing object-oriented programming concepts early on. The second edition includes updated content, reorganized chapters, and new topics such as computational thinking and parallel processing.

Uploaded by

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

Guide To Java A Concise Introduction To Programming 2nd Edition 2nd James T Streib download

The document is a guide to the second edition of 'Guide to Java: A Concise Introduction to Programming' by James T. Streib and Takako Soma, aimed at helping beginners quickly learn Java programming fundamentals. It emphasizes concise explanations, numerous examples, and interactive questions to reinforce learning, while also introducing object-oriented programming concepts early on. The second edition includes updated content, reorganized chapters, and new topics such as computational thinking and parallel processing.

Uploaded by

csecsdjango
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/ 83

Guide To Java A Concise Introduction To

Programming 2nd Edition 2nd James T Streib


download

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

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 Streib James Tsoma

https://ebookbell.com/product/guide-to-java-a-concise-introduction-to-
programming-streib-james-tsoma-21986274

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
Second Edition
Undergraduate Topics in Computer Science

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

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

Guide to Java
A Concise Introduction to Programming

Second Edition

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

ISSN 1863-7310 ISSN 2197-1781 (electronic)


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

1st edition: © Springer-Verlag London 2014


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

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

James T. Streiba,1 and Takako Somaa,2


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

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

Comparison to Other Texts


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

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

Features of This Text


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

v
vi Preface

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


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

Features New to the Second Edition

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

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


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

Overview of the Chapters


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

Ordering of the Chapters

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

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

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

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

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

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

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

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

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

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

Illinois College James T. Streib


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

0 Introduction to Computing Concepts 1


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

1 Variables, Input/Output, and Arithmetic 17


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

xi
xii Contents

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

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

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

4 Iteration Structures 121


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

4.5 Nested Iteration Structures 140


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

5 Objects: Revisited 155


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

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

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

7.3 Array Access 224


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

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

9 Objects: Inheritance and Polymorphism 293


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

10 Elementary File Input and Output 321


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

10.4 File Input and Output Using an Array 328


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

11 Bit Manipulation 341


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

12 Introduction to Parallel Processing Programming 356


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

Appendix A Explanation and Elaboration of Concepts in Chapter 1 375


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

Appendix B Exceptions 387


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

Appendix C Javadoc Comments 


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

Appendix D Glossary 

Appendix E Answers to Selected Exercises 

References and Useful Websites 

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

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

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

0.1 Introduction

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

0.2 Overview of Hardware and Software

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

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


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

CPU

Input Output
RAM

Storage

Fig. 0.1 Computer hardware

0.2.2 Software

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


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

Compiler Assembler

High-Level Assembly Machine


Language Language Language

Fig. 0.2 Assemblers and compilers

0.2.3 History and Java

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

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

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


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

0.2.4 High-level Translation

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

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

Compile Interpreter

High-Level Machine High-Level Machine

Instruction1 10101010 Instruction1 10101010


01010101 01010101

Instruction2 00110011 Instruction2 00110011


11101110 11101110

Instruction3 00001111 Instruction3 00001111


11110000 11110000

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

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

Fig. 0.3 Compilers and interpreters


0.2 Overview of Hardware and Software 5

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

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

Interpreter
Compiler

Java Bytecode Machine

Instruction1 Bytecode 10101010


Bytecode 01010101

Instruction2 Bytecode 00110011


11101110

Instruction3 Bytecode 00001111


Bytecode 11110000

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


instruction at a time

3. And then execute only the corresponding


machine instructions

Fig. 0.4 Java instructions, bytecode, and machine language

0.3 Introduction to Computational Thinking


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

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

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

Initial state Final state

Fig. 0.5 Tower of Hanoi game

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

Fig 0.6 The largest ring in the final position

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

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

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

Computer scientists naturally use computational thinking when writing programs,


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

0.4 Essentials of Software Design

0.4.1 Syntax, Semantics, and Errors


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

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

0.4.2 Design Methodology


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

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

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

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

0.4.2.2 Design

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

0.4.2.3 Implementaion

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

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


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

0.4.2.4 Maintenance

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

0.4.3 Tools and Techniques

0.4.3.1 Pseudocode

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

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

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

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

areaRec height x width areaRec = height * width;

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

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

0.5 A Brief Look at Computer Ethics

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


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

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

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

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


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

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


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

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

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

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

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


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

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


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

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


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

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

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

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

1.2 Java Skeleton


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

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


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

Fig. 1.1 Java skeleton program

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

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

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

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

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

1.3.1 Text-based Output

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

Fig. 1.2 Hello World!

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

The method name println LVRIWHQSURQRXQFHGDV³SULQWOLQH´HYHQWKRXJKLWLVQRW


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

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

Hello World!
_

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

1.3.2 GUI-based Output

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


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

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

import javax.swing.*;

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

Fig. 1.3 Message Dialog Box

The JOptionPane.showMessageDialog indicates that the


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

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

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

1.4 Variables and Constants


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

Fig. 1.4 Representation of memory

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

Fig. 1.5 Using names for memory locations

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


22 1 Input/Output, Variables, and Arithmetic

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


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

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


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

Type Size Range


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

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

int number;

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

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

double average;

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

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

char initial; String name;


and would be represented with values as follows, respectively:

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

1.5 Assignment Statements


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

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

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

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

number 5

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

int number, answer;


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

indeterminate. The memory locations would look as follows:

number 5 answer ---

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

number 5 answer 5

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

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

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

number 5 result ---

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

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

number 5 result 5.0

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

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

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

number 5.7 result 6

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

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

1.6 Output

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

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

Hello
World!
_

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

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

Hello

World!
_

The following code segment would accomplish this task:


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

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

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

Fig. 1.6 Outputting an int

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

The number is 5
_

Fig. 1.7 Outputting an int with description of output


30 1 Input/Output, Variables, and Arithmetic

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

Fig. 1.8 Outputting a double precision number without formatting

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

printf(control string, expr, expr, …)

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

Fig. 1.9 Formatting a double precision number


1.6 Output 31

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. 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.8.
Some characters cannot be simply included between double quotes for output. In order
to output a double quotation mark, a back slash in front of the double quotation marks
needs 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, \
1.6.2 GUI-Based
When using GUI-based output and if multiple lines of text need to be displayed in a
message box, the control character \nZKLFKVWDQGVIRU³QHZOLQH´FDQEHXVHGWRVHSDUDWH
the lines as in

JOptionPane.showMessageDialog(null, "Hello\nWorld!");

which results in the dialog box shown below:

As can be seen, Hello, and World! are output on separate lines. The \n can also be
used in a string with text-based output, which works similarly to the ln portion of a
println statement. Since there is no choice with message boxes, it will be used in GUI-
based output and the ln will be used more often in text-based output.
32 1 Input/Output, Variables, and Arithmetic

The output of integers in message boxes is fairly easy, where the variable name needs
to be placed in the parameter list. If one wants to identify the integer being output to the
user, then just as with text-based output, the identifying string is concatenated with the
integer using the + sign. Likewise, the output of double precision numbers can be
formatted as with text-based output. The program in Figure 1.10 is the same as Figure 1.9
except GUI-based output is used:

import javax.swing.*;
public class MsgBoxOutput {
public static void main(String[] args) {
double num;
num = 1.0 / 3.0;
JOptionPane.showMessageDialog(null, "The number is "
+ String.format("%4.2f", num));
}
}

Fig. 1.10 Outputting a double precision number using GUI

The format method defined in the String class in String.format("%4.2f",


num) will return a formatted number and display it in a dialog box. Note that the format
method does not alter the contents of num.

1.7 Input

1.7.1 Text-based
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, or a
disk and this section will deal with the simplest form of input from the keyboard.

As in the last section, it is best to start with a simple example based on the previous
program in Fig. 1.7 and modified as shown in Fig. 1,11. 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.
1.7 Input 33

Remember when the System.out.println and System.out.printf


statements were used for output, the java.lang package including the System class
was not imported at the beginning of the program. This is because the java.lang
package, which includes the System and Math classes, is used extensively, and is
automatically imported into all Java programs.

Fig. 1.11 Program to input an integer

Similar to GUI-based output, 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, but
instead of the swing package, the util package is used for text-based input.
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 in Section 0.4.3.2 and will be discussed further in Chap. 2 , a class can
be thought of as the set of blueprints for a building. Notice that the class name begins with
an upper-case S, whereas the variable name begins with a lower-case s. Continuing, 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
34 1 Input/Output, Variables, and Arithmetic

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.12 includes a prompt just prior to the input.

Fig. 1.12 Prompting a user to input a number

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. Instead of using a
System.out.println(); notice that a System.out.print(); without the ln
is used which causes the cursor to stay on the same line for subsequent input. Further, a
prompt should be formatted well such as including 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.
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-IULHQGO\ SURPSW FDQ EH SROLWH VXFK DV ³3OHDVH HQWHU D QXPEHU ´ EXW
typically a prompt should avoid the use of first-SHUVRQZRUGVOLNH³,´DQG³\RX´DVLQ³,
ZRXOGOLNH\RXWR«´VLQFHWKHFRPSXWHULVDPDFKLQHQRWDKXPDQ
Now would be a good time to enter, compile, and run the program in Fig. 1.12 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,
1.7 Input 35

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.2 GUI-based
A GUI input dialog box can be created by using the showInputDialog method that is
also defined in the JOptionPane class. The following code shows how the
showInputDialog method can be invoked:
JOptionPane.showInputDialog(null,"What is your first name?");
As with the showMessageDialog method, it sends a JFrame object and a String
object as arguments. As before, the null value causes the dialog box to appear in the
center of the screen. The second argument is a message displayed above a text field in the
dialog box. The text field is an area in which the user can type a single line of input from
the keyboard. When the statement is executed, a dialog box will appear and a user can
enter text in the text field as in Figure 1.13.

Fig. 1.13 An input dialog box asking the first name

When the OK or Cancel button is clicked, or the Enter key is pressed, which is an
alternative to pressing the OK button, the dialog box will disappear. However, it does not
do anything more and the value entered in the text field is gone. In order to save the value
the user entered, a String variable needs to be declared, and in this case it is called
firstName. Then the value returned from the method has to be assigned to a variable
both as shown below:

String firstName;
firstName = JOptionPane.showInputDialog(null ,
"What is your first name?");

Now, if the user enters Maya in the text field and clicks the OK button or presses the
enter key, a reference to the String object with the value "Maya" will be assigned to
the String variable firstName . If the user clicks the OK button or presses the enter
key without entering anything in the text field, firstName will reference the object of
the String type with an empty string. If the user clicks the Cancel button regardless of
what was entered in the text field, firstName will contain the value null.
The following program demonstrates how to use both types of dialog boxes. Notice the
import javax.swing.*; statement, which is not only needed for GUI-based output,
Random documents with unrelated
content Scribd suggests to you:
THE GENTLE YOUTH FROM
LEADVILLE.

I
n addition to the other attractions about the depot, the old
museum of curiosities from the Rocky Mountains has been re-
opened. I like to go down and listen to the remarks of the
overland passenger relative to these articles. There are two stuffed
coyotes chained to the door, one on each side, and it amuses me to
see a solicitous parent nearly yank his little son to pieces for going
so near these ferocious animals. The coyotes look very life-like, and
show their teeth a good deal, but it breaks a man all up when he
finds that their digestive apparatus has been replaced with sawdust
and plaster of Paris.
After a coyote gets to padding himself out with baled hay and
cotton so as to look plump, he loses his elasticity of spirits, and we
cease to respect him. Sometimes a tourist asks if these coyotes are
prairie dogs.
A few days ago a man from Michigan, who has been here two
weeks and wears a large buckskin patch where it will do the most
good, and who is very bitter in his remarks about "tenderfeet," was
standing at the depot, when a young man, evidently from a
theological seminary, came along from the train whistling, "What a
friend we have in Jesus." He walked up to the Michigan man, who
began to look fierce, and timidly asked if he would tell him all about
the coyote.

The Michigan man, who never had seen a live coyote in his life,
volunteered to tell him some of the finest decorated lies, with
Venetian blinds and other trimmings to them, while the young man
stood there in open-mouthed wonder, with daylight visible between
his legs as high as the fifth rib. I never saw such a
picture of rapt attention in my life. As he became
more interested, the Michigan man warmed up to his
work and lied to this guileless youth till the
perspiration rolled down his face. As the train started
out, the delegate to the Young Men's Christian
Association asked the Michigan man for his address. "I
want the address of some good earnest liar," he said,
"one who can lie by the day, or by the job, and
endure the strain. I want a man to enter the field for
the championship of America. Any communication you
may wish to make will reach me at Leadville,
Colorado. I have been in the Rocky Mountains ever
since I was three years old, and have lived for weeks
with no other diet but coyote on toast and raw
Michigan man." He waved his hand at the M. man, and said: "If I
don't see you again, hello!" and he was gone.
How many such little episodes we experience on our journey to
the tomb!
A SNIDE JOURNALIST.

R
ecent occurrences here have seemed to absolutely demand
that something be said relative to newspaper-men.
During my residence here I have been brought face to face
with more fraud journalists than ever before, and I am forced to lift
up my voice against it. I have met the ordinary-tramp who is pleased
and happy if he be allowed to eat cold-grub and sleep beneath the
twinkling stars, but the newspaper-tramp is meaner, more self
assumed and has brighter prospects for perdition than all the rest.
He stands out ahead of the rank and file of tramps as a kind of
Major-General tramp, fearless and self reliant.
He feels the nobility of the profession of journalism, and indeed it
is a calling of which its followers may well be proud, but the snide
representative of the press is too proud. He puts on too many frills.
Perhaps I am too easily picked up in this manner, but I cannot
help sympathizing with deserving newspaper men who lack many of
the comforts of life. I have been there. I know what it is to battle
with a cold world and wrestle with hunger. But now in the midst of
prosperity, my heart goes out for these vagrants in such a way that
just as I begin to get affluent, I find some subject for my charity,
and I have to begin over again.
On Monday last a young man with a hopeful light in his eye,
alighted from the eastern-bound train, and going into the Thornburg
House, registered his name, at least we will play that it was his
name, for no one else has since called in to claim it.
We will call him Brown as a matter of convenience. His front
name, as I afterward learned, was Ward. I might say that, in putting
this report together, another Ward has been heard from, but I leave
that for the docile reader to do as he or she may see fit.
Mr. Brown then proceeded to get acquainted with the people of
Laramie and be sociable. He was not so reticent as some prominent
newspaper men are, but seemed to be the rollicking, jovial kind. He
said that he was the travelling correspondent of the Salt Lake
Tribune and also represented the Louisville Courier-Journal.
I wondered at the time what in the name of all that was
handsome, the Courier-Journal wanted to pay a man and send him
to the front for, with Laramie City as his objective point. Bye-and-bye
he crossed my path and made himself known. Said he knew me by
reputation, and then I began to get alarmed. I was afraid he was a
detective. But he wasn't. I drew him out on the subject of Harry
Watterson. He knew blank. Knew him well. Had slept with him. He
and Hank had been drunk together several times.
Then I felt proud. He was an intimate friend of a great man, and
sitting there talking with an unsophisticated youth like me just as
naturally as life. It sounds like a book. I asked him up to my office,
and made him sit in my best chair—the one with the four good legs
—while I took the foundered one. I told him to make himself
perfectly free with the luxuriant furniture of the office, and invited
him to spit on the floor whenever it came handy. I told him that I
knew great men didn't want to feel hampered while chewing
tobacco, and that I wanted my guests to feel at ease.
He then took his knife, cut off a piece of tobacco, about the size of
a paper weight, threw it back till it struck the gable-end of his mouth
with a hollow thud, and proceeded to unroll the most gorgeous
panorama of falsehoods that I ever listened to. Casually, while
putting the fresco work on my floor, he took out a letter from
Watterson, and showed it to me. Watterson writes about the same
kind of a copper-plate hand that I do.
I wanted to take the letter and make a plaster cast of it, but Mr.
Brown said Hank wouldn't like it. The letter went on in a free and
easy way to joke Brown about looking too often on the maddening
bowl, and then asked him to be a correspondent for the C. J.
The next day I came down town thinking about how easy it was
for any one, by a straightforward, honest course, to rise in the
world, and get acquainted with prominent men. Bye and bye I met
the Sheriff. He asked me if I didn't want to go up to the jail and take
a last look at my journalistic friend. I went up. Brown lay there in an
easy position on an old blanket, in one of the cells.
The surroundings seemed to be in perfect harmony with the
general appearance of Mr. Brown. He had taken off the large satin
arrangement which served partly as a necktie, and partly to throw
the public off its guard in relation to his shirt. The shirt was there,
slightly disfigured, but still in the ring. It was the same shirt that he
had started out in life with. He had outgrown it, and it looked feeble,
but it was evidently determined to stay by Mr. Brown.
I looked at him and then broke into tears. Large $2.00 sobs
convulsed my frame. I told him that he had basely imposed upon
me, and led me to believe that he was a Republican, and now he
had removed the mask as it were, and I could see that he was a
Democrat. With these stone walls and iron grates, and that soiled
shirt, I could no longer doubt.
I left him, resolving that hereafter I would not be betrayed by
appearances. He will drift away into the mighty, surging mass of
humanity, and we shall forget it. Perhaps, when the Governor of
Maine holds a mass meeting and re-union at Augusta, he will be
there. But he will drop out of my horizon like the memory of a red-
headed girl, and I shall go on my way until some other newspaper
man with a letter from Whitelaw Reid, or George Washington, or
Noah, or some other prominent man, comes along, and then I shall,
no doubt, open up to his view the same untold wealth of confidence
and generous trust.
Those who are looking anxiously every mail for a copy of the
Louisville Courier-Journal or the Salt Lake Tribune, containing a long
letter about their town, will be disappointed. They will never come.
Through the long visita of years and down through the mellow
softened atmosphere of the Sweet Bye and Bye I hear the low, sad
refrain, and it is refraining, "Never More." Instead of the merry
prattle of Mr. Brown amid the loud echo of his expectorations as they
fall with a startling crash upon the marble floor of my office, I only
hear the rattle of the cast iron "come-alongs" and the tearful "Never
More."
HE WAS BLIND.

W
hile engaged the other day in writing a little ode to the liver
pad, I heard a slight noise, and on looking toward the door
I saw a boy with his hat in his hand standing on one leg
and thoughtfully scratching it with the superior toe of the other foot.
I asked the freckled youth what I could do for him, and he said
that there was a man at the foot of the stairs who wished to see me.
I asked him then why in the name of a great republic and a free
people he didn't see me. Then I told the boy that there was no
admission fee; that it was the regular afternoon matinee, and it was
a free show.
The frank and manly little feilow then came forward and told me
that the man was blind.
It was not intended as a joke. It was a horrible reality, and pretty
soon a man into whose sightless orbs the cheerful light of day had
not entered for many years came up the stairs and into the office.
I said: "Ah, sir, I see that you are a poor, blind man. You cannot
see the green grass and waving trees. While others see the pleasant
fields and lovely landscape you wander on year after year in the
hopeless gloom. Poor man. Do you not at times yearn for
immortality and pine to be among the angels where the light of a
glorious eternity will enter upon your sightless vision like a beautiful
dream?"
This was a little sentiment that I had committed to memory, being
an extract from the Youth's Companion.
He wiped away three or four scalding tears with his sleeve and
said that he did. He was getting means, he said, to enable him to go
to New York, where he was going to have his eyes taken out and
refilled. He also intended to have the cornea filed down and a new
crystal put in.
I asked him how much he thought it would cost. He said he
thought it could be arranged so that $1,000 would pay the bill. At
first I started to draw a check for that amount, and then I thought I
would try him with a dollar first.
He took the dollar and walked sadly away.
It always makes me feel bad when I see a fellow creature who is
doomed with uncertain steps and sightless eyes to tread his weary
way through life, and I cannot be happy when I know that such
misery is abroad in the land. I thought how much I had to be
thankful for, how fortunate I had been to have all my senses and my
bright and beautiful intellect, that I wouldn't take $400 for.
Then I wandered out to a saloon on A street to get a cigar. The
blind man was there. He had just poured out about six fingers of
Jamaica rum and was setting them up for the boys. I thought I
would stand in with the arrangement, so I leaned up against the bar
in very classic style and took two cigars at twenty-five cents apiece.
When he came to pay for the goods he shoved out the dollar I
gave him, which I recognized, because it was a pewter dollar, and a
very inferior pewter dollar at that.
The bartender kicked like a roan cow, and while the excitement
was at its height I stole away to where I could be alone with my
surging thoughts.
The blind man is still in town, but he is not succeeding very well.
Unfortunately he has told several large openfaced lies and the
feeling of pity for him has petered out, if I may be allowed that
expression.
When he is sober he is going to have his eyes operated on at New
York, and when he is drunk he is going to have them attended to in
San Francisco. This gives the general appearance of insincerity to his
remarks, and the merciless public yearns for him to pack his night
shirt, like the Arabs and silently steal away.
THOUGHTS OF THE MELLOW
PREVIOUSLY.

I
t is the evening of St. Valentine's Day, and I am thinking of the
long ago. St. Valentine's Day is nothing now but a blessed
memory. Another landmark has been left behind in our onward
march toward the great hereafter. We come upon the earth, battle a
little while with its joy? and its griefs, and then we pass away to give
place to other actors on the mighty stage.
Only a few short years ago what an era St. Valentine's Day was to
me.

Now I still get valentines, but they are different and


they affect me differently.
They are not of so high an order of merit artistically,
and the poetry is more impudent and less on the
turtle-dove order.
Some may be neglected on St. Valentine's Day, but
I am not. I never go away by myself and get mad
because I have been overlooked. I generally get
valentines enough to paper a large hall.
I file them away carefully and sell them back to the
dealer for next year. Then the following St. Valentine's
Day I love to look at the familiar features of those I have received in
the years agone.
One of these blessed valentines I have learned to love as I do my
life. I received it first in 1870. It represents a newspaper reporter
with a nose on him like the woman's suffrage movement. It is a
large, enthusiastic nose of a bright bay color, with bias folds of the
same, shirred with dregs of wine. How well I know that nose. The
reporter is represented in tight green pants and orange coat. The
vest is scarlet and the necktie is maroon, shot with old gold.
The picture represents the young journalist as a little bit disposed
to be brainy. The intellect is large and abnormally prominent. It
hangs out over the deep-set eyes like the minority juror on the
average panel.
I can not help contrasting this dazzling five-cent valentine with the
delicate little poem in pale blue and Torchon lace which I received in
the days of yore from the redheaded girl with the wart on her
thumb. With little of genuine pleasure have fame and fortune to
offer us compared with that of sitting behind the same school desk
with the Bismarck blonde of the school and with her alternately
masticating the same hunk of spruce gum!
I sometimes chew gum nowadays to see if it will bring back the
old pleasant sensations, but it don't. The teacher is not watching me
now. There is too little restraint, and the companion too who then
assisted in operating the gum business, and used to spit on her slate
with such elegance and abandon, and wipe it thoughtfully off with
her apron, she too is gone. One summer day when the little birds
were pouring forth their lay, and the little lambs were frisking on the
green sward, and yanking their tails athwart the ambient air, she lit
out for the great untried West with a grasshopper sufferer. The fluff
and bloom of existence for her too is gone. She bangs eternal
punishment out of thirteen consecutive children near Ogallalla,
Nebraska, and wears out her sweet girlish nature working up her
husband's underclothes into a rag carpet. It seems tough, but such
is life.
MY TOMBSTONE MINE.
Camp on Alder Gulch, June 18, 1880.

T
he general feeling of expectation and suspense which is the
natural result of recent mineral discoveries near to any mining
town, is still prevalent. If possible it is on the increase, and all
the prevailing indications of profound mystery are visible
everywhere. There is a general air of knowing something that other
people do not. Almost every man is hugging to his bosom a
ponderous secret which is slowly crushing him, while all his fellow
men are trying to hold down the same secret.
Occasionally a man comes to me, takes my ear and wrapping it
around his arm two or three times so that I can't get away, he tells
me that he knows where there is the richest thing in America. Only
he and his wife and another man and his wife know where this
wonderful wealth is to be found.
He asks me to come into it so that capital will then be interested. I
agree to it and on the way to the camp I overtake the able-bodied
men of Wyoming, all of whom are trying in their poor, weak way to
keep the same secret.
Such is life.
Sometimes I think that perhaps I had better give up mining. I do
not seem to get the hang of the thing, somehow. All the claims I get
hold of are rich in nothing but assessments, while less deserving
men catch on to the bonanzas.
Once I located a vein which showed what I called good indications
of a permanent vein, staked it out under the United States law and
went to work on it. I paid out $11 for sharpening picks alone, in
going down ten feet to hold it. It was mighty hard quartz, but the
lead grew wider and better defined all the time till I got down ten
feet and had an assay.
The assayer said that I had struck a marble quarry, but it was very
inferior marble after all. Besides I found afterward that it was owned
by Jay Gould and some other tender feet from New York.
Then I relocated the claim and called it The Marble-Top Cemetery
Lode, and went away. Probably if I had gone down on it, the ore
would have shown free milling tombstones and Power's Greek slaves
and all that kind of business, but I felt kind of depressed all the time
while I was at work on it. There was a kind of "Hark from the tombs
a doleful sound," air about the whole mine.
Cummins City still booms. Building lots have gone up to $100
each. This for a place where a few weeks ago the song of the coyote
was heard in the land, and where the valley of the river, and bald
sides of the rugged mountains were unscarred, is a good showing.
The magical power of a mineral excitement to transform the bleak
prairie and the rocky canyon into a thriving village at once, is
something to command our admiration and wonder.
Two months ago, I might say, the little village of Cummins City
was nothing but a little caucus of prairie dogs, and a ward meeting
of woodticks.
Now look at it. Opera houses, orphan asylums, hurdy-gurdies,
churches, barber shops, ice-cream saloons, dog-fights, musical
soirees, spruce gum, bowling-allies, salvation, and three card monte.
Everything in fact that the heart of man could yearn after.
As you drive up Euclid Avenue, you smell the tropical fragrance of
frying bacon, and hear the recorder of the district murmuring with a
profane murmur because his bread won't raise. Here and there along
the river bank, like a lot of pic-nickers, the guileless miners are
panning pounded quartz, or submitting their socks to the old process
for freeing them from decomposed quartzite, and nonargentiferous
clayite. Flying from the dome of the opera house is a red flannel
shirt, while a pair of corpulent drawers of the same ruddy
complexion, is gathering all the clear, bracing atmosphere of that
locality.
As a picturesque tower on the roof of the Grand Central, the
architect has erected a minaret or donjon keep, which is made to
represent a salt barrel. So true to life is this new and unique design,
that sometimes the cattle which roam up and down Euclid Avenue,
climb up on the mansard roof of the Grand Central, and lick the salt
off the donjon keep, and fall over the battlements into the moated
culverin, or stick their feet through the roof and rattle the pay gravel
into the custard pie and cottage pudding.
Bill Root, the stage driver, went out there during the early days of
the camp, and with more or less red liquor stowed away among his
vitals.
William is quite sociable and entertaining, even under ordinary
circumstances, but when he has thawed out his digestion with fire-
water, he talks a good deal. He is sociable to that extent that the
bystander is steeped in profound silence while William proceeds to
unfold his spring stock of information. On the following morning
William awoke with a seal brown taste in his mouth, and wrapped in
speechless misery. There was no cardinal liquor in the camp, (a
condition of affairs which does not now exist,) so that William was
silent. On the amputating table of the leading veterinary surgeon of
Cummins City was found a tongue that had just been removed. It
was really cut from the mouth of a horse that had nearly severed it
himself, by drawing a lariat through it: but the story soon gained
currency that an indignant camp had risen in its might, and visited
its vengeance on William Root for turning loose his conversational
powers on the previous day.
Great excitement was manifested throughout the camp, as William
had not uttered a word as yet. Toward noon, however, a party of
hardened miners, carrying a willow-covered lunch basket with a cork
in the top, arrived in camp, and shortly after that it was ascertained
that the conversational powers of Mr. Root still remained unimpaired.
The chaplain of the camp set a day for fasting and prayer, and the
red flannel shirt on the dome of the opera house was hung at half-
mast in token of the universal sorrow and distress.
This is a true story, which accounts for the awkward manner in
which I have told it.
BANKRUPT SALE OF A CIRCUS.

A
s I write these lines my heart is filled with bitterness and woe.
There is a feeling of deep disappointment this morning that
has cast my soul down into the very depths of sadness. Some
years ago the legislature of Wyoming conceived the stupendous idea
that the circus instead of being man's best friend and assistant in his
onward march through life, was after all a snare and a delusion.
This august body then passed a law that fixed the licenses of
circuses showing in Wyoming Territory at $250, which was of course
an embargo on the show business that, as I might say, laid it out
colder than a wedge so far as Wyoming Territory was concerned.
The history of that law is a history of repeated injury and
usurpation. Our people were bowed down to the earth with the iron
heel of an unjust legislature and forced to drag out the weary years
without the pleasures which come to other States and other
Territories.
In the midst of this overhanging gloom, there were two men who
were not afraid of the all powerful legislature, but boldly lifted up
their voices and denounced with clarion tone and dauntless eye the
great wrong that had been done to our people.
One of these men was a tall, fine-looking man, with piercing eye
and noble mein. He stood out at the front in this unequal war and
with his silvery hair streaming in the mountain zephyrs, he told the
legislature that a justly indignant people would claim at the hands of
her law-makers a full and ample retribution for the tyrannical act.
Judge Blair, Associate Justice of the Supreme Court of Wyoming,
whether at the social gathering or the quarterly meeting, never lost
an opportunity to condemn the unrighteous act or to labor for its
abolishment. He fearlessly adjourned court time after time in order
that the jury might go to Denver or Salt Lake to attend the circus,
and embodied in one of his opinions on the bench the everlasting
truth that "the usurpation of the people's prerogatives by the
lawmakers of any State or Territory, in so far as to deprive them of a
divine right inherent in their very natures, and compelling them to
undergo a slavish isolation from the Mammoth Aggregation of Living
Wonder? and Colossal Galaxy of Arenic Talent, was unjust in its
conception and criminal in its enforcement." See Boggs vs. Boggs,
981. The other dauntless antagonist of the tyrannical law was a
young man with pale seldom hair, and a broad open brow that
bulged out into space like a sore thumb. He was slender in form like
a parallel of longitude, with a nose on him that looked like a thing of
life. This young man was myself.
Together we talked in season and out of season, laboring with the
law-makers with an energy worthy of a better cause.
We met with scorn and rebuffs on every hand, and the cold, hard
world laughed at us, and unfeelingly jeered at our ceaseless
attempts. But we labored on till last winter, the welcome telegram
was flashed over the wires that the despotic measure was no more.
Then there was a general joy all over the Territory. Judge Blair
sang in that impassioned way of his, which makes a confirmed
invalid reconciled to death, and I danced.
When I dance there is a wild originality about the gyrations that
startles those who are timid, and causes the average, unprotected
ballroom-belle to climb up on the platform with the orchestra, where
she will be safe.
Bye-and-bye the young man with the step-ladder and the large oil
paintings, and the long-handled paste brush came to town, and put
some magnificent decalcomania pictures on the bill-boards and
fences; and Judge Blair and I patted each other on the back; and
laughed seven or eight silvery laughs.
But in the midst of our unfettered glee a telegram came from
Denver that the circus that had billed our town had been attached
by the sheriffs. It seems that the elephant had broken into a
warehouse in Denver and had eaten 160 bales of hay, worth $100
each in the Leadville market. The owner of the hay then attached
the show in order to secure pay for the hay.
This necessitated a long delay and finally a sale of the circus.
Everything went, the big elephant and the baby elephant, the band
chariot with a cross-eyed hyena painted on it, the steam calliope
that couldn't play anything but "Silver Threads Among the Gold," the
sacred jackass from North Park, the red-nosed babboon from New
Jersey, the sore-eyed prairie dog from Jack Creek, the sway-backed
grizzly bear from York State, and the second-hand clown from
Dubuque, all had to go.
Then they opened a package of petrified jokes and antique
conundrums that had been exhumed from the ruins of Pompeii. It
seemed almost like sacrilege, but the ruthless auctioneer tore these
prehistoric jokes from the sarcophagus and knocked them down to
the gaping throng for whatever they would bring.
The show was valued at $2,000,000 on the large illustrated
catalogues and bright-hued posters, but after the costs of
attachment and sale had been paid there was only $231 left.
Oh! what a sacrifice. How little there is in this brief transitory life
of ours that is abiding. How few of our bright hopes are ever
realized. How many glad promises are held out to us for the roseate
future that never reach fruition.
GREELEY VERSUS VALLEY TAN.

I
stopped over one day at Greeley on my return. Greeley is the
town after which Horace Greeley was named. It is enclosed by a
fence and embraces a large tract of very fine agricultural land.
The editor of the Tribune had just received a brand new power
press. I asked him to come out and take something. He did not
seem to grasp my meaning exactly.
Afterward I wandered about the town thinking how much dryer
the air is in Greeley than in Denver. The throat rapidly becomes
parched, and yet the inducements for the visitor to step in at various
places and chew a clove or two are very rare indeed. I thought what
a dull, melancholy day the Fourth of July must be in Greeley, and
how tame and dull life must be to those who experience a uniform
size of head from year to year. The blessed novelty of rising in the
morning with a dark brown taste in the mouth and the cheerful
feeling that your head is so large that you can't possibly get it out
through your bed-room door, are sensations that do not enter here.
All the water not used at Greeley for irrigating purposes is worked
up into a light, nutritious drink for the people.
THE ETERNAL FITNESS OF THINGS.

A
n exchange comes out with an article giving the former
residence and occupation of those who are immediately
connected with the Indian management. It will be seen that
they are, almost without an exception, from the Atlantic coast,
where they have had about the same opportunity to become
acquainted with the duties pertaining to their appointment as Lucifer
has had for the past two thousand years to form a warm personal
acquaintance with the prophet Isaiah.
With all due respect to the worthy descendants of the Pilgrim
Fathers, and not wishing to cast a slur upon the ability or the
integrity of the dwellers along the rock-bound coast of New England,
I will say in the mildest manner possible that these men are no more
fit to manage hostile Indians than Perdition is naturally fitted for a
powder house.
A man may successfully cope with the wild and fierce codfish in
his native jungle, or beard the salt water clam in his den, and still
signally fail as an Indian agent. The codfish is not treacherous. He
may be bold, blood-thirsty and terrible, but he will never go back on
a treaty. Who ever heard of a codfish going back on his word? Who
ever heard of a codfish leaving the Reservation and spreading
desolation over the land? No one. The expression on the face of a
codfish shows that he is perfectly open and above board.
We might say the same of the clam. Of course if driven to the
wall, as it were, he will fight; but we have yet to find a single
instance in the annals of history where the clam—unless grossly
insulted and openly put upon, ever made an open outbreak.
This is why we claim that clam culture and Indian management
are not analogous. They are not simultaneous nor co-extensive.
They are not identical nor homogeneous.
I feel that in treating this subject in my candid and truthful way,
perhaps the Administration will feel hurt and grieved; but if so I can't
help it. The great reading public seems to look to me, as much as to
say: "What are your views on this great subject which is agitating
the public mind?" I can't evade it, and even if President Hayes were
an own brother, instead of being a warm, personal friend and
admirer, I would certainly speak right out as I have spoken out, and
tell the whole broad Republic of Columbia that to successfully steer a
hostile tribe of nervous, refractory and irritable Indian bummers past
the rocks and shoals of war is one thing, and to drive a salt water
clam up a hickory tree and kill him with a club, is entirely another
thing.
THEY UNANIMOUSLY AROSE AND
HUNG HIM.

I
was talking the other day with a Laramie City man about
Leadville, he said:
"In addition to the fact of Laramie money being now invested
there, we have sent many good citizens there to build up homes and
swell the boom of the young city. We also sent several there of
whom we are not proud. We still hold them in loving remembrance.
Sometimes we go through the motions of getting judgments against
these men, and making transcripts with big seals on them, and
sending to Leadville to be placed on the execution docket of Lake
county.
"We also sent Edward Frodsham to Leadville. We intimated to him
that life was very brief and that if he wanted to gather a little stake
to leave his family perhaps he could do so faster in Leadville than
anywhere else. So he went. He is there now. He at once won the
notice of the public there and soon became the recipient of the most
flattering attentions. A little band of American citizens one evening
took him out on the plaza, or something of that kind, and hung him
last fall.
"The maple turned to crimson and the sassafras to gold, and when
the morning woke the song of the bunko-steerer and the robin, Mr.
Frodsham was on his branch all right, but he couldn't seem to get in
his work as a songster. There seemed to be a stricture in the glottis,
and the diaphragm wouldn't buzz. The gorgeous dyes of the autumn
sunrise seemed strangely at variance with the gen d'arm blue of Mr.
Frodsham's countenance.
"His death calls to mind one sunny day in the midsummer of '78.
It was one of those days when there is a lull in the struggle for
existence, and the dreamy silence and hush of nature seem to be
concurred in by a committee of the whole.
"It was one of those days when, in the language of the average
magazine poet—

The flowers bloomed, the air was mild,


The little birds poured forth their lay,
And everything in nature smiled.

"But soon from out the silence, bursting upon the quiet air, came
the sharp report of a pistol. Then another and another in rapid
succession. People who were going to trade in that locality suddenly
thought of other places of business where the same articles could be
obtained cheaper. Men who were not afraid of danger in any form,
went away because they didn't want to be called as witnesses on the
inquest.
"The shooting went on for some time. It sounded like the battle'of
the Wilderness. After a while it ceased. A large party of men went
out to gather up the dead and arrange for a grand funeral. But the
remains were not so dead as they ought to be. There were bullet
holes to be sure, penetrating various parts of the combatants, but
the funeral had to be postponed. The sidewalks were plowed up,
signs were riddled and windows shattered, but Edward Frodsham
got off with a bullet hole through the side. The doctor pronounced it
a very close call, but not necessarily fatal. It was a terrible
disappointment to every one. As a shooting match it was a
depressing failure, and as a double funeral it was not deserving of
mention.
"The city council told Frodsham that if he couldn't shoot better
than that he might select some young growing town outside of
Wyoming and grow up with it. He did so. He favored Colorado with
his stirring, energetic presence.
"His grave grows green to-day on the sunny hill-side 'neath the
bending willow, and the soft, sweet breath that is sighing through
the pines and stirring the delicate ferns beside the glassy depth of
the mountain stream, is singing his requiem. [Perhaps, however, I
am rushing the season for Leadville a little; if so the last refrain after
the word 'presence,' may be wrapped up in warm flannels and
stored away till July.]"
RHETORIC VS. WOODTICK.
Camp on the New Jerusalem Mine, June 15.

I
t is impossible at present to say anything about what the future
of this district may bring forth. Every lead shows up beautifully,
and so much so, in fact, that claim owners are working first one
and then another in order to hold them under the new law, which
requires an amount of work to be done on the lead within sixty days
which is generally only required within one year. This new regulation,
which is the act of the district of course, may not stand any very
severe test, but at present the miners are respecting it.
It is severe on me, however, and virtually leaves me out. What I
need is a law that will not ride over and overthrow and freeze out
the poor man. This law is passed in the interest of capital and in
direct violation of the rights and privileges of the great surging mass
of horny-handed workingmen like Brick Pomeroy and myself.
I havn't the time to particularize or describe the different mines
visited, and if I were to do so the chances are that I wouldn't cover
myself or the district with glory.
It is true that I know a foot wall from a windlass, with one hand
tied behind me, but if I were buying a mine I would be about as apt
to purchase a deposit of sulphurets of expectations, showing traces
of free milling telluride of disappointment, as anything else.
The camp has about 300 miners and prospectors now within the
city limits. All up and down the picturesque valley of the swift-
flowing river the low cabin and white tent dot the green sward, and
far above the everlasting hills rear their heads on high, torn by the
Titanic power of giant heat in the days of the long ago.
I said this to Professor Paige, the scientific correspondent of the
Inter-Ocean, who accompanied me. I thought that perhaps it would
tickle him to know that I could reel off a sentence like that, but it
didn't affect him in that way. On the contrary, he seemed to think
that the heat must have affected me in some way.
We climbed Jehu mountain on the evening that we arrived in
camp. We thought it would be the proper thing to do, so we dug our
toe-nails into the prehistoric granite and the micacious what's-his-
name and climbed to the top.
For a few minutes we didn't mind it much and got along first-rate,
trying to make each believe that climbing mountains was our regular
business.
I began to tell the Professor a little harmless lie about how I had
travelled among the Alps, but I didn't finish it. Somehow I felt like
breathing in what atmosphere was not in actual use, but I didn't
have any place to put it.
The air at Jehu Mountain is good enough what there is of it, but it
is too rare. If a man could let out the back straps of his vest and
breathe in the unoccupied atmosphere lying between the Laramie
river and the Zodiac it would be all right, but he can't do it. His
intentions are good, but his skin isn't elastic enough to hold the
diluted fluid.
We climbed up to where we could see the silvery moon rising like
a pale schoolma'am and looking sadly across the dark valley asleep
in night's embrace. I thought it was time to say something.
"Professor," said I, as my brow lighted up like a torchlight
procession, and my voice broke upon the hush and solitude of
evening like the tremulous notes of the buzz saw, "do you not think
that far away amid the unknown worlds which drift through space
and along whose track the drifting systems of planets wheel and
circle through countless ages, while man, clothed in a little brief
authority, cuts such fantastic tricks Before high heaven as makes the
angels weep, regarding himself as the center of the solar system,
planning to frustrate the immutable laws of nature, violating the
prime and co-ordinate common law of universes, going behind the
returns, as it were, trying to peer behind the veil, as I might say,
prognosticating the unprognosticatable, evading the axioms and by-
laws which not only regulate worlds and their creation, but link the
phantasmagoria of diagonal animalculæ and cast broadcast the
oleaginous incongruity of prehistoric usufruct?"
The Professor didn't say anything. He didn't seem to have followed
me. Somewhere the thread had been broken, and the glowing truths
couched in such language as would light up the pages of history and
astronomy, were lost upon the silent air.
The Professor seemed sad and anxious and preoccupied. There
was a look of apprehension and doubt and distrust in his eye, and
he moved about uneasily. I asked him if there were any last words
that I could carry to his friends, and ii there were any little acts of
humanity and friendship which I could perform to render his last
moments more pleasant.
He said there were.

Then he told me that a wood-tick was slowly but surely boring a


hole into his spinal column, near where the off scapula forms a
junction with the nigh one, and asked me to help bring him to
justice.
We should learn from this that heaven-born genius, with the music
of poetic language and aflame with an inspiration almost miraculous,
sometimes makes less impression upon the listener than a little
insect no larger than a grain of mustard seed.
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