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

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

The document provides information about the second edition of 'Guide to Java: A Concise Introduction to Programming' by James T. Streib and Takako Soma, aimed at helping readers quickly learn Java programming fundamentals. It emphasizes concise content, numerous examples, and interactive elements to engage beginners while also covering advanced topics like bit-wise logic and parallel processing. The text is part of the Undergraduate Topics in Computer Science series and is suitable for self-study or as a course textbook.

Uploaded by

nadanacuja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
12 views

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

The document provides information about the second edition of 'Guide to Java: A Concise Introduction to Programming' by James T. Streib and Takako Soma, aimed at helping readers quickly learn Java programming fundamentals. It emphasizes concise content, numerous examples, and interactive elements to engage beginners while also covering advanced topics like bit-wise logic and parallel processing. The text is part of the Undergraduate Topics in Computer Science series and is suitable for self-study or as a course textbook.

Uploaded by

nadanacuja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Read Anytime Anywhere Easy Ebook Downloads at ebookmeta.

com

Guide to Java: A Concise Introduction to


Programming (2nd Edition) James T. Streib

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

OR CLICK HERE

DOWLOAD EBOOK

Visit and Get More Ebook Downloads Instantly at https://ebookmeta.com


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: [email protected].
2
Email: [email protected].

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 [email protected]
October 1, 2022 Takako Soma
[email protected]
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
Another Random Scribd Document
with Unrelated Content
from all care and thought, must necessarily be happy: enjoying their
independence through the labours of those, whose duty it is to
preserve it to them; and who ought never to permit the people to
think that their interests are neglected by their rulers. As to that
exact equality of rights, which is held so dear by a free people; it
cannot be preserved: for the people themselves, however free and
unrestrained they may be, are remarkable for their deference to
many persons; and exercise a great preference as it respects men
and dignities. That which is called equality also, is a most unjust
thing in itself: for when the same honour is enjoyed by the high and
by the low, through a whole people, that very equality must be
unjust; and in those states which are governed by the better class, it
can never happen. These, Lælius, and some other reasons
resembling them, are wont to be urged by those who chiefly praise
that form of government.
XXXV. “But which, Scipio, among those three, do you chiefly approve
of?” said Lælius.
Scipio. “You do well to ask, which chiefly of the three, since
separately I do not approve of any of them; but should prefer to
every one of them, a government constituted out of all three. But if
one of them for its simplicity may be admired, I should approve of
the kingly form, and give it the highest praise. For the name of king
calls up at once the idea of a father, consulting with his citizens as if
they were his own children; and more anxious to preserve them,
than to reduce them to slavery: it being a great advantage to the
weak to be sustained by the exertions and by the foresight of one
pre-eminent and good man. Here however the better class profess
to do the same thing to more advantage, and say there is more
wisdom with numbers than with one, and at the same time equal
justice and faith. But the people call out with a loud voice, that they
choose neither to obey one nor many; that nothing is sweeter to the
beasts of the field than liberty, which is wanting to all who serve
either under the better class or under a king. Thus on the score of
personal attachment, kings attract us. The better class by their
wisdom; and liberty on the side of the people. So that in making the
comparison, it is difficult to say which is preferable.”
L. “I believe it,” said he, “but if you leave this point unfinished, the
other parts of the subject can scarcely be cleared up.”
XXXVI. S. “Let us imitate therefore Aratus, who in his introduction to
a discourse upon high matters, thought it best to begin with Jupiter.”
L. “Why with Jupiter? and what has this discussion to do with the
verses of Aratus?”
S. “Insomuch, that the opening of our debate may be honoured with
the name of him, whom all, learned and unlearned, consent with
one voice, to be the one king of all the gods and men.” “What then!”
said Lælius. “What do you believe in but the things which are before
your eyes?” replied he. “This opinion has been established for the
conduct of life, by those who have had the direction of public affairs;
that the belief might prevail, that one king ruled in heaven, who with
his nod, as Homer says, could tumble down Olympus; and that he
should be considered as the King and Father of all. Great is the
authority for it, and many the witnesses, inasmuch as all have
concurred in it. Nations too have agreed, as we find in the decrees
of princes, that the regal form of government was most excellent,
since they imagine the gods themselves to be under the government
of one king. And if we have been told that this and similar opinions
have sprung from fables and the errors of the ignorant, let us listen
to those who may be considered almost the common teachers of
erudite men; who as it were, saw these very things with their eyes,
which we scarcely are acquainted with, when we hear of them.”
“And who are they?” said Lælius. “They,” replied he, who in their
investigations of the nature of all things, have perceived a design in
the universal structure of this world * * * * * *

[Four pages wanting.]

XXXVII. * * * * * * “But if you desire it Lælius, I can give you


authorities in no wise barbarous, nor of too remote an antiquity.”
L. I should be glad to have them.
S. You are aware that it is now somewhat less than four hundred
years since this city has been governed without kings.
L. That is true; rather less.
S. What then are four hundred years, for the age of a city or state;
is it such a long period?
L. It can hardly be called an adult age.
S. Then there was a king in Rome four hundred years ago?
L. And a very superb one.
S. Who before him?
L. A most just one; and from that period up to Romulus, who
reigned six hundred years from the present time.
S. Then he is not so very remote.
L. Not at all. The institutions of Greece were already on the wane.
S. I submit to you now, whether Romulus was the king of a
barbarous people?
L. If as the Greeks say, all men were either Greeks or Barbarians;
then I am afraid he must be esteemed a king of a barbarous people.
But if that epithet is appropriate to a difference of manners, rather
than to languages, I think the Greeks not less barbarians than the
Romans.” “In relation to the matter of which we speak,” said Scipio,
“it is intelligence we are looking for, rather than men. If a discreet
people therefore, not of a very ancient period, have preferred the
government of kings, I am availing myself of testimony which cannot
be deemed savage, uncivilized, or of a barbarous antiquity.”
XXXVIII. “I perceive Scipio,” said Lælius, “that you are sufficiently
provided with testimony. But with me, as with good judges, sound
argument prevails more than witnesses.” “Make use of an argument
then,” replied Scipio, “which your knowledge of yourself can suggest
to you.” “What knowledge,” said he.
S. Why as when by chance it happens to you to be angry with some
one.
L. That occurs oftener than I could wish.
S. What! when you are in anger, do you suffer your mind to fall
under the domination of that passion?
L. No, so help me Hercules. I rather imitate Archytas, the Tarentine;
who on arriving at his country house, and being greatly offended at
perceiving his orders had been disobeyed, “You are a miserable
wretch,” said he to his farmer, “and I would have you flogged to
death if I were not angry.” “Excellent,” said Scipio. “Archytas wished
to calm his anger by reflection, considering that degree of it which
was not under the control of reason, to be leading on to a sort of
sedition of the mind. To it add avarice, ambition, the passion for
glory, and for sensual pleasures; and it will appear that there exists
in the minds of men, a sort of regal controlling power, to wit,
reflection. For that is the best part of the mind, and where its
authority prevails, there is no room for sensuality, for anger, or for
rashness.
L. So it is.
S. Do you approve therefore of a mind so disposed?
L. There is nothing I admire more.
S. Then you really do not think, reflection being driven away; that
voluptuousness or the angry passions, which are without end,
should have the mastery in all things.
L. Indeed I can conceive of nothing more wretched, than such a
state of mind; nor of a man more debased than when under such
government.
S. You prefer then all parts of the mind, to be under some
government, the government of reflection?
L. I certainly prefer it.
S. Why therefore do you hesitate in your opinion about public
affairs; where if the administration is transferred to many, there will
be no one, as I now understand it, to take the command. And it
seems that if authority is not one thing, it is nothing at all.
XXXIX. “I would ask,” said Lælius, “of what consequence it is to us,
whether one or many, if justice is dispensed by the latter.” “Since I
find Lælius,” said Scipio, “that my witnesses have made no great
impression on you, I shall not desist from making use of yourself as
a witness to prove what I say.” “Me,” said he, “in what way?”
S. Why adverting to the directions you so earnestly gave to your
family, when we were lately at Formianum; to obey only the orders
of one person.
L. Oh! my farmer!
S. Well, at home, I suppose, several are entrusted with the
management of your affairs?
L. No, only one.
S. What, your whole establishment! does no one but yourself
manage it?
L. Just so.
S. Do not you therefore accede to the same conclusion in public
affairs: that the government of a single person, if it is a just one, is
the best?
L. I am brought to the conclusion, and must almost assent to it.
XL. You will be more inclined to that opinion, said Scipio, when
omitting the analogies of one pilot, one physician, who if they are
any way skilled in their arts, ought one to have the control of the
ship; the other of the patient, in preference to many; I come to the
consideration of greater matters.
L. What are they?
S. Are you not aware that the name of king became odious to this
people, on account of the oppression and pride of one man, Tarquin?
L. Yes, I am aware.
S. Then you are aware of what haply in the course of this discussion,
I may find occasion to speak. Tarquin being driven out, the people
exulted with a marvellous sort of insolence of freedom. At one time
driving innocent people into exile; at another, confiscating the
property of many. Next came annual consuls. Then the fasces
prostrated before the people—appeals in all cases. Then the mutiny
of the plebeians—then a complete revolution in every thing, placing
all things in the power of the people.
L. It is as you say. “It is true,” said Scipio—“in peace and tranquillity,
some license may be permitted when there is nothing to fear, as at
sea sometimes, or in a slight fever: but like him who is at sea, when
suddenly the ocean puts on its terrors, or the sick man, when his
complaint oppresses him, and the assistance of one is implored: so
our people in time of peace, interfere in internal affairs, threaten the
magistrates, refuse submission to them, denounce them and
provoke them; yet in war obey them as they would a king, preferring
their safety to the indulgence of their passions. Also in our more
important wars, our countrymen have constantly preferred the
command to be in the hands of one, without any colleague; the
extent of whose power is indicated by his name. For a dictator is so
called on account of every thing being dictated by him. But in our
books, Lælius, you see also that he is called master of the people.”
L. It is so. “Wisely therefore did those ancients,” said Scipio * * * *

[Two pages wanting.]

XLI. * * * When a people is deprived of a just king, as Ennius says,


after the death of one of the best of kings,
“Long were their bosoms moved with deep regret;
Oft they together call upon his manes.
Oh, godlike Romulus! the bounteous gods
What a protector did they give in thee?
Oh father, parent, blood derived from heaven!”
Those whom the laws enjoined them to obey, they did not call lords
or masters; finally, not even kings, but guardians of the country,
fathers and gods. Nor without cause, for what is added,
“Thou broughtest us into the realms of light!”

They thought that life, honour, and every comfort was given to them
by the justice of a king. And the same inclinations would have
remained with their posterity, if the character of their kings had not
changed. But you perceive that kind of government was ruined by
the injustice of one man.
L. I do perceive it, and I am desirous of knowing the course of these
changes, not only in our own country, but in all governments.
XLII. “It will be for you,” said Scipio, “when I shall have given my
opinion of that kind of government which I prefer, to give a more
accurate account of the mutations in governments; although I do
not think them much to be apprehended in the form I am inclined
to. But a regal form of government is particularly and most certainly
exposed to change. When a king begins to be unjust, that form of
government perishes at once. The tyrant is, at the same time, the
worst of all conditions of government, and the nearest to the best.
Whom, if the better class have overturned, which for the most part
happens, the commonwealth possesses that second class of the
three. And this is a sort of royalty; a paternal government of the
principal people, for the benefit of the rest. But if the people cast out
or slay the tyrant; rejoicing in their own deed, they are more
moderate, as long as they know and feel the value of being so, in
their endeavour to protect the commonwealth constituted by
themselves. But when the populace have bent their force against a
just king, and have stripped him of his kingdom; or even, as it
happens very often, have tasted the blood of the better class, and
have prostrated the whole republic in their madness; think not that
the vexed ocean or the wildest conflagration, can be more easily
kept down, than the unbridled insolence of the multitude.
XLIII. Then is produced what in Plato is so clearly described, if I can
in any manner express it in Latin, a thing difficult to be done, but I
will endeavour. “It is then,” he says, “when the insatiable throats of
the people, parched with the thirst of liberty, and led on by rash
demagogues, have greedily drank, not temperate but too unalloyed
draughts of freedom. Then the magistrates and chiefs, unless they
are too lenient and indulgent, permitting them every excess of
liberty; are pursued, impeached, insulted, and called oppressors,
kings, and tyrants.” I think this part of his works is known to you.
L. I am well acquainted with it.
S. Then follows, “Those who pay obedience to the magistrates, are
tormented by the people, are called voluntary slaves. But those
magistrates who affect to be on an equality with the lowest; and
other individuals who strive to abolish all distinction between citizens
and magistrates, are exalted with praises, and overwhelmed with
honours. And in this condition of things, it follows, of course, that
there is an unrestrained license in a government of this kind; so that
every private family is without any government: and this evil extends
even to the beasts. At length the father fears the son—the son
disregards the father: every sort of decency is extinguished, that an
open license may prevail. Nothing distinguishes the citizen from the
stranger. The master pays court to his scholars, that he may be
flattered by them. Teachers are despised by their disciples. Young
persons take upon themselves the authority of aged ones, who
abase themselves to mingle in their games, lest they become odious
and burdensome to them. At last slaves give themselves all sorts of
liberties. Wives assume the privileges of their husbands. Nay the
dogs, the horses, the asses at length are so infected with liberty, and
run kicking about so, that it is absolutely necessary to get out of
their way. Wherefore from this infinite license these things result,
that the minds of the citizens become so scornful and impatient, that
if the least power of government is exercised, they become
exasperated and will not endure it; whence they come to despise
every kind of law, that they may be without the least restraint
whatever.”
XLIV. “You have,” said Lælius, “precisely expressed Plato’s
sentiments.”
S. Returning therefore to the subject of my discourse. “It is from this
very license,” he says, “which they deem to be liberty itself, that a
tyrant springs up as a sapling from a root. For as the destruction of
the better class arises from their overweening power, so this excess
of liberty, effects the slavery of this free people. Thus all extremes of
an agreeable nature, whether in the seasons, or in the fertility of the
fields, or in our natural feelings, are often converted into their
opposites. Especially it occurs in public affairs, where excess of
liberty degenerates into public and individual slavery. Out of such
licentious freedom a tyrant arises, and the most unjust and severe
bondage. For by a people so untameable, or rather so outrageous,
some leader is chosen out of the multitude, in opposition to the
better class, now persecuted and driven from their offices: bold and
dishonest, perversely persecuting those who have frequently
deserved well of their country, and gratifying the people from his
own means and from those of others. To whom, that he may be
freed from all apprehensions on account of his private condition,
authority is given and continued to him. Surrounded too by guards,
as was the case with Pisistratus at Athens, at length he becomes the
tyrant of the very citizens who brought him forward. Who, if he is
subdued by the good, as often happens, the state is regenerated. If
by the bad, then a faction is established, another kind of tyranny.
The same state of things too frequently occurs in that goodly form of
government of the better class, when the vices of the chiefs have
caused them to deviate from their integrity. Thus do they snatch the
government of the commonwealth from each other like a ball—
tyrants from kings—chiefs or the people from tyrants; and factions
or tyrants from them, nor does the same mode of government ever
last a long time.
XLV. These things being so, the regal form of government is in my
opinion much to be preferred of those three kinds. Nevertheless one
which shall be well tempered and balanced out of all those three
kinds of government, is better than that; yet there should be always
something royal and pre-eminent in a government, at the same time
that some power should be placed in the hands of the better class,
and other things reserved for the judgment and will of the multitude.
Now we are struck first with the great equability of such a
constitution, without which a people cannot be free long; next with
its stability. The three other kinds of government easily fall into the
contrary extremes: as a master grows out of a king; factions from
the better class; and mobs and confusion from the people. The
changes too are perpetual which are taking place. This cannot well
happen in such a combined and moderately balanced government,
unless by the great vices of the chief persons. For there is no cause
for change, where every one is firmly placed in his proper station,
and never gives way, whatever may fall down or be displaced.
XLVI. But I am afraid, Lælius, and you too my very discreet and
respected friends, if I continue long in this strain, my discourse will
appear more like that of a master or teacher to you, than as a
conversation with you. Wherefore I will speak of matters known to
us all, and which we have all inquired into long ago. For I am
convinced, and believe, and declare, that no kind of government,
either in the constitution, the planning, or the practice, is to be
compared with that which our fathers have left to us, and which was
adopted by our ancestors. Which if you please, since you have been
desirous that I should repeat things known to yourselves, I will shew
not only what it is, but that it is the best. And with our own
government in view, I will if I can, have a reference to it, in
whatever I may say respecting the best form of government. The
which if I can follow up and effect, I shall, as I think, amply fulfil the
task which Lælius has imposed on me.
XLVII. “It is your task indeed, Scipio,” said Lælius, “most truly yours.
For who in preference to yourself may speak of the institutions of
our forefathers; you being sprung from such illustrious ancestors; or
of the best form of government. The which if we now possess it,
would hardly be so, if any one stood in a more conspicuous situation
than yourself. Or who may venture to advise measures for posterity,
when thou, having delivered the city from its greatest terrors, hast
foreseen for the latest times?”

CICERO’S REPUBLIC.
BOOK II.

I. Perceiving them all now eager to listen to him, Scipio thus began
to speak. “It was old Cato, to whom as you know I was singularly
attached, and whom I admired in the highest degree: to whom,
either through the advice of both my parents, or from my own
prepossession, I devoted myself entirely from my youth; whose
conversation never could satiate me. Such was the experience of the
man in public affairs, which he had for a long time successfully
conducted in peace and war. His manner of speaking too, a
facetiousness mixed with gravity: his constant desire also to improve
himself and others; indeed his whole life in harmony with his
maxims. He was wont to say, that the condition of our country was
pre-eminent above all others for this cause. That among other
people, individuals generally had respectively constituted the
government by their laws and by their institutes, as Minos in Crete,
Lycurgus in Lacedemon. At Athens, where the changes were
frequent, at first Theseus, then Draco, then Solon, then Clisthenes;
afterwards many others. Finally exhausted and prostrated, it had
been upheld by that learned man Demetrius, of Phalera. But that the
constitution of our republic was not the work of one, but of many;
and had not been established in the life of one man, but during
several generations and ages. For he said so powerful a mind had
never existed; from which nothing had escaped; nor that all minds
collected into one, could foresee so much at one time, as to
comprehend all things without the aid of practice and time. For
which reason, as he was wont, so shall my discourse now repeat the
origin of the people; for I have a pleasure in using the very words of
Cato. But I shall more easily follow up my proposition in describing
our own republic to you, in its infancy, its growth, in its adult, and its
present firm and robust state; than if I were to create an imaginary
one, as Socrates is made to do in Plato.
II. When all had approved of this, he proceeded. “What beginning,
therefore, have we of the establishment of a republic so illustrious
and so known to you all, as the origin of the building of this city by
Romulus, born of his father Mars? For let us concede to the common
opinion of men, especially as it is not only well established, but also
wisely recorded by our ancestors, that those who have deserved well
of us on account of our common interest, be deemed not only to
have possessed a divine genius, but also a divine origin. He
therefore after his birth, with Remus his brother, is said to have been
ordered to be exposed on the Tiber, by the Alban king, Amulius,
apprehensive lest his kingdom should be shaken. In which place,
having been sustained by the teats of a wild beast, the shepherds
took him, and brought him up in the labour and cultivation of the
fields. It is said, that when he had grown up, he was distinguished
above the rest by his corporeal strength, and the daringness of his
mind. So that all who then inhabited the fields, where at this day
stands the city, obeyed him willingly and without dissent. And being
constituted their leader, that we may now come from fables to facts,
with a strong force he took Alba-longa, a powerful and well
constructed city in those times, and put the king Amulius to death.
III. Having acquired which glory, he is said first to have auspiciously
thought of building a city, and of establishing a government. In
regard to the situation of the city, a circumstance which is most
carefully to be considered by him, who endeavours to establish a
permanent government; he chose it with incredible skill. For neither
did he remove to the sea, although it was a very easy thing for him
with his forces, to march through the territory of the Rutulians and
Aborigines; neither would he build a city at the mouth of the Tiber,
to which place the king Ancus led a colony many years after. For he
perceived, with an admirable foresight, that maritime situations were
not proper for those cities which were founded in the hope of
continuance, or with a view to empire. First, because maritime towns
were not only exposed to many dangers, but to unseen ones. For
the ground over which an expected enemy moves, as well as an
unexpected one, announces his approach beforehand by many
indications: by sound itself of a peculiarly tumultuous kind. No
enemy can make a march, however forced, without our not only
knowing him to be there, but even who he is, and whence he
comes. But a maritime enemy and a naval force may be before you,
ere any one can suspect him to be come. Nor even when he does
come, does he carry before him any indication of who he is, or from
whence he comes, or even what he wants. Finally by no kind of sign
can it be discerned or determined whether he is a friend or an
enemy.
IV. In maritime cities, too, a sort of debasing and changeable
manners prevail. New languages and new customs are mingled
together, and not only productions but manners are imported from
abroad; so that nothing remains entire of the pristine institutions.
Even they who inhabit those cities are not faithful to their homes,
but with capricious inclinations and longings are carried far from
them; and although their persons remain, their minds are rambling
and wandering abroad. Nor did Carthage or Corinth, long before
shaken, owe their ruin to any thing more than to the unsettled
scattering of the citizens, who abandoned the study of agriculture
and arms through their cupidity of gain and love of roaming. Many
pernicious excitements too to luxury, are brought over the sea to
cities by commercial importation or by conquest. Even the very
amenity of the situation suggests many costly and enervating
allurements. What I have said of Corinth, I know not if I may as
truly say of all Greece; for almost all Peloponnessus lies on the sea,
and except the Phliuntians, there are none whose lands do not
extend to the coast. Beyond Peloponnessus, the Enianes, the
Dorians, and the Dolopians are the only people in the interior. What
shall I say of the islands of Greece? which surrounded with billows,
float about as it were with the institutions and manners of their
cities. These things as I said before, relate to ancient Greece; but of
the colonies brought by the Greeks into Asia, Thrace, Italy, Sicily,
and Africa, except Magnesia alone, which of them is not washed by
the ocean? Thus a part of the Grecian shores seemed to be joined to
the lands of the barbarians. For among the barbarians themselves,
none were a maritime people, except the Etruscans and the
Carthagenians; the one for the sake of commerce, the other for the
sake of piracy. A most obvious cause of the evils and revolutions of
Greece, arising from the vices of these maritime cities, which awhile
ago I slightly touched upon. Nevertheless among these evils there is
a great convenience. The products of every distant nation can be
wafted to the city you inhabit; and in return the productions of your
own lands can be sent or carried into whatever countries you
choose.
V. Who then more inspiredly than Romulus could secure all the
maritime conveniences, and avoid all the defects? placing the city on
the banks of a perennial river, broadly flowing with an equal course
to the sea. By which the city might receive what it wanted from the
ocean, and return whatever was superfluous. Receiving by the same
channel all things essential to the wants and the refinements of life,
not only from the sea, but likewise from the interior. So that it
appears to me, he had foreseen this city, at some period, would be
the seat and capital of a mighty empire: for a city placed in any
other part of Italy would not easily have been able to acquire such a
powerful influence.
VI. As to the native defences of the city, who is so unobservant as
not to have them marked and fixed in his mind? Such is the
alignment and direction of the wall, which by the wisdom of
Romulus, as well of succeeding kings, was bounded on every part by
lofty and craggy hills: so that the only entrance, which was between
the Esquiline and the Quirinal hills, was defended by a huge mound,
and a very wide ditch. The citadel, surrounded by this craggy and
seemingly hewn rock, had such a gallant position, that in that
furious invasion of the terrible Gauls, it remained safe and intact. He
choose also a place abounding in springs, and salubrious even in a
pestilent region. For there are hills which while they enjoy the
breezes, at the same time throw a cool shade upon the vallies.
VII. These things were done too with great celerity. For he not only
founded a city, which he ordered to be called Rome, from his own
name; but to establish it, and strengthen the power of the people
and his kingdom, he adopted a strange and somewhat clownish
plan, but worthy of a great man, whose providence extended far into
futurity. When the Sabine virgins, descended from respectable
families, were come to Rome to see the games, whose first
anniversary he had then ordered to be celebrated in the circus, he
ordered them to be seized during the sports, and gave them in
marriage to the most honourable families. For which cause, when
the Sabines had made war upon the Romans, and when the success
of the battle was various and doubtful, he struck a league with
Tatius, king of the Sabines, at the entreaty of the very matrons who
had been seized: in consequence of which he admitted the Sabines
into the city: and mutually having embraced each others sacred
rites, he associated their king with him in the government.
VIII. After the death however of Tatius, all the power came back into
his hands: although he had admitted some chiefs into the royal
council with Tatius, who were called fathers, on account of the
affection borne to them. He also divided the people into three tribes,
named after himself, after Tatius, and after Lucumon, a companion
of Romulus, who had been slain in the Sabine war: and into thirty
curia, which curia he called by the names of those from among the
Sabine virgins seized, at whose entreaties the peace and league had
been formed. But although these things were done before the death
of Tatius, yet after that event, his government became much better
established, aided by the authority and counsel of the fathers.
IX. In the which he saw and judged as Lycurgus at Sparta had done,
a little while before him: that states were better governed by
individual command and royal power, if the authority of some of the
better class were added to the energy of that kind of government.
Thus sustained, and as it were propped up by the senatorial
authority, he carried on many wars very successfully with his
neighbours; and appropriating to himself no part of the spoil, he
never ceased to enrich the citizens. At that time Romulus paid in
most things attention to auspices, a custom we still retain, and
greatly advantageous to the republic. For he built the city under the
observance of auspices at the very beginning of the republic; and in
the establishment of all public affairs, he chose an augur from each
of the tribes to assist him in the auspices. He also had the common
people assigned as clients to the principal men, the utility of which
measure I will afterwards consider. Fines were paid in sheep and
cattle: for then all property consisted in flocks, and in possessions of
lands, whence the terms pecuniary[12] and landholders[13] were
derived. He did not attempt to govern by severity or the infliction of
punishments.
X. When Romulus had reigned thirty-seven years, and had
established those two excellent foundations of the state, the
auspices and the senate, he obtained this great meed: for when he
had disappeared upon a sudden obscuration of the sun, he was
deemed to have been placed among the number of the gods. A
belief which no mortal had ever inspired without the greatest pre-
eminence in virtue. And this is most to be admired in Romulus, that
others who are said to have been deified out of the mortal state,
lived in the less civilized ages of man, when the proneness to fiction
was great, and the unenlightened were easily led to believe in it. But
during the period of Romulus, not quite six hundred years ago, we
know that learning and literature existed, and that the ancient errors
peculiar to the uncultivated ages of mankind were removed. For if
Rome, according to an investigation of the annals of the Greeks, was
built in the second year of the seventh olympiad; the reign of
Romulus occurred at that period when Greece was full of poets and
musicians; and when but little faith would be given to fabulous
stories, unless they were concerning very ancient things. For one
hundred and eight years after Lycurgus ordained laws to be written,
the first olympiad was established: which through a mistake in the
name, some have thought to be founded by Lycurgus. Homer,
however, by those who take the lowest period, is made to precede
Lycurgus about thirty years. From which it may be gathered that
Homer flourished many years before Romulus. So that there was
scarce room in so intelligent an age, and amid so many learned
men, for any one to establish fictions. Antiquity sometimes has
received fables crudely devised, but that age already refined, and
especially deriding improbable events, has rejected * * *

[About 230 letters wanting.]

* * * * Simonides was born in the fifty-sixth olympiad, by which the


credit given to the immortality of Romulus may be more easily
understood, seeing that the institutions of society were then so well
established, organized, and known. But really so great was the force
of his genius and virtue, that what men would have given no credit
to for many ages in favour of any other man, was believed of
Romulus upon the evidence of Proculus Julius, a countryman, who at
the instigation of the fathers, in order to repel from themselves
every suspicion of the death of Romulus, is said to have declared in
the assembly, that he had seen Romulus on that mount which is now
called Quirinal; and that he had commanded him to request the
people to erect a temple for him upon that hill; that he was a god,
and was called Quirinus.
XI. “Do not you perceive therefore a new people not only sprung
from the wisdom of one man, and not left crying in leading strings,
but already grown up, and almost an adult?” “Indeed we perceive
it,” said Lælius, “and that you have entered upon a new method of
discussion, which is no where to be found in the writings of the
Greeks. For that pre-eminent person,[14] whom no one has excelled
in writing, has imagined to himself a situation, in which he might
construct his city after his own pleasure: admirable enough perhaps,
but foreign to the conduct and the manners of men. Others have
discussed the subject in relation to the kinds and causes of
governments, but not under any particular example of a form of
government. You seem to me to be about to do both, for according
to your method, you appear to prefer to attribute to others what you
yourself have observed, than to imagine a state of things, as
Socrates is made to do in Plato. And these matters respecting the
foundation of the city, you suppose to be part of a system, which
were only adopted by Romulus through necessity or chance. And
your discourse is not of a desultory kind, but concerning a particular
commonwealth. Wherefore proceed as you have begun, for already I
perceive you are about to follow on with the other kings, as
perfecting the government.”
XII. “Wherefore,” said Scipio, “when the senate, which Romulus had
instituted out of the better class, and which had been so much
favoured by the king, as to cause them to be called fathers, and
their children patricians; endeavoured after the death of Romulus, to
carry on the government itself without any king; the people would
not endure it, and in their regret for Romulus did not cease to
demand a king. Upon which the leading men prudently imagined a
mode of interregnum, new and unknown to other nations. So that
until a regular king was proclaimed, neither the city should be
without a king, nor with one too long a period. Fearing lest from too
long an enjoyment of the government, the interrex should be
reluctant to lay it down, or strong enough to maintain himself in it.
Even in these times, this new people perceived what had escaped
the Lacedemonian Lycurgus; who esteemed it best not to choose a
king, if this were indeed in the power of Lycurgus to do, but rather
to be governed by any one whatever descended from the race of
Hercules. But our ancestors, rude as they appear to have been,
thought it behoved them rather to look to royal wisdom and virtue,
than to descent.
XIII. When the great fame of Numa Pompilius had reached them,
the people, leaving aside their own citizens, called in by the
authority of the fathers, a king not born among them, and sent to
the Curians for a Sabine to reign over Rome. When he arrived,
although the people had decided that he should be king in the
conventions of the curia, nevertheless he himself had a law passed
in the curia concerning his own power; and as he saw the Romans
through the institutions of Romulus were eager after warlike
pursuits, he deemed it proper to wean them somewhat from that
propensity.
XIV. And first, the lands which Romulus had acquired in war, he
divided equally among the citizens; and pointed out to them, that
without depopulating and pillaging, they might possess all the
necessaries of life, by the cultivation of their lands. He inspired them
also with the love of peace and repose, under which justice and
good faith most kindly flourish; and under the protection of which,
the cultivation of the fields, and the gathering of the harvest are
most secure. The same Pompilius having established auspices of a
superior kind, added two augurs to the ancient number, and placed
five priests over sacred things from the class of the chief men. And
having established those laws which we possess in our monuments,
he softened, by the ceremonies of religion, minds which were
inflamed by the habit and inclination of making war. He added also
Flamens, Salii, and Vestal Virgins; and established with great
solemnity all the branches of religion: ordaining many ceremonies to
be learnt and observed, but without any expense. Thus he increased
the duty of religious observances and diminished the cost of them.
In like manner he established markets, games, and all the stated
occasions of assembling the people together. Under which
institutions, he recalled the minds of men become fierce and wild in
warlike pursuits, to humanity and gentleness. When he had reigned
thirty-nine years in the most perfect peace and concord, (in this we
follow principally our friend Polybius, than whom no one was more
accurate in ascertaining periods,) he departed from life; having
strengthened every thing for the endurance of the government, by
those two conspicuous virtues, religion and clemency.
XV. When Scipio had spoken these words. “Is it true, Africanus,” said
Manilius, “what tradition has brought down to us, that this king
Numa was a disciple of Pythagoras, or is it certain he was a
Pythagorean? For often we have heard this, as having been declared
by old people, and understand it also to be the common opinion; yet
we do not see it sufficiently proved by the authority of the public
annals.” “It is false,” replied Scipio, “entirely so Manilius! Not false
alone, but ignorantly and absurdly false; for the mendacity of those
assertions is not to be endured, which we not only see are not true,
but which could never have been so. It was in the fourth year of the
reign of Lucius Tarquinius Superbus, that Pythagoras is ascertained
to have come to Sybaris and Crotona, and those parts of Italy. For
the sixty-second Olympiad announces that very arrival of
Pythagoras, and the beginning of the reign of Superbus. From which
it may be understood by a calculation of the reigns, that Pythagoras
touched first at Italy about a hundred and forty years after the death
of Numa. Nor has this fact, by those who have very diligently
investigated the annals of the times, ever been thrown into any
doubt.” “Immortal gods,” said Manilius, “how inveterate and great is
the error of men! Nevertheless, I can be very well pleased in the
belief, that our intelligence has not been derived from abroad, and
through foreign arts, but from natural and domestic virtues.”
XVI. “You will distinguish that more clearly,” said Africanus, “when
you perceive how the commonwealth advances and comes to the
greatest perfection by a straight forward and natural course. For in
this also the wisdom of our ancestors is to be praised; that many
things derived from abroad, have been rendered much more perfect
by us, than they were from whence they were brought, and where
they first had existence. You will see also that the greatness of the
Roman people has not been confirmed by chance, but by wisdom
and discipline. Fortune indeed being propitious to us.
XVII. King Pompilius being dead, the people upon the proposition of
an interrex, created Tullus Hostilius king, in the conventions of the
curia; and he, after the example of Pompilius, consulted the people
in the curia, concerning his power. His military glory was great, and
important warlike affairs took place. He constructed edifices for the
senate and the curia, and surrounded them with military trophies.
He established a law also for the declaration of war, which most
justly decreed by him, he made more sacred by the solemnity of
Heralds: so that every war which was not proclaimed and declared,
was deemed to be impious and unjust. And observe how wisely our
kings saw that some sort of deference must be paid to the people. I
might say many things on that head. Tullus indeed did not venture
to appear with royal insignia unless at the command of the people.
For in order that it might be lawful for him to be preceded by twelve
lictors with their fasces * *

[Two pages wanting.]

XVIII. * * * * * “The government which your discourse is


establishing, does not creep, but rather flies towards perfection.” S.
“After him, Ancus Martius, grandson to Numa Pompilius by his
daughter, was made king by the people, who had his elevation
sanctioned by a law of the curia. Who having conquered the Latins
in a war, incorporated them into the state. He also added the
Aventine and Cælian Mounts to the city. The lands too which he had
conquered he distributed, and made a public domain of all the
forests he had taken on the sea coast. He built a city at the mouth
of the Tiber, and planted a colony there. When he had thus reigned
twenty-three years, he died. “This king also is to be praised,” said
Lælius, “but the Roman history is obscure: for although we know
who was the mother of this king, we do not know who was his
father.” S. “So it is” said he, “but generally the names of the kings
only of those times are conspicuous.”
XIX. “But it is here that we first perceive the city to have become
more intelligent by extrinsic information. For not a gentle stream
flowed from Greece into this city, but an abundant flood of arts and
knowledge. It is stated that one Demaratus, a Corinthian, a principal
man, and of much honour and authority in his own city, and of an
easy fortune, not being able to endure Cypselus, the tyrant of the
Corinthians, fled with a great deal of money, and betook himself to a
flourishing city of Etruria, among the Tarquinians. When he had
heard that the domination of Cypselus was confirmed, being an
independent and powerful man, he renounced his country, and was
received a citizen by the Tarquinians: and in that city he fixed his
home and establishment. Where when he had begotten two sons
from one of the Tarquinian matrons, he instructed them in all the
arts after the manner of the Greeks * * * *

[Two pages wanting.]


XX. * * * * * He was well received in the city, and became intimate
with king Ancus on account of his learning and liberal knowledge. So
much so that he shared all his counsels, and might be deemed even
a partner in his kingdom. For there was a great affability in him, and
an extreme readiness in aiding, protecting, and doing liberal acts to
every citizen. Martius therefore being dead, L. Tarquinius was
created king by the united suffrages of the people; for thus he had
changed his name from his Grecian one, that in every thing he might
be seen to imitate the manners of the people. Having caused his
accession to be confirmed by a law, he doubled the pristine number
of the fathers; calling those whose opinions he first asked, ancient
fathers of the greater families; and those whom he had admitted, he
called the lesser families. Then he established the knights; after the
manner that has obtained unto our day. He could not change the
names of the Titienses, of the Rhamnensians, or the Luceres, when
he wished to do so; because Attus Nævius being then Augur in great
reputation, would not consent to it. We see the Corinthians chose
formerly to assign cavalry for the public service, and to have their
expenses defrayed by taxes on orphans and widows. But to the old
troops of horse he added others, and made twelve hundred knights.
He doubled this number after he had subdued the Equi in war, a
powerful and ferocious race, which threatened the affairs of the
Roman people. And when he had driven the Sabines from the walls
of the city, he scattered them with his horse and conquered them. It
is he whom we understand to have instituted the great games,
which we call Roman, and to have made a vow during the Sabine
war, while in battle, that he would raise a temple on the capitol to
the great and good Jupiter. He died when he had reigned thirty-eight
years.
XXI. “Now,” said Lælius, “is that saying of Cato very certain, that the
constitution of the state is not the work of one moment or one man:
for it is evident how great an accession of good and useful
institutions occurred under each reign. But he comes next, who
appears to me to have looked farther than them all into the nature
of government.” “So it is,” said Scipio, “for after him Servius Sulpicius
is stated first to have reigned without the command of the people.
He is said to have been born of a Tarquinian slave: she having
conceived him by some client of the king. Brought up among the
number of the servants, when he attended at the royal table, he did
not suppress those sparks of genius, which even then shone forth in
the boy: so shrewd was he in every thing, whether in business or
conversation. Wherefore Tarquin, who at that time had only young
children, became so attached to Servius, that he was generally
thought to be his son; and with great pains instructed him in all
those arts, which he himself had been taught, after the very superior
manner of the Greeks. But when Tarquin had perished by the plots
of the sons of Ancus, Servius, as I before said, began to reign, not
by the command, but by the assent and sufferance of the people.
For when Tarquin was falsely said to be alive, and sick from the
effects of his wound; he declared the law in royal pomp, and
discharged debtors with his own money. Conducting himself with
much courtesy, he declared that he pronounced the law at the
command of Tarquin. He did not commit himself to the fathers, but
Tarquin being buried, he conferred with the people about himself,
and being authorised to reign, he had his accession confirmed by a
law of the curia. And first he avenged himself by war, for injuries
received from the Etruscans, * * * * * *

[Two pages wanting.]

XXII. * * he inscribed eighteen centuries of horse in the great


register. Afterwards having set apart a great number of equestrians
from the mass of the whole people, he distributed the rest of the
citizens into five classes, and divided the old from the young: and
classed them in such a manner, that the suffrages were not in the
power of the multitude, but of the landed proprietors. He was
careful of what ought always to be observed in government; that
numbers alone should not have the ascendency. Which classification
if it were unknown to you, should be explained by me. You will
perceive the plan was such, that the centuries of horse with six
suffrages, (a century being added from the carpenters on account of
their great utility to the city,) and the first class, make eighty-nine
centuries: to which from the one hundred and four centuries, for so
many remain; if only eight are added, the whole power of the people
is obtained: and the much greater multitude comprehended in the
ninety-six centuries remaining, is neither excluded from voting, lest it
should seem disdainful; nor is it made too effective, lest it should be
dangerous. In the which matter he was very circumspect even as to
terms and names. Those from among the wealthy he called
“assiduos”[15] from paying their taxes in money. Those who
possessed no more than one thousand five hundred pieces of brass,
or those who were polled in the register without any possessions
whatever, he called proletaries; as if progeny only; that is, as if
nothing but population might be expected from them. But of those
ninety six centuries, more were enumerated in one century, than
almost in the whole first class. Thus the right of suffrage was not
prohibited to any one by law, and that class had a greater weight of
suffrage, which had most at stake in the preservation of good
government. As to public criers, men hired for parade, clarion
players, horn players, and proletaries, * * * *

[Four pages wanting.]

XXIII. * * * * * Was[16] sixty-five years more ancient, being built


thirty-nine years before the first olympiad. And the very ancient
Lycurgus had the same thing in view. This equality therefore, and
this triple nature of public affairs appears to me to have been
common to us and to those people. But what is peculiar in our
republic, and than which nothing can be more admirable, I will look
very critically into if I am able; as nothing similar is to be found in
any government. For these things which I have adverted to, were so
mingled in this state, and among the Lacedemonians, and the
Carthagenians, that they were not properly balanced. For in
whatever government any one man enjoys perpetual power,
especially royalty, although even a Senate may exist in it, as was the
case at Rome under the kings, and in the laws of Lycurgus at Sparta;
and even granting the people some share in the government, as was
the fact under our kings: still that royal name will stand pre-eminent,
nor can a government of that kind be any thing but a kingdom, or
be called otherwise. But such a form of government is especially
subject to change for this reason; that it easily falls into the most
unprofitable courses, precipitated thereunto by the vices of one
man. For the royal form of government itself, not only is not to be
condemned, but I know not whether it is not greatly to be preferred
to the other simple forms, if I could approve of any simple form of
government. But only as long as it preserves its proper character,
which is that the safety, the equality, and tranquillity of the citizens,
are to be preserved by the justice, the wisdom, and the perpetual
power of one man. Many things however are altogether wanting to a
people subject to a king. Liberty among the first: which is not that
we may live under a just master, but under none at all. * * *

[Two pages wanting.]

XXIV. For some time fortune prosperously accompanied this unjust


and cruel master in the administration of affairs. He subdued all
Latium in war, and took Suessa, an opulent and well stored Pometian
city. Enriched with great spoils of gold and silver, he accomplished
the vow of his ancestor in the building of the capitol. He established
colonies, and according to the institutions of those from whom he
had derived his origin, he sent magnificent gifts, as offerings of his
spoils, to Apollo at Delphos.
XXV. Here the very circle is set in motion, whose natural movement
and revolution you learn to distinguish from the beginning. For the
very head of discretion in civil matters, upon which all our discourse
turns, is to observe the ways and bendings of public affairs; so that
when you perceive what way any thing inclines, you may either keep
it back, or meet it by opposing other things to it. For the king of
whom I speak, having stained himself first with the murder of a
good king, no longer preserved his integrity of mind, and wished to
inspire fear himself, because he dreaded every sort of punishment
for his wickedness. Afterwards borne up with his victories and riches,
he exulted with insolence, and imposed no restraint on his own
conduct, or the licentiousness of his followers. Wherefore when his
eldest son had used violence with Lucretia, the wife of Collatinus,
and daughter of Tricipitinus, and the noble and chaste woman had
inflicted death upon herself on account of that injury; L. Brutus, a
man pre-eminent in mind and courage, released his fellow citizens
from that unjust yoke of a cruel slavery: who, although he was a
private citizen, sustained the whole government, and was the first
who taught in this city, that no man was to be considered
insignificant, when the public liberties were to be preserved. Under
which leader and head, the whole city being in commotion, as well
with the recent complaints of the family and kindred of Lucretia, as
with the remembrance of the many wrongs done by the haughtiness
of Tarquin himself, and his sons; the banishment of the king, his
children, and his whole race was pronounced.
XXVI. Do not you perceive then how a master may spring out of a
king, and how a form of government from being good, may become
the very worst, through the vice of one man. This is that master
over the people, whom the Greeks call tyrant; him only they esteem
a king, who consults like a parent with the people, and preserves
those over whom he is placed, in the most prosperous condition of
life. A sort of government very good as I have said, but bordering
upon and inclining to a very pernicious one. For when this king
deviates into unjust rule, at once he becomes a tyrant, and an
animal more hideous, more destructive, and more odious, in the
eyes of gods and men cannot be conceived: surpassing, although in
the human form, the most monstrous wild beasts in cruelty. How can
he be rightly called a man, who observes no fellowship of humanity
with his fellow citizens, no communion of law with the whole race of
man? But a more proper place to speak of this will occur, when
circumstances will suggest to us to speak of those, who have sought
to usurp the Government over free cities.
XXVII. You have here then the origin of a tyrant, for the Greeks
would have this to be the name of an unjust king. Our ancestors
indeed have called all who have had an exclusive and perpetual
dominion over the people, kings. Thus Spurius Cassius, M. Manilius,
and Spurius Mælius, are said to have wished to establish a kingdom,
and even * * * * * *

[Two pages wanting.]

XXVIII. Lycurgus gave the name of ancients[17] at Lacedemon, to


that too small number of twenty-eight, to whom he wished the
whole authority of counsel to be confided, while the sole command
should be held by the king. Wherefore our ancestors translating and
adopting that term, those whom he called ancients, they called a
senate: as we have already stated Romulus to have done with the
select fathers. Nevertheless, the royal title, and its strength and
power were always pre-eminent. Impart too something of power to
the people, as was done by Lycurgus and Romulus, and you will not
satisfy them with freedom, but you will inflame them with the
passion of liberty, when you have only permitted them to taste of
power. The fear indeed will always hang over them, lest they should
have an unjust king, which generally happens. The fortune therefore
of a people is, as I said before, very uncertain, which is placed in the
will or conduct of one man.
XXIX. Wherefore this first form, example, and origin of a tyrant, is
found by us in that very government which Romulus instituted with
auspices, and not in that, which Plato says Socrates imagined to
himself in that peripatetic discourse. And as Tarquin subverted the
whole fabric of royalty, not because he grasped a new sort of
authority, but because he made a bad use of it; so let us oppose to
him another; a good man, wise and expert in every thing useful and
dignified in civil life: a tutor and steward as it were of the
commonwealth, for so may be called whoever is the ruler and
governor of a state. Imagine to yourselves that you recognise such a
man; one who can protect the state, both by his counsel and
conduct. And since the name of such a man has not been alluded to
in this discourse, and that a character of this kind will be frequently
treated of in what remains to be said * * * * * *
[Twelve pages wanting.]

XXX. * * * * * * Plato described a state more to be desired, than to


be hoped for upon the smallest scale. He did not constitute things as
they might exist, but in such a manner as the nature of civil affairs
might be considered. As to myself, if in any way I am able to
accomplish it, with the same principles which he had in view, I will
look, not into the picture and shadow of a state, but into a most
powerful republic; that I may appear to touch, as it were, the true
cause of every public good and evil. After these two hundred and
forty years of regal government, and indeed a little more, including
the interregnums, Tarquin being banished, the royal title was as
odious to the Roman people, as it had been regretted after the
death, or rather the disappearance of Romulus, and as much as they
wanted a king then, in like manner, after the expulsion of Tarquin,
they could not endure the name of one.
XXXI. Under this feeling our ancestors then expelled Collatinus, who
was innocent, through apprehension of his family connexions, and
the other Tarquins from disgust at their names. From the same
cause too P. Valerius ordered the fasces to be lowered when he
began to speak before the people; and had his building materials
taken to the foot of the Velia, as soon as he perceived the suspicions
of the people to be raised on account of his having begun to build in
a more conspicuous part of the Velia, the very place where King
Tullus had dwelt. He also, in the which he greatly deserved the name
of Publicola, had that law passed for the people, which was first
carried in the meetings of the centuries, that no unfriendly
magistrate should put to death, or flog any Roman citizen for
appealing. The pontifical books however declare appeals to have
existed under the kings; the augural records show it also. The twelve
tables too in many laws indicate that it was lawful to appeal from
every judgment and punishment. What is brought down to us by
tradition, of the Decemvirs who wrote the laws, being created
without any appeal, sufficiently shows that the other magistrates
had not the power of judging without appeal. The law, too, which for
the sake of concord passed in the consulate of Lucius Valerius
Potitus, and M. Horatius Barbatus, men very justly popular;
sanctioned the principle, that no magistrate should be created
without appeal. Nor did the Portian laws, which are three as you
know of the three Portii, contain any thing new except the
confirmation of it. Publicola therefore, upon the law in favour of
appeal being published, immediately ordered the axes to be taken
from off the fasces, and the next day had Sp. Lucretius appointed to
him as his colleague: being his superior in age, he ordered his own
lictors to go to him; and first established the custom that lictors
should precede each of the consuls, alternate months, lest the
ensigns of command among a free people, should be as numerous
as in a kingdom. There was something more than mediocrity in this
man, as I consider him: who having given a moderate liberty to the
people, preserved more easily the authority of the chiefs. Nor do I
repeat these things, now so old and obsolete to you, without cause.
I select examples of men and things drawn from illustrious persons
and times, to which the remainder of my discourse shall be applied.
XXXII. In such a manner the senate governed the commonwealth in
those days, that though the people were free, still they interfered in
but few things. Public affairs were principally managed under the
authority, and by the rules and customs of the senate. And although
the consuls possessed their power only for a year, it was royal in its
nature and effect. And this was strenuously preserved, as necessary
to the preservation of the influence of the nobles and principal
chiefs, that nothing should be established in the meetings of the
people, which was not sanctioned by the authority of the fathers. In
these very times too, T. Larcius was appointed dictator, about ten
years after the first consuls. A new kind of authority, very much
resembling, as we perceive, the royal power. But all great matters
were conducted by the authority of the principal men, the people
submitting to it. And great events took place in those times in war,
under renowned men in the supreme command, from among those
very dictators and consuls.

You might also like