Maria Litvin Gary Litvin
Object-Oriented
Programming
and
DEL eT Todt ges9Fourth AP Edition
Java
Methods
Object-Oriented Programming
and
Data Structures
Maria Litvin
Prilps Academy, Andover, Massachusets
Gary Litvin
Skylight Sofware, Inc.
Skyjight Publishing
‘Andover, MassachusettsSkylight Publishing
9 Bartlet Street, Suite 70
Andover, MA 01810
web: www.skylit.com
e-mail:
[email protected]
[email protected]
Copyright © 2022 by Maria Litvin, Gary Litvin, and
Skylight Publishing
All rights reserved. No part of this publication may be reproduced,
stored in a retrieval system, or transmitted, in any form or by any means,
electronic, mechanical, photocopying, recording, or otherwise, without
the prior written permission of the authors and Skylight Publishing,
Library of Congress Control Number: 2021944689
ISBN 978-0-9972528-2-8
* AD and Advanced Placement are registered trademasks of The Collage Board, which wae
not involved inthe production of and does not endorse ths book.
‘The names of commercially available software and products mentioned in this book are
used for identification purposes only and may be wademacks or registered trademarks
‘owned by eomporstions and ether commercial entities. Skylight Publishing and the authors
hhave no affiliation with and disclaim any sponsorship or endorsement by any of these
product magufscrures or trademadk owners
(Oracle, Java, and Java logos are trademarks or registered trademarks of Oracle Corporation
andlor ite affiliates inthe U.S. and other coustrics,
SCRABBLE® is the registered trademark of HASBRO in the United States and Canada and.
‘of LW. Spear and Sons, PLC, a subsidiary of Mattel, Inc. outside the United States and
Canada
12345678910 27 26 25 24 23 22
Printed in the United States of AmericaBrief Contents
Preface xiii
How to Use This Book xii
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 8
Chapter 9
Chapter 10
Chapter 11
Chapter 12
Chapter 13
Chapter 14
Chapter 15
Chapter 16
Chapter 17
Chapter 18
Chapter 19
Chapter 20
Chapter 21
Appendices
Hardware, Software, and the Intemet 1
An Introduction to Software Engineering 11
Java Syntax and Style 43
Objects and Classes 65
Data Types, Variables, and Arithmetic 95
Boolean Expressions and if-else Statements
Algorithms and Iterations 177
Stings 207
Amays 235
Implementing and Using Classes. 271
java.util.ArrayList 319
Class Hierarchies 341
Algorithms and Recursion 365
Searching and Sorting 383
Streams and Files 413
Graphies 429
GUI Components and Events 435
Mouse, Keyboard, Sounds, and Images 443
Recursion Revisited 447
Sets and Maps 475
Computing in Context 495
*
Solutions to Selected Exercises
Index 499
133
tii1. Hardware / Software ®
2. Software Engineering
3. Syntax and Style
4. Objects and Classes
APCSA
Exam
5. Arithmetic
6. Boolean /
7. Algorithms / Iterations File /O
Graphics
8. Strings SUI
‘ v
9. Arrays 18. Streams and Files 49, Recursion Revisited
! H
10. Classes: Details 16. Graphics = 20. Sets and Maps
At seraynise 17. GUI/ Events we
7
L
12. Class Hierarchies 78. MoneSomdsinages ©
13. Algorithms / Recursion
14, Searching and Sorting
v
21. In Context / Ethics ©Contents
Preface xiii
How to Use This Book xvii
Chapter 1. Hardware, Software, and the Internet 1
1.1 Prologue 2
7 Hardware Overview ‘& www.skylit.com/javamethods4/
1.2.1 The CPU
JM-Chapterd1 www pdf
12.2, Memory
1.2.3 Secondary Storage Devices
1.2.4 Input and Output Devices
13 Software Overview
14 What Do Software Engineers Do?
1.5. Representation of Information in Computer Memory
15.1 Numbers
1.5.2. Characters
1.6 — The Internet
17 Summary
Exercises 5
Chapter 2. An Introduction to Software Engineering ul
2.1 Prologue 12
2.2 Compilers and Interpreters 14
2.3 Software Components and Packages 21
2.4 Lab: Three Ways to Say Hello 22
2.5 Object-Oriented Programming 29
2.6 Lab: More Ways to Say Hello 32
2.7 Summary 37
Exercises 38vi CONTENTS
Chapter 3. Java Syntax and Style 43
3.1 Prologue 44
3.2 AnExample ofa Class 45
3.3. UsingComments 48
3.4. Reserved Words and Programmer-Defined Names 50
3.5 Syntax vs. Style 53
3.6 Statements, Blocks, Indentation 57
3.7 Lab: Correcting Syntax Errors $8
3.8 Summary 60
Exercises 61
Chapter 4. Objects and Classes 65
4.1 Prologue 66
42 Case Study: A Drawing Program 67
43 Classes 70
44 Fields, Constructors, and Methods 75
4.5 Inheritance 81
4.6 Case Study and Lab: Balloons of AllKinds 85
47 Summary 88
Exercises 90
Chapter 5. Data Types, Variables, and Arithmetic 95
5.1 Prologue 96
5.2 Declaring Fields and Local Variables 98.
5.3. Primitive Data Types 102
5.4 Strings 104
5.5 Constants 104
5.6 Scope of Variables 107
5.7 Arithmetic Expressions 109
5.8 Compound Assignment and Increment Operators 112
59 — Avoiding Division by Zero Errors 114
5.10 Converting Numbers and Objects into Strings 115
S11 Lab: Pie Chart 119
5.12 Themath Class 121
5.13 Calling a Method from main 122
5.14 Summary 123
Exercises 125CONTENTS: vii
Chapter 6. Boolean Expressions and if-else Statements 133
6.1 Prologue 134
62 if-else Statements 136
63 boolean DataType 137
64 Relational Operators 138
65 Logical Operators 140
6.6 Order of Operators 142
6.7 Short-Circuit Evaluation 143
68 if-else-ifandNested if-else 144
69 Case Study and Lab: Rolling Dice 149
6.10 The switch Statement 158
6.11 Enumerated Data Types 161
6.12 Case Study and Lab: Rolling Dice Concluded 163
6.13 Summary 167
Exercises 169
Chapter 7. Algorithms and Iterations 77
7.1 Prologue 178
7.2 Properties of Algorithms 179
7.3 The while and for Loops 184
74 Thedo-while Loop 188
7.5 returnandbreak inLoops 189
7.6 NestedLoops 191
7.7 Case Study: Euclid’s GCF Algorithm 194
7.8 Lab: Perfect Numbers 196
7.9 Summary 197
Exercises 199
Chapter 8. Strings 207
8.1 Prologue 208
8.2 Literal Strings 208
83 String Constructors and Immutability 209
84 string Methods 212
8.5 Formatting Numbers into Strings 219
8.6 Extracting Numbers from Strings 222
8.7 Character Methods 223
8.8 Lab: Lipograms 224
8.9 The StringBuffer Class 226
8.10 Summary 228
Exercises 229CONTENTS
Chapter 9. Arrays 235
9.1 Prologue 236
9.2 One-Dimensional Arrays 237
93 Lab: Fortune Teller 241
94 Two-Dimensional Arrays 242
95 Case Study and Lab: Chomp 244
9.6 Iterations and the “For Each” Loop 249
9.7 Inserting and Removing Elements 252
98 — Case Study and Lab: the Sieve of Eratosthenes 254
9.9 Summary 256
Exercises 258
Chapter 10. Implementing and Using Classes 2
10.1. Prologue 272
10.2 Public and Private Features of a Class. 276
10.3. Constructors 278
10.4 References to Objects 282
10.5 Defining Methods 283
10.6 Calling Methods and Accessing Fields 286
10.7 Passing Parameters to Constructors and Methods 289
108 return Statement 292
10.9 Case Study and Lab: Snack Bar 295
10.10 Overloaded Methods 300
10.11 Static Fields and Methods 303
10.12 Case Study: Snack Bar Concluded 308
10.13 Summary 310
Exercises 312
Chapter 11, java.util ArrayList 319
11.1 Prologue 320
112 Arraybist’s Structure 320
113. ArrayList’s Constructors and Methods 323
11.4 Lab: Exploding Dots 326
11.5 Lab: Shuffler 328
116 arrayList’s Pitfalls 329
11.7 Lab: Creating an Index for aDocument 332
118 Summary 336
Exercises 337CONTENTS:
x
Chapter 12. Class Hierarchies
341
12.1
12.2
123
12.4
12.5
12.6
127
12.8
Prologue 342
Class Hierarchies 344
Abstract Classes 345
Invoking Superclass’s Constructors 347
Calling Superclass’s Methods 350
Polymorphism 352
Interfaces 353
Summary 356
Exercises 358
Chapter 13. Algorithms and Recursion
365
13.1
13.2
133
134
13.5
Prologue 366
Recursive Methods 367
Tracing Recursive Methods 370
Case Study: File Manager 371
Summary 375
Exercises 375
Chapter 14. Searching and Sorting
383
14.1
14.2
143
144
145
146
147
14.8
149
14.10
14.11
Prologue 384
equals, compareTo, and compare 385
Sequential and Binary Search 391
Lab: Keeping Things in Order 395
Selection Sort 396
Insertion Sort 397
Mergesort 399
Quicksot 402
Lab: Benchmarks 404
java.util.Arrays andjava.util.Collections 406
Summary 408
Exercises 410CONTENTS
Chapter 15. Streams and Files 413
15.1
15.2
153
15.4
15.5
15.6
Prologue 414
Pathnames and the java.io.File Class 416
Reading ftom aText File 418
Writing toa Text File 421
Lab: Choosing Words 423
Summary 424
Exercises 425
Chapter 16. Graphics 29
16.1
16.2
16.3
16.4
16.5
16.6
16.7
16.8
Prologue 430
paint, paintComponent, ad sepaint
Coordinates = www.skylit.com/javamethods4/
ciors JM-Chapter16-www pat
Drawing Shapes
Fonts and Text
Case Study and Lab: Pieces of the Puzzle
Summary
Exercises 432
Chapter 17. GUI Components and Events 435
171
17.2
17.3
17.4
17.5
17.6
177
Prologue 436
Pluggable Look and Feel
Basic Swing Components and Their Events Myr oilcomavanetinist!
Layouts
Menus
Case Study and Lab: the Ramblecs Game
Summary
Exercises 438CONTENTS:
xi
Chapter 18. Mouse, Keyboard, Sounds, and Images
443
18.1
18.2
13.3
13.4
18.5
18.6
18.7
18.8
Prologue 444
Mouse Events Handling
Keyboard Events Handling
Lab; Ramblecs Concluded
Playing Audio Clips
‘Working with Images
Lab: Slide Show
Summary
Exercises 445
“& wonw.skylt.com/javamethods4/
JM-Chapter1 8-www.pot
Chapter 19. Recursion Revisited
447
19.1
19.2
193
19.4
19.5
19.6
19.7
Prologue 448
Three Examples 448
‘When Not to Use Recursion 455
‘Understanding and Debugging Recursive Methods 459
Lab: the Tower of Hanoi 462
Case Study and Lab: the Game of Hex 463
Summary 468
Exercises 468
Chapter 20. Sets and Maps
475
20.1
20.2
203
20.4
20.5
20.6
20.7
Prologue 476
Lookup Tables 477
Lab: Cryptogram Solver 479
Hash Tables 482
java.util’sHashset and HashMap 484
Lab: Search Engine 487
Summary 489
Exercises 490xii CONTENTS
Chapter 21. Computing in Context
495
21.1 Prologue 496
21.2 Be Creative!
213 Rules of Digital Citizenship
28.3.1 Formulating Ethical Guidelines
283.2 Maintaining Professional Standards
28.3.3. Regulating Users
214 System Reliability and Security
28.4.1 Avoiding System Failure
28.4.2 Maintaining Data Integrity
28.4.3. Protecting Secure Systems and Databases
215 Legal Issues
285.1 Privacy
28.5.2. Censorship vs. Free Speech
28.5.3. Intellecmal Property and Copyright Issues
21.6 Summary
Suggested Activities
Appendices
+ wow skylit.comijavamethods4/
JM-Chapter21-www.pat
Common Syntax Error Messages
GUI Examples Index
The EasyReader, EasyWriter, EasySound,
and EasyDate Classes
pop
Solutions to Selected Exercises www.skylit.com/javamethods4
Index 499
The 17 Bits of Style s& www.skylit. comjavamethods4Preface
This book offers a thorough introduction to the concepts and practices of object-
oriented programming in Java. It also introduces some of the common data
structures and related algorithms: one- and two-dimensional arrays, ArrayList,
Sets and Maps, and their implementations in the Java Collections Framework.
Chapters 1-14 follow the syllabus of the AP Computer Science in Java course (AP
CS “A”). They will prepare you well for the AP exam. Chapters 15-18 on file input
and output, graphics, graphical user interfaces, and events handling in Java will give
you a better sense of real-world Java programming; this material also makes case
studies, labs, and exercises more fun. Chapter 19 revisits recursion at a deeper level
Chapter 20 introduces the concepts of look-up tables, sets, and maps, and their
implementation in the Java Collections Framework. ‘The last chapter, Computing in
Context, discusses creative, responsible, and ethical computer use.
This edition builds on our earlier books, Java Methods A & AB: OOP and Data
Structures (Skylight Publishing, 2006), and Java Methods, second and third AP
Editions (2011 and 2015). The AB-level AP CS exam was discontinued by the
College Board in 2009. Teachers who continue teaching advanced data structures
and students who want to leam this material on their own can find complete data
structures chapters in the Java Methods Third AP edition e-book. In this edition we
have added a lab and exercises to the ArrayList chapter.
The book follows four main threads: Java syntax and style, OOP concepts and
techniques, algorithms, and Java libraries. As in the software engineering profession.
itself, these threads are interwoven into an inseparable braid.
We strive to present the technical details while grounding them in clear explanations
of the underlying concepts. OOP has an extensive conceptual layer and complex
temminology. Fortmately, many OOP concepts are more straightforward than the
terminology makes them appear. Most of the key elements are actually quite
intuitive: objects (entities that combine data elements and functions), classes
(definitions of types of objects), methods (functions that carry out certain tasks),
instantiation (creating an object of a particular class), inheritance (one class
extending the features of another class), encapsulation (hiding the implementation
details of a class), polymorphism (automatically calling the correct methods for
specific objects disguised as objects of more generic types), and event-drivenxiv CONTENTS
applications (where the operating system, the user, or events in the program trigger
cettain actions),
We also emphasize good programming style, an element not mandated by formal
Java language specifications but essential for writing readable and professional code.
Our labs and case studies aim to demonstrate the most appropriate uses of the
programming techniques and data structures we cover. OOP is believed to facilitate
teamwork, software maintenance, and software reuse. While it is not possible for an
introductory textbook to present a large-scale real-world project as a case study, the
case studies and Labs in this book offer a taste of how these OOP benefits can play
out in larger projects.
It is not our goal to teach exclusively the material required for the AP CS A exam.
While we mosily stay within the Java AP subset defined by the College Board for AP
CS exams in Java, we also want to give you a solid conceptual foundation and
introduce sound software design and coding practices. If you are preparing for the AP
exam, you'll need to be familiar with the College Board’s Course and Exam
Description and use our review book, Be Prepared for the AP Computer Science
Exam in Java (Skylight Publishing).
We assume that at least two or three class periods each week will be held in a
computer lab with students working independently or in small groups. A set of
Student Files downloadable from this book’s web site contains all the case studies,
labs, and exercises in the book; a downloadable set of Teacher Files, available to
teachers only, provides complete solutions to all the labs and exercises.
Still, with all the examples and case studies, we leave a lot of work to you, the
student. This is not a Java-in-n-days book or an n-hours-fo-complete book. It is a
book for learning essential concepts and technical skills at a comfortable pace, for
acquiring a repertoire of techniques and examples to work from, and for consulting as
needed when you start writing your own Java code professionally or for fun.
Working through this book will not make you a Java expert right away, but it will
bring you to the level of an entry-level Java programmer with a better than average
understanding of the fundamental concepts. Object-oriented programming was
originally meant to make software development more accessible to beginners, and
Java Methods is written in that spirit.
Without further delay, let us begin learning object-oriented programming in Java!CONTENTS: wv
oo &
Since our first book came out in 1998, many of our colleagues, too many to name,
have become good friends. We are grateful to them for their loyal support,
encouragement, and the many things they have taught us over the years
We thank the students in Maria’s AP Computer Science classes for their patience
while studying from earlier editions of this book: they have caught several typos and
mistakes and made many useful suggestions.
Our special thanks to Margaret Litvin for her thorough and thoughtful editing.
ct + +
The cover image of a star with lens flare and bokeh effect was generated using 3D
software.How to Use This Book
This edition’s companion web site —
ods4
http://www. skylit.com/javane
— is an integral part of this book. It contains five chapters and several appendices.
It also has downloadable student files for case studies, labs, and exercises, assembled
together in what we call Student Files. Also on the book’s web site are links, errata,
supplemental papers, and syllabi and technical support information for teachers.
We have chosen to place Chapters 1, 16, 17, 18, and 21 and the appendices on the
web either because they rely on many web links or because the material they cover is
handy to have online for reference.
* The web symbol indicates a “webnote”; you will find it in the alphabetical
list of webuote links on the book’s web site.
Jy refers to Java Methods Student Files. For example, “you can find
HelloWorld.java in Jy\ch02\Hello” means the HelloWorld. java
file is located in the Ch02\He1Lo subfolder in the Student Files folder.
es
J, This icon draws your attention toa lab exercise or a hands-on exploration of
an example.
“Parentheses” like these, in the margin, mark supplementary material
intended for a more inquisitive reader. This material either gives a glimpse
of things to come in subsequent chapters or adds technical details.
1¥,2.* In exercises, a square indicates an “intermediate” question that may require
more thought or work than an ordinary question or exercise. A diamond
indicates an “advanced” question that could be treacherous or lead to
unexplored territory — proceed at your own risk.
xviix7 How To UsE Tus Book
(MC) We have included a few multiple-choice questions in the exercises. These
are marked (MC).
¥ A checkmark at the end of a question in an exercise means that a solution is
included in Jy\solutionsToExercises.pdf. We have included
solutions to about one-third of the exercises.
‘The Teacher Files folder, which contains complete solutions to all the exercises and
labs, is available for downloading free of charge to teachers who use this book as a
textbook in their schools. Go to skylit.com/javamethodsé and click on the
“Teachers’ Room” link for details.
(To a slightly different subject...)
How you use this book will depend on your background in computers. If you are
familiar with computers and some coding, you can glance quickly at Chapters | and 2
to see whether they fill any gaps.
Chapters 3, Java Syntax and Style, and 4, Objects and Classes, can be covered in any
order, depending on your taste.
If you know C++, Chapters 5. 6, and 7 will be easy for you. But do still read them
for the sake of the case studies and labs, which cover broader concepts than the
chapter headings imply. Chapters 15, Streams and Files, 16, Graphics, 17, GUI
Components and Events, and 18, Mouse, Keyboard, Sounds, and Images. are optional
as far as the AP exams are concemed. Chapter 19 can be skipped if you understand
recursion really well (or are not at all interested in it). Chapter 21, Computing in
Context, is an important introduction to social and ethical issues involved in
computer use. This chapter can be read after the AP exam,ch 001
Hardware, Software, and the Internet
13
14
15
16
17
Prologue 2
Hardware Overview +& www.skylit.com/javamethods4/
1.2.1 The CPU JM-Chapter01-wwrw.pdt
12.2 Memory
1.2.3 Secondary Storage Devices
1.2.4 Input and Output Devices
Software Overview
What Do Software Engineers Do?
Representation of Information in Computer Memory
15.1 Numbers
1.5.2 Characters
‘The Intemet
summary
Exercises 52 CHAPTER | ~ HARDWARE, SOFTWARE, AND THE INTERNET
1.1 Prologue
The most important piece of a typical computer is the Central Processing Unit or
CPU. In apersonal computer, the CPU is a microprocessor made from a tiny chip of
silicon, sometimes as small as half an inch square. Immensely precise manufacturing
processes etch a huge number of semiconductor devices, called transistors, into the
silicon wafer. Each transistor is a microscopic digital switch and together they
control, with perfect precision, billions of signals — little spikes of electricity — that
arise and disappear every second. The size of the spikes doesn’t matter, only their
presence or absence. The transistors in the CPU recognize only two states of a
signal, “on” or “off.” “1” or “0,” “true” or “false.” This is called digital electronics
(as opposed to analog electronics where the actual amplitudes of signals carry
information).
‘The transistors on a chip combine to form logical devices called gates. Gates
implement Boolean operations (named after the British mathematician George Boole,
1815-1864, who studied the properties of logical relations). For example, an AND
gate takes two inputs and combines them into one output signal. The output is set to
“tue” if both the first and the second input are “true,” and to “false” otherwise
(Figure 1-1-a). In an OR gate, the output is set to “true” if either the first or the
second (or both) inputs are true (Figure I-1-b). A NOT gate takes one input and sets
the output to its opposite (Figure 1-1-c). Note the special shapes used to denote each
type of gate.
These three basic types of gates can be combined to make other Boolean operations
and logical circuits. Figure 1-2, for example, shows how you can combine AND,
OR, and NOT gates to make an XOR (“eXclusive OR”) operation. ‘This operation sets
the output to “true” if exactly one of its two inputs is “te.” In the late 1940s, John.
von Neumann, a great mathematician and one of the founding fathers of computer
technology, showed that all arithmetic operations can be reduced to AND, OR, and
NOT logical operations.1.1 ~ PROLOGUE 3
f@) b) ©
AND gate OR gate NOT gate
as
De AND B A—[>o— NoT A
“A | NOTA
Tl F
el T
Figure 1-1. AND, OR, and NOT gates
—) >— A x0R &
i
A XOR B
aanalo
A
7
F
F
Figure 1-2. XOR circuit made of AND, OR, and NOT gates
maaan
The microprocessor is protected by a small ceramic case mounted on a PC board
(Printed Circuit board) called the motherboard. Also on the motherboard are
memory chips. The computer memory is a uniform pool of storage units called Bits.
A bit is the smallest possible unit of information, with its value set to 0 or 1. For
practical reasons, bits are grouped into groups of eight, called bytes. So 8 bits make
L byte.4 CHAPTER | ~ HARDWARE, SOFTWARE, AND THE INTERNET
[J one byte is eight bits.
There is no other structure to memory: the same memory is used to store numbers
and letters and sounds and images and programs. All these things must be encoded,
one way or another, in sequences of Os and 1s. A typical personal computer made in
the year 2021 had 8, 12, or 16 “gigs” (gigabytes; 1 gigabyte is 2” 10" bytes) of
RAM (Random-Access Memory) packed in a few SIMMs (Single In-Line Memory
Modules).
The CPU interprets and executes (“runs”) computer programs, or sequences of
instructions stored in the memory. The CPU fetches the next instruction, interprets
its operation code, and performs the appropriate operation. There are instructions for
arithmetic and logical operations, for copying bytes from one location to another, and
for changing the order of execution of instructions. ‘The instructions are executed in
sequence unless a particular instruction tells the CPU to “jump” to another place in
the program. Conditional branching instructions tell the CPU to continue with the
next instruction or jump to another place depending on the result of the previous
operation.
Besides the CPU, a general-purpose computer system also includes peripheral
devices, which provide input and output and secondary mass storage. In a laptop or
tablet computer, the “peripheral” devices are no longer quite so peripheral: a
keyboard. a display. a hard drive, a DVD drive, a wireless network adapter. a web
cam (camera), @ touch pad or touch screen, a microphone, and speakers are all built
into one portable unit.
CPU, memory, peripherals — all of this is called hardware. It is a lot of power
concentrated in a small device. But to make it useful, to bring life into it, you need
programs, sofhvare. Computer programs are also miracles of engineering, but of a
different kind: software engineering. They are not cast in iron, nor even silicon, but
in intangible texts that can be analyzed, modified, translated from one computer
language into another, copied into various media, transmitted over networks, or lost
forever. Software is to a computer as tunes are to a band: the best musicians will be
silent if they don’t have music to play.
Take this amazing device with its software and connect it to the Internet, a network
of billions of computers of all kinds connected to each other via communication lines
of all kinds and running programs of all kinds, and you end up with a whole new
world. Welcome to cyberspace!CHAPTER 1 ~ EXERCISES J
In the rest of this chapter we will briefly discuss:
+ The main hardware components: CPU, memory, peripheral devices
+ What software is
© How numbers and characters are represented in computer memory
© What the Internet is
ww 12-17 &
These sections are online at http: //www. skylit.com/javamethods4.
Exercises
‘Sections LI-LA
1. Mark T (true) or F (false) the output of each of the following circuits
with the given inputs.
—D- =D
(@) (b)
1 —De—
* De
co
2.5 Let's say that two circuits are equivalent if they produce the same outputs for
the same inputs. Draw a circuit equivalent to the one in Question 1-b using
two NOT gates and one AND gate.
3. Simplify the circuit in Question 1-c to an equivalent one that has only two
gates: one NOT gate and one AND gatea
CHAPTER | ~ HARDWARE, SOFTWARE, AND THE INTERNET
(a)" Draw an alternative XOR circuit, different from the one in Figure 1-2
using two NOT gates, two OR gates, and one AND gate. < Hint:
least one of the inputs, A or B, must be true, and at least one of the
negated inputs, NOT A or NOT B, must be true, too. 3 ¥
(b)* Draw a third XOR circuit using four gates: one OR gate, two AND
gates, and one NOT gate
(MC) Computer memory is called RAM because:
It provides rapid access to data
It is mounted on the motherboard,
It is measured in megabytes.
‘Any byte can be accessed directly through its address.
Its chips are mounted in a rectangular array.
rpORP
Mark true or false and explain:
(a) One meg of RAM can hold exactly as much information as one meg on
a flash drive.
(b) _ A factory-formatted hard disk is split into a fixed number of files.
v
(©) In personal computers the operating system resides in ROM. v
Find an old discarded desktop computer, unplug the power cord, and
disconnect all other cables. Open the cover and identify the motherboard,
CPU, RAM, USB ports (sockets for cable connectors), hard disk, CD-ROM,
and other components and adapters, if present.
Identify the following entities or devices as part of a computer system’s
hardware (H) or software (S).
(a) Operating system
(b) CPU
(©) GUI Graphical User Interface) v
(d) Bus
(e) RAM
(p)" FileCHAPTER 1 ~ EXERCISES 7
Identify the operating system that is running on your current computer and
some apps installed on it: a word processor, an Intemet browser, a
spreadsheet program, e-mail, an image processing application, games, and so
on,
10.
i.
12.
Mark true or false:
(a) Only data but not CPU instructions can be stored in RAM.
(b) In ASCII code each character is represented in one byte. v
(©) 16-bit binary numbers can be used to represent all non-negative
integers from 0 to 2!¢-1
(d) Programs stored in ROM are referred to as “firmware.
‘What is the maximum number of different codes or numbers that can be
represented in
(a) 3 bits? v
(b) 8 bits?
(©) 2 bytes?
Assuming that binary numbers represent unsigned integers in the usual way,
with the least significant bit on the right, Fill in the blanks in the table.
Example
Binar: Decimal Rex
00001000 8
00011100 28
(a) 00000010
(b)
(©) 10000000
@ 73a Lv
fe) ta
(11110101
(@" 00000101 10010010 vCHAPTER | ~ HARDWARE, SOFTWARE, AND THE INTERNET
13.
14.
15.
16."
17.4
An experiment consists of tossing a coin 10 times and its outcome is a
sequence of heads and tails. How many possible outcomes are there?
How much memory does it take to hold a gray-scale digital image of 512 by
512 pixels (picture elements, which are tiny squares) with each pixel holding
one of the 256 levels of gray?
‘When a printer runs out of paper, the eight-bit printer status register of the
parallel interface adapter gets the following settings: bit 7 (leftmost bit),
"BUSY," is set to 1: bit 5, "PE" ("paper end"), is set to 1: and bit 3.
"ERROR," is set to 0. Bit 4 is always 1 when a printer is connected; bit 6 is
0; and bits 0-2 are not used. Write the hex value equal to the setting of the
printer status register when the printer runs out of paper, assuming that bits
0-2 are 0.
Design a method for representing the state of a tic-tac-toe board in computer
memory. Can you fit your representation into three bytes?
In the game of Nim, stones are arranged in piles of arbitrary size. Each
player in turn takes a few stones from any one pile. Every player must take
at least one stone on every turn. The player who takes the last stone wins.
Games of this type always have a winning strategy. This strategy can be
established by tagging all possible positions in the game with two tags,
“plus” and “minus,” in such a way that any move from a “plus” position
always leads to a “minus” position, and from any “minus” position there is
always a possible move into some “plus” position. The final winning
position must be tagged “plus.” Therefore, if the first player begins in a
“minus” position, she can win by moving right away into a “plus” position
and returning to a “plus” position on each subsequent move. If, however, the
first player begins in a “plus” position, then the second player can win,
provided he knows how to play correctly.
In Nim, we can convert the number of stones in each pile into a binary
number and write these binary numbers in one column (so that the “units”
digits are aligned on the right). We can tag the position “plus” if the number
of 1s in each column is even and “minus” if the count of 1s in at least one
column is odd. Prove that this method of tagging “plus” and “minus”
positions defines a winning strategy. Who wins starting with four piles of 1,
3, 5, and 7 stones — the first or the second player? What’s the correct
response if the first player takes five stones from the pile of 7?CHAPTER 1 ~ EXERCISES 9
18.
The table below is called a Greco-Roman square: each of the three Latin
letters occurs exactly once in each row and each column; the same is true for
each of the three Greek letters; and each Latin-Greek combination ocewss
exactly once in the table:
Ay | Ba | cp
BB | Cy | Aa
Co | AB | By
Substitute the digits 0, 1, and 2 for A, B, C and for a, fy (in any order).
Convert the resulting base-3 numbers into decimal (base-10) numbers. The
base-3 system uses only three digits: 0, 1, and 2. The numbers are
represented as follows:
Decimal Base 3
Add | to each number, You will get a table in which the numbers | through
9 are arranged in such a way that the sum of the numbers in each row and
column is the same. Explain why you get this result and find a way to
substitute the digits 0, 1, and 2 for letters so that the sum of numbers in each
of the two diagonals is also the same as in the rows and columns. What you
get then is called a magic square. Using a similar method, build a 5 by 5
magic square10 CispTer 1 ~ Harpwars, SOFTWARE, AND THE INTERNET
Seetion 1.6
19. (MC) What does TCP stand for?
Telnet Control Program
Transmission Control Protocol
Transport Compression Protocol
Telephone Connectivity Program.
None of the above
PoOwP
20. Are the following entities or devices hardware (H) or software (S)?
(a) Host y
(b) LAN
(c) Browser
(d) Search engine v
(e) Router
(O" TCPAP Adapter v
21. Find and explore the web pages about Internet and World Wide Web
pioneers.Hello Joe
Chapter 2
An Introduction to Software
Engineering
21 Prologue 12
22 Compilers and Interpreters 14
23 Software Components and Packages 21
24 Lab: Three Ways to Say Hello 22
25 Object-Oriented Programming 29
26 Lab: More Ways to Say Hello 32
2.7 Summary 37
Exercises 38
il12 (CiapTER 2 ~ AN INTRODUCTION To SOFTWARE ENGINEERING
2.1 Prologue
One of the first computers, ENIAC,**“* developed in 1942-1946 primarily for
military applications, was programmed by people actually connecting hundreds of
wires io sockets (Figure 2-1) — hardly a “software development” activity as we
know it. (ENIAC occupied a huge room, had 18,000 vacuum tubes, and could
perform 300 multiplications per second,) In 1946, John von Neumann developed the
idea that a computer program can be stored in the computer memory itself in the form
of encoded CPU instructions, together with the data on which the program operates.
‘Then the modern computer was bom: a “universal, digital, program-stored” computer
that can perform calculations and process information.
Figure 2-1. Two technicians wiring the right side of ENIAC
(Courtesy of U. S, Army Research Laboratory)
Once program-stored computers were developed, it made sense to talk about
programs as “written.” In fact, at the beginning of the computer era, programmers
wrote programs in pencil on special forms: then technicians punched the programs
into punch cards*?™*"" or perforated tape. A programmer entering a computer
room with a deck of punch cards was a common sight. Fairly large programs were
written entirely in machine code using octal or hexadecimal instruction codes and
memory addresses. It is no coincidence that the same word, “coding,” is used for
writing programs and encrypting texts. Programmers were ofien simply2.1 ~ PROLOGUE 13
‘mathematicians, electrical engineers, or scientists who learned the skill on their own,
when they needed to use a computer for their work.
In those days computers and “computer time” (that is, the time available for running
programs) were very expensive, much more expensive than a programmer's time,
and the high computer costs defined the rules of the game. For instance, only fairly
important computer applications could be considered, such as military and scientific
computations, large information systems, and so on. Programmers strove to make
their programs run faster by developing efficient algorithms (the concept of an
algorithm is described in Chapters 7 and 13). Often one or two programmers wrote
the entire program and knew all about it, while no one else could understand it
Computer users were happy just to have access to a computer and were willing to
Jeamn cryptic instructions and formats for using programs.
Now, when computers are so inexpensive that they have become a household
appliance, while programmers are relatively scarce and expensive, the rules of the
game have changed completely. This change affects which programs are written,
how they are created, and even the name by which programmers prefer to be called
— “software engineers” or “app developers.” There is still a need, of course, for
understanding and optimizing algorithms. But the emphasis has shifted to
programmers’ productivity, professionalism, and teamwork — which requires using
standard programming languages, tools, and software components.
Software applications (“apps”) that run on a personal computer are loaded with
features and must be very interactive and “user-friendly.” (that is, have an intuitive
and fairly conventional user interface). They must also be portable (that is, able to
ran on different computer systems and mobile devices, including tablets and
smartphones) and internationalized (that is, easily adaptable for different languages
and local conventions). Since a large team may work on the same software project, it
is very important that all members of the team follow the same development
methodologies, and that the resulting programs be understandable to others and well
documented. Thus software engineering has become as professionalized as other
engineering disciplines: there is a lot of emphasis on knowing and using professional
tools in a team environment, and virtually no room for solo wizardry.
A typical fairly large software project may include the following tasks:
* Interaction with customers, understanding customer needs, refining and
foumalizing specifications
* General design (defining a software product’s parts, their fimctions and
interactions)
* Detailed design (defining objects, functions, algorithms, file layouts, etc.)14 (CiapTER 2 ~ AN INTRODUCTION To SOFTWARE ENGINEERING
* Design/prototyping of the user interface (designing screen layouts, menus,
dialog boxes, online help, reports, messages. etc.)
Coding and debugging
Performance analysis and code optimization
* Documentation
* Testing
* Packaging and delivery
User technical support
And, in the real world:
* Bug fixes, patches and workarounds, updated releases, documentation updates,
and so on.
Of couse there are different levels and different kinds of software engineers, and it is
not necessary that the same person combine all the skills needed to design and
develop good software. Usually it takes a whole team of software designers,
programmers, artists, technical writers, QA (Quality Assurance) specialists, and
technical support people.
In this chapter we will first discuss general topics related to software development,
such as high-level programming languages and software development tools, We will
discuss the difference between compilers and interpreters and Java's hybrid
compiler + interpreter approach. Then we will learn how to compile and run simple
Java applications and take a first look at the concepts involved in object-oriented
programming.
2.2 Compilers and Interpreters
Computer programmers very quickly realized that the computer itself was the perfect
tool to help them write programs. The first step toward automation was made when
programmers began to use assembly languages instead of numerically coded CPU
instructions. In an assembly language, every CPU instruction has a short mnemonic
name. A programmer can give symbolic names to memory locations and can refer to
these locations by name. For example, a programmer using assembly language for
Intel’s 8086 microprocessor can write:2.2 ~ COMPILERS AND INTERPRETERS 15
index dv 0 3 "Define word" — reserve 2 bytes
+ for an integer and call it "index".
mov si,index 7 Nove the value of index into
} the ST register
A special program, called the assembler, converts the text of a program written in
assembly language into the machine code expected by the CPU.
Obviously, assembly language is totally dependent on a particular CPU; porting a
program to a different type of machine would require rewriting the code. As the
power of computers increased, several high-level programming languages were
developed for writing programs in a more abstract, machine-independent way.
FORTRAN (Formula Translation Language) was defined in 1956, COBOL
(Common Business Oriented Language) in 1960, and Pascal and C in the 1970s.
C++ gradually evolved from C in the 1980s, adding OOP (Object-Oriented
Programming) features to C.*™** Now there are hundreds of programming
languages. Some are specialized, such as MatLab, and some are general. In recent
years, Python has become popular in schools and in software companies.
Java was introduced in the mid-1990s and eventually gained popularity as a fully
object-oriented programming language for platform-independent development, in
particular for programs transmitted over the Internet. Java and OOP are of course the
main subjects of this book, so we will start looking at them in detail in the following
chapters.
A program written in a high-level language obeys the very formal syntax rules of the
language. This syntax produces statements so unambiguous that even a computer can
interpret them correctly. In addition to strict syntax rules, a program follows sivle
conventions; these are not mandatory but make the program easier to read and
understand for fellow programmers, demonstrating its author's professionalism.
oe
A programmer writes the text of the program using a software program called an
editor. Unlike general-purpose word-processing programs, program editors may
have special features useful for writing programs. For example, an editor may use
colors to highlight different syntactic elements in the program or have built-in tools
for entering standard words or expressions common in a particular programming
language.
* There are several “block languages,” such as Scratch and Blockly, designed for children. In
these environments a program is assembled by dragging and connecting blocks that represent
commands and data. Very litle typing is required.16 (CiapTER 2 ~ AN INTRODUCTION To SOFTWARE ENGINEERING
‘The text of a program in a particular programming language is referred
to as source code, or simply the source. The source code is stored in a
file, called the source file.
Before it can run on a computer, a program written in a high-level programming
language has to be somehow converted into CPU instructions. One approach, for
example common with C++, is to use a special software tool called a compiler. The
compiler is specific to a particular programming language and a particular CPU. It
analyzes the source code and generates appropriate CPU instructions. ‘The result is,
saved in another file, called the object module. A large program may include several
source files that are compiled into object modules separately. Another program, a
linker, combines all the object modules into one executable program and saves it in
an executable file (Figure 2-2).
Editor Compiler Linker
is a
Source Object Executable
code code program
t oo)
© helio.cyp —=—shelo.ebj—= helo. ene
O-
. Software development cycle for a compiled
program: edit-compile-link-run,
For a compiled program, once it is built and tested, the executable file is distributed
to program users. The users do not need access to the program’s source code and do
not need to have a compiler. ‘The executable program runs on a particular operating
system.
Java also uses a compiler, but, as we will explain shortly, the Java
compiler does not generate object code for a particular CPU.2.2 ~ COMPILERS AND INTERPRETERS 17
In an alternative approach, commonly used with such languages as BASIC and
Python, instead of compiling, a program in a high-level language can be interpreted
by a software tool called an interpreter (Figure 2-3). The difference between a
compiler and an interpreter is subtle but important. An interpreter looks at the high-
level language program, figures out what instructions it needs to execute, and
executes them, But it does not generate an object-code file and does not save any
compiled or executable code. A user of an interpreted program needs access to the
program’s source code (which is often called a script), and an interpreter, and the
program has to be interpreted again each time it is run, It is like a live concert as,
opposed to a studio recording, and a live performance needs all the instruments each.
time.
Editor Interpreter
™ E17 source p>
code
Gecrint)
t
© nelle. pr
Figure 2-3. Interpreted program
A particular programming language is usually established as either a compiled
language or an interpreted language (that is, it is either more often used with a
compiler or an interpreter, respectively). FORTRAN, COBOL, Ada, C++ are
typically compiled; BASIC, Perl, Python are interpreted. But there is really no clear
cut distinction. BASIC, for example, was initially an interpreted language, but soon
BASIC compilers were developed. C is usually compiled, but C interpreters also
exist.
1 Java is different: it uses a mixed compiler-plus interpreter approach.18 (CiapTER 2 ~ AN INTRODUCTION To SOFTWARE ENGINEERING
A Java compiler first compiles the program into bytecode, instructions that are pretty
close to a machine language, But a machine with this machine language does not
exist! It is an abstract computer, a Java Virtual Machine (JVM). The bytecode is
then interpreted on a particular computer by the Java interpreter for that particular
CPU. A program in bytecode is not object code, because it is still platform-
independent (it does not use instructions specific to a particular CPU). It is not
source code, either, because it is not readable by humans. It is something in between.
Why does Java use a combination of a compiler and an interpreter? There is no
reason why a regular Java compiler couldn’t be created for a particular type of
computer. But originally one of the main purposes of Java was to deliver programs
to users via the Internet. A Java-enabled browser (that is, a browser that has a Java
interpreter built into it) can run little Java programs, called applets (miniature
applications). The many applets available free on the Internet, often with their source
code, was one of the reasons why Java has become so popular so fast. When you
connect to a web site and see some elaborate action or interactive features, it may
mean that your computer has received a Java applet and is running it.
Java designers had to address the key question: Should users receive Java source
code or executable code? The answer they came up with was: neither. If users got
source, their browsers would need a built-in Java compiler or interpreter. That would
make browsers quite big, and compiling or interpreting on the uset’s computer could
take a long time, Also, software providers may want to keep their source
confidential. But if users got executables, then web site operators would somehow
need to know what kind of computer each user had (for example, a PC or a Mac) and
deliver the right versions of programs. It would be cumbersome and expensive for
web site operators to maintain different versions of a program for every different
platform. There would also be a security risk: What if someone delivered a malicious
program to your computer?
Bytecode provides an intermediate step, a compromise between sending source code
or executables to users (Figure 2-4). On one hand, the bytecode language is
platform-independent, so the same version of bytecode can serve users with different
types of computers. It is not readily readable by people, so it can protect the
confidentiality of the source code. On the other hand, bytecode is much closer to the
“average” machine language, and it is easier and faster to interpret than “raw” Java
source. Also, bytecode interpreters built into browsers get a chance to screen
programs for potential security violations (for example. they can block reading of and
writing to the user's disks). Still, security concems remain, and nowadays applets
have fallen out of favor.2.2 ~ COMPILERS AND INTERPRETERS 19
Editor Compiler
=| source | = | Bytecode
code
S&S =
Hello. java Hello.class
Interpreter q
Interpreter
O-B 4
To speed up the loading of applets, a new software technology was developed, called
JIT (Sust-In-Time) compilers. A JIT compiler combines the features of a compiler
and an interpreter. While interpreting bytecode, it also compiles it into executable
code, for faster execution of the same program in the future. (To extend our music
analogy, a IIT compiler works like a recording of a live concert.) This means an
applet can be interpreted and start running as soon as it is downloaded from the
Intemet. On subsequent runs of the same applet, it can be loaded and run from its
executable file without any delay for reinterpreting bytecode.
Naturally, bytecode does not have to travel through the Internet to reach the user: a
Java program can be compiled and interpreted on the same computer. That is what
we will do for testing Java applications in our labs and exercises
Nowadays, Java applets have become obsolete, mainly due to security risks. New
tools for adding action to websites have come about. These tools are safer and easier
touse. The new word for little programs is “apps.”
Soe20 (CiaPTER 2 ~ AN INTRODUCTION To SOFTWARE ENGINEERING
Modern software development systems combine an editor, a compiler, and other tools
into one Integrated Development Environment (IDE). Some of the software
development tools (a program editor, for example) are built into the IDE program
itself, larger tools (a compiler, an interpreter) are usually stand-alone programs, for
which the IDE only serves as a front end. An IDE has a convenient GUI (Graphical
User Interface) — one mouse click on an icon will compile and run your program.
Modern programs may be rather complex, with dozens of different types of objects
and functions involved. Structure analyzers and viewers built into an IDE create
graphical views of source files, objects, their functions, and the dependencies
between them, GUI visual prototyping and design tools help a programmer design
and implement a graphical user interface.
Few programs are written on the first try without exrors or, as programmers call them,
bugs (Figure 2-5).
Figure 2-5. The term “bug” was popularized by Grace Hopper,*¥** a legendary
‘computer pioneer, who was the first to come up withthe idea of a compiler and who
created COBOL. One of Hopper's favorite stories was about a moth that was found
‘wapped between the points of a relay, which eaused a malfunetion of the Mark IL Asien
Relay Calculator (Harvard University, 1945). Technicians removed the moth and affixed
itt the log shown inthe photograph.
I Programmers distinguish syntax errors and logic errors.
Syntax errors violate the syntax rules of the particular programming language and are
caught by the compiler or interpreter. Logic errors are caused by flawed logic in the
program; they are not caught by the compiler or interpreter but show up at “run
time,” that is when the program is running. Some run-time errors cause an exception:
the program encounters a fatal condition and is aborted with an exror message, which
describes the type of the exception and the program statement that caused it. For
example, if an arithmetic operation is trying to divide a number by 0, then the
program is aborted with an “arithmetic exception: division by zero” error. In Java it
might look like this:
Exception in thread "main" java.lang.arithmeticexception: / by zezo2.3 ~ SOFTWARE COMPONENTS AND PACKAGES 21
Other run-time errors may cause program’s unexpected behavior or incorrect results.
These are caught only in thorough testing of the program.
It is not always easy to correct bugs just by looking at the source code or by testing
the program on different data. To help with this, there are special debugger programs
that allow the programmer to trace the execution of a program “in slow motion.” A
debugger can suspend a program at a specified break point or step through the
program statements one at a time. With the help of a debugger, the programmer can
examine the sequence of operations and the contents of memory locations after each.
step
2.3 Software Components and Packages
Writing programs from scratch may be fun, like growing your own tomatoes from
seeds, but in the present environment few people can afford it. An amateur, faced
with a programming task, asks: What is the most original (elegant, efficient, creative,
interesting) way to write this code? A professional asks: What is the way to not write
this code but use something already written by someone else? With billions of lines
of code written, chances are someone has already implemented this or a similar task,
and there is no point duplicating his or her efforts. (A modem principle, but don’t try
it with your homework!) Software is a unique product because all of its production
cost goes into designing, coding and testing one copy; manufacturing multiple copies
is virtually free. So the real task is to find out what has been done, purchase the
rights to it if it is not free, and reuse it.
There are many sources of reusable code. Extensive software packages come with
your compiler. Other packages may be purchased from third-party software vendors
who specialize in developing and marketing reusable software packages to
developers. Still other packages may be available for free in the spirit of the open
source*°"""" philosophy. In addition, every experienced programmer has
accumulated his or her own collection of reusable code.
Reusability of software is a two-sided concept. As a programmer, you want to be
more efficient by reusing existing code. But you also want to write reusable code so
that you yourself, your teammates, your enterprise, and/or the whole world can take
advantage of it later. Creating reusable code is not automatic: your code must meet
certain requirements to be truly reusable. Here is a partial list of these requirements:22 (CiapTER 2 ~ AN INTRODUCTION To SOFTWARE ENGINEERING
* Your code must be divided into reasonably small parts or components
(modules). Each component must have a clear and fairly general purpose.
Components that implement more general functions must be separated from
more specialized components,
* Your software components must be well documented, especially the interface
part, which tells the user (in this case, another programmer) what this
component does and how exactly to use it. A user does not necessarily always
‘want to know how a particular component does what it does,
* The components must be robust. They must be thoroughly tested under all
possible conditions under which the component can be used, and these
conditions must be clearly documented. If a software module encounters
conditions under which it is not supposed to work, it should handle such
situations gracefully, giving its user a clue when and why it failed instead of just
crashing the system.
* It should be possible to customize or extend your components without
completely rewriting them.
Individual software components are usually combined into packages. A package
combines functions that deal with a particular set of structures or objects: a graphies
package that deals with graphics capabilities and display: a text package that
manipulates strings of text and text documents: a file package that helps to read and
write data files: a math package that provides mathematical functions and algorithms:
and soon. The ArrayList class in the java.util package from the standard Java
library is a reusable class for handling lists: it is explained in Chapter 11. The
HashSet and HashMap classes from the same package are described in Chapter 20.
Java coders can take advantage of dozens of standard packages that are already
available for free: new packages are being developed all the time. At the same time,
the plenitude of available packages and components puts an additional burden on the
software engineer, who must be familiar with the standard packages and keep track
of the new ones
2.4 Lab: Three Ways to Say Hello
A traditional way to start exploring a new software development environment is to
write and get running a little program that just prints “Hello, World!” on the screen.
After doing that, we will explore two other very simple programs. Later, in
Section 2.6, we will Look at simple GUI programs.
In this section, we will use the most basic set of tools, IDK (Java Development Kit)
IDK comes from Oracle Corporation, the owners of Java.2.4 ~ Lap: THREE Ways TO SaY HELLO 23
JDK includes a compiler, an interpreter, other utility programs, the
standard Java library, documentation, and examples.
IDK itself does not have an IDE (Integrated Development Environment), but Oracle
and many third-party vendors, universities, and other organizations offer IDEs for
working with Java, Eclipse, BlueJ, JGrasp, NetBeans, DrJava, are some examples,
but there are others. Most IDEs have versions for different operating systems
(Windows, Mac, Linux). This. book’s companion web site,
wwe. skylit.com/javamethods4, has instructions for installing and using Eclipse
and JGrasp.
In this lab the purpose is to get familiar with JDK itself, without any
IDE. However, if you don’t feel like getting your hands dirty (or if you
are not authorized to run command-line tools on your system), you can
start using “power” tools right away. Just glance through the text and
then use an IDE to type in and test the programs in this lab.
We assume that by now you have read Oracle’s instructions for installing and
configuring JDK under your operating system and have it installed and ready to use.
In this lab you can tesi that your installation is working properly. If you are not
going to use command-line tools, then you need to have an IDE installed and
configured as well
This lab involves three examples of very simple programs that do not use GUL, just
text input and output, Programs with this kind of old-fashioned user interface are
often called console applications (named after a teletype device called a console,
which they emulate). Once you get the first program running. the rest should be
easy.
Our examples and commands in this section are for Windows.
1. Hello, World
IDK tools are UNIX-style command-line tools, which means the user has to type in
commands at the system prompt to run the compiler and the interpreter. The
compiler is called javac. exe; the interpreter is called java.exe. These programs
reside in the bin subfolder of the folder where your JDK is installed. This might be,
for example, C:\Program Files\Java\jdk-16\bin. You'll need to make these
programs accessible from any folder on your computer. To do that, you need to set
the path environment variable to include IDK’s bin folder. There is a way to make24 (CiapTER 2 ~ AN INTRODUCTION To SOFTWARE ENGINEERING
a permanent change to the path, but today we will just type it in once or twice,
because we don’t plan on using command-line tools for long.
Create a work folder (for example, C:\mywork) where you will put your programs
from this lab. You can use any editor (such as Notepad) or word processor (such as
Wordpad or MS Word) or the editor from your IDE to enter Java source code. If you
use a word processor, make sure you save Java source files as “Text Only.” But the
file extension should be .j2va. Word processors such as Word tend to attach the
cxt extension to your file automatically. The trick is to first choose
Save as type: Text-Only (*.txt), and only after that type in the name of
your file with the correct extension (for example, He1 loWior1d. java),
In your editor, type in the following program and save it in a text file with the name
HelloWorld. java:
yee
+ pisplays a "Hello World!" message on the screen
public class HelloWorld a
t =
public static void main(stzing!] args) G®
{
systen.out.printla("sello, World!")
,
'
I In Java, names of files are case sensitive.
This is true even when you run programs in a Command Prompt window. Make sure
you type in the upper and lower cases correctly and don’t include any spaces
In the little program above, Hei loworld is the name of a class as well as the name
of its source file. (Don’t worry if you don’t quite know what that means, for now.)
‘The name of the file that holds a Java class must be exactly the same as
the name of that class (plus the extension . java).
This rule prevents you from having two runnable versions of the same class in the
same folder. Make sure you name your file comectly. There is a convention that the
name of a Java class (and therefore the name of its Java source file) always starts
with a capital letter.2.4 ~ Lap: THREE Ways TO SaY HELLO 25
The Java interpreter calls the main method in your class to start your
program. Every Java program must have a main method.
If a program consists of several classes, one of them must have main. The one in
your program is
public static void main(String[] args)
For now, treat this as an idiom. You will learn the meaning of the words public.
static, void, String, and args and the meaning of [] later.
system is a class that is built into all Java programs. It provides a few system-level
services. System. out is a data element in this class, an object that represents the
computer screen output device. Its print1n method displays a text string on the
screen,
Examine what you have typed carefully and correct any mistakes — this
will save time,
Save your file and close the editor. Open the Command Prompt window (click
“Start.” in the search box, type “Command Prompt.” and then, in the list of results,
click “Command Prompt”). Navigate to the folder that contains your program (for
example, mywork) using the cd (change directory) command, and set the path:
C:\Documents and Settings\Owner>cd \mywork
Ci\mywork> path C:\program files\java\jdk-16\bin;3PATH?
Now compile your program:
Ci\mpwori® javae HelleWorld.java
If you have mistyped something in your source file, you will get a list of emors
reported by the compiler. Don’t worry if this list is quite long, as a single typo can
cause several errors. Verify your code against the program text above, eliminate the
typos, and recompile until there are no errors.
Type the di (directory) command:
Cs\mywork> die
You should see files called Hel loWorld.java and HelloWorld.class in your
folder. The Latter is the bytecode file created by the compiler.26 (CiaPTER 2 ~ AN INTRODUCTION To SOFTWARE ENGINEERING
Now run the Java interpreter to execute your program:
c:\mywork> Java HelloWorld
Every time you make a change to your source code, you'll need to
recompile it. Otherwise the interpreter will work with the old version of
the .class file,
2. Greetings
A Java application can accept “command-line arguments” from the operating system.
These are words or numbers (character strings separated by spaces) that the user can
enter on the command line when he rus the program. For example, if the name of
the program is Greerings and you want to pass two arguments to it, “Annabel” and
“Lee”, you can enter:
cr \myvork> java Greetings Annabel Lee
If you are using an IDE, it usually has an option, a dialog box. where you can enter
command-line arguments before you run the program.
If you are already using your IDE and do not feel like figuring out how
to enter command-line arguments in it, skip this exercise and go directly
to Step 3, “More Greetings.”
Sine following Java program expects two command-line arguments.
* This program expects two command-line arguments
* -- 2 person's first name and last nane.
* For example:
* C:\mywork> java Greetings Annabel Lee
public class Greetings
fi
public static void main(string[] args)
(
String firetName = args(01;
string LastName = args [i];
system. out -printin ("Hello
System. out -println ("Congr
,
:
"4 firstwane +" " + lascName);
tulations on your second program!");
Type up this program in your editor and save it in the text-only file2.4 ~ Lap: THREE Ways TO SaY HELLO 27
Greetings. java. Compile this program:
C:\myworio Javac Greetings. java
{{ Now run it with two command-line arguments: your first and last name
3. More Greetings
Now we can try a program that will prompt you for your name and then display a
message. You can modify the previous program. Stait by saving a copy of it in the
text file Greetings2. Java.
+ This program prompts the usex to enter his ox her
* first name and last name and displays 2 greeting message.
* author: Maria Litvin
*/
import java.util.scanner;
public class Greetings?
e
public static void main(String?) azgs) &
t
Scanner Kboard = new Scanner (System. in);
system.out print ("Enter your fizst name: ");
string firstNane = Kboard.nextLine();
system.out print ("Enter your last name: ");
String lastName = Kboard.nextLine()
system.out.printin("Hello, "+ firstName +" " + lastwame);
System.out printin(*Welcome to Java!");
kboard.close (07
'
Our Greetings? class uses a Java library class Scanner from the java.util
package. This class helps to read numbers, words, and lines from keyboard input.
The import statement at the top of the program tells the Java compiler where it can
find the Scanner class.28 (CiaPTER 2 ~ AN INTRODUCTION To SOFTWARE ENGINEERING
Compile Greet ings2. java —
s\mynork> Javae Greetings? java
—and mun it:
myvork> java greetings2
What do you get?
Exception in throad "nain* java. lang.NoClaseboffounderrort
hare: Greetings2)
St java. 1ang.Classtoader .defineciase: [ative wathod)
at java. lang.claseLoader defineciase (Classiaader
te jevecne sloeder.
at java.net URIClassLoader ,access5100 URLCLacsioade!
Be Java. not Uriclasstoadersi . run (UXLCLasstoader. 330
at java vaccesscontroller -doPrivi leged (at:
at java
St Java. 1ang.claseLoader.ioadclass (ClassLoader J ava/a0e)
at gun.nise.bauncherSappClasstoader.loadclass aauncher dava
at java lang. ClassLoader losdclass [Classtoader Java:25i)
at Java. 1ang.ClaseLeade: .leadclassInternal (ClassieaderJav
greetings? (wrong
ve Method)
URIClasstoader .findClass (URIClasstoader.java:188)
Wow! The problem is, you entered greetings? with a lowercase “G”, and the Java
interpreter cannot find a file called greetings2.class. Remember: Java is case-
sensitive. You can see now why you might want some help from an IDE!
Try again:
myvork> Java Greetings?
Now the program should run: it prompts you for your first and last name and displays
a greeting message:
mynork> java Greetings2
Enter your first name: Virginia
Enter your last name: Woolf
Hello, Virginia Woolf
Welcome to Java!
If you are using an IDE, you will be able to compile and run Greetings? with one
click of a button.2.5 ~ OBJECT-ORIENTED PROGRAMMING 29
2.5 Object-Oriented Programming
In von Neumann computer architecture. a program is a sequence of instructions
executed by a CPU. Blocks of instructions can be combined into procedures that
perform a certain calculation or carry out a certain task: these can be called from
other places in the program. Procedures manipulate some data stored elsewhere in
computer memory. This procedural way of thinking is suggested by the hardware
architecture, and naturally it prevailed in the early days of computing. In procedural
progranming, 4 programmer has an accurate picture of the order in which
instructions might be executed and procedures might be called. High-level
procedural languages don’t change that fact. One statement translates into several
CPU instructions and groups of statements are combined into functions, but the
nature of programming remains the same: the statements are executed and the
finctions are called in a precise order imposed by the programmer. These procedures
and functions work on separately defined data structures
In the early days, user interface took the form of a dialog: a program would show
prompts asking for data input and display the results at the end, similar to the
Greetings? program in the previous section. This type of user interface is very
orderly — it fits perfectly into the sequence of a procedural program. When the
concept of graphical user interface (GUD developed, it quickly became obvious that
the procedural model of programming was not very convenient for implementing
GUI applications. In a program with a GUI. a user sees several GUI components on.
the screen at once: menus, buttons, text entry fields, and so on. Any of the
components can generate an event: things need to happen whenever a user chooses a
menu option, clicks on a button, or enters text. A program must somehow handle
these events in the order of their arrival. It is helpful to think of these GUI
components as animated objects that can communicate with the user and other
objects. Each object needs its own memory to represent its current state. A
completely different programming model is needed to implement this metaphor.
Object-oriented programming (OOP) provides such a model.
The OOP concept became popular with the introduction of Smalltalk,*"“"*™ the first
general-purpose object-oriented programming language with built-in GUI
development tools. Smalltalk was developed in the early 1970s by Alan Kay**” and
his group at the Xerox Palo Alto Research Center. Kay dreamed that when
inexpensive personal computers became available, every user, actually every child,
would be able to program them: OOP, he thought, would make this possible. As we
know, that hasn't quite happened, Instead, OOP first generated a lot of interest in
academia as a research subject and a teaching tool, and then was gradually embraced30 (CiapTER 2 ~ AN INTRODUCTION To SOFTWARE ENGINEERING
by the software industry, along with C++, and later Java, as the prefered way of
designing and writing software.
One can think of an OOP application as a virtual world of active objects. Each object
has its own “memory,” which may contain references to other objects. Each object
has a set of methods that can process messages of certain types, change the object’s
state (memory), send messages to other objects, and create new objects, An object
belongs to a particular class, and each object’s functionality, methods, and memory
structure are determined by its class. A programmer creates an OOP application by
defining classes.
Two principles are central to the OOP model: event-driven programs
and inheritance.
In an OOP program many things may be happening at once, and external events (for
example, the user clicks the mouse or types a Key, the application's window is
resized, etc.) can determine the order of program execution. An OOP program, of
course, still runs on sequential von Neumann computers; but the software simulates
parallelism and asynchronous handling of events.
An OOP program usually defines many different types of objects. However, one
type of objects may be very similar to another type. For instance, objects of one type
may need to have all the functionality of another type plus some additional features.
It would be a waste to duplicate all the features of one class in another. The
mechanism of inheritance lets a programmer declare that one class of objects extends
another class. ‘The same class may be extended in several different ways, so one
superclass may have several subclasses derived from it (Figure 2-6). A subclass
may in turn be a superclass for other classes, such as tiusic is for Audio and MP3.
An application ends up looking like a branching tree, a hierarchy of classes. Classes
with more general features are closer to the top of the hierarchy, while classes with
more specific functionality are closer to the bottom.2.5 ~ OBJECT-ORIENTED PROGRAMMING 31
cD
Music Video Pictures Blank
Z A
Figure 2-6. A hierarchy of classes that represent
compact disks with different content
Audio
Object-oriented programming aims to answer the current needs in software
development: lower software development and documentation costs, better
coordinated team development, accumulation and reuse of software components,
more efficient implementation of multimedia and GUI applications, and so on. Java
is a fully object-oriented language that supports inheritance and the event-driven
model. It includes standard packages for graphics, GUI, multimedia, events
handling, and other essential software development tools.
Our primary focus in this book is working with hierarchies of classes. Event-driven
software and events handling in Java are considered to be more advanced topics. For
example, they are not included in the Advanced Placement Computer Science Course
and Exam Description, We will discuss events handling in Java and provide
examples in Chapters 17 and 18.32 (CiapTER 2 ~ AN INTRODUCTION To SOFTWARE ENGINEERING
2.6 Lab: More Ways to Say Hello
In Section 2.4 we learned how to run very simple console applications. These types
of programs, however, are not what makes Java great: they can be easily written in
other programming languages.
The features that distinguish Java from some other languages are its
built-in support for GUI and graphics and its support for object-
oriented programming.
In this section we will consider three more examples: a program with a simple GUI
object, another with graphics, and the third with a simple animation. Of course at
this stage you won’t be able to understand all the code in these examples — we have
a whole book ahead of us! This is just a preview of things to come, a chance to get a
general idea of what is involved and see how these simple programs work.
1A GUI application
In this program, #e11oGui. java, we create a standard window on the screen and
place a “Hello, GUI!” message in it. Our HeiloGui class extends the Jane
library class, which is part of Java’s Swing package. We are lucky we can reuse
JF rame’s code: it would be a major job to write a class like this from scratch. We
would have to figure out how to show the title bar and the border of the window and
how to support resizing of the window and other standard functions. JFrame takes
care of all this. All we have left to do is add a label to the window's content pane —
the area where you can place GUI components.
Our He11oGui class is shown in Figure 2-7. In this program, the main method
creates one object, which we call window. The type of this object is described as,
HelloGui; that is, window is an object of the HelloGui class. This program uses
only one object of this class. main then sets window's size and position and displays
it on the screen. Our class has a consiructor, which is a special procedure for
constructing objects of this class. Constructors always have the same name as the
class. Here the constructor calls the superclass’s constructor to set the text displayed
in the window’ title bar and adds a label object to the window’s content pane.2.6 ~ Lap: Mor Ways TO SaY HELLO 33
java.awt Color;
Java. awt Container;
Java..awt .FlowLayout?
import Javax.swing. JFrame;
import Javax.swing.JLabel;
public class Hellocui extends JFrame
i
public Hellocui() // Constructor
{
super("GUI Deno"); —// Set the title bar
container © = getContenteane();
¢-setBackground (Color CYAN) ;
c.setLayout (new FlowLayout ())4
dd (new JLabel(" Hello, GUI!", 10))7
public static void main(String[] args)
{
HelloGui window = new Hellogui();
Z/ Set this window's location and size:
// upper-left corner at 300, 300; width 200, height 100
window. setSounds(300, 300, 200, 100);
window. setDefaul tcloseoperation (.
window. setVisible (true);
same -EXTT_ON_CLOSE);
Figure 2-7. Jy\ch02\Hel1oGui\HelloGui.. java
The code in Figure 2-7 is a little cryptic, but still we can see roughly what's going on.
Do not retype the program — just copy HelloGui.java from the
Jy\ch02\ Hel loGui folder into your current work folder (Jy refers to student files
available at www.skylit.com/javamethods4). Set up a project in your favorite
IDE, and add/copy the class, He1loGui to the project. Compile and mn the
program using menu commands, buttons, or shortcut keys in your IDE.34 (CiaPTER 2 ~ AN INTRODUCTION To SOFTWARE ENGINEERING
Hello, Graphics
We will now change our program a little to paint some graphics on the window
instead of placing a text label. The new class, #elloGraphics, is shown in
Figure 2-8.
import java.awt.Graphies;
import java.awt.Colors
import java.awt.Container;
import javax.swing.gFrame;
import javax.swing.gPanel;
public class Hellocraphics extends JPanel
public void paintcomponent (Graphics )
1
super-paintComponent (g); // Call JPanel's paintComponent method
// to paint the background
g-setcolor (Color-RED);
// Draw a 150 by 45 rectangle with the upper-left
(/ comer at x = 20, y= 40:
g-drawrect (20, 40, 150, 45);
g-setCoLor (Color. BLUE)
// praw a string of text starting at x = 55, y
g-drawstring("Hello, Graphies!", 55, 65);
)
public static void main(string[] args)
{
JFrame window = new JFrame("Graphics Demo") ;
// Set this window's location and size:
(/ agper-left corner at 300, 300; width 200, height 150
window. seteounds(300, 300, 200, 150);
window. setD=faultclosedperation(gFrame.=XTT_ON_CLOSE) ;
HelloGraphics panel = new BelloGraphics ();
panel.setbackground (color.wEITS); // the default color is light gray
Container ¢ = window.getcontentPane () ;
c-add (panel) ;
ndow, setVisible (true);
Figui
28. Jw\chO2\He1l1loGui\HelloGraphics. java2.6 ~ Lap: MoRE WAYS TO SAY HELLO 35
HelloGraphics extends a library class gPanel. Each JPanel object has a
paintComponent method that generates all the graphics contents for the panel.
paintComponent is called automatically whenever the window is opened, resized,
or repainted. ‘These events are reported to the program by the operating system,
By default, 72anel's paintComponent method only paints the background of the
panel, Our class He1loGraphics redefines (overrides) paintcomponent to add a
blue message inside a red rectangle. paintComponent receives an object of the
type Graphics, often called g, that represents the panel’s graphics context (its
position, size, etc.),
The graphics coordinates are in pixels and have the origin (0, 0) at the
upper-left corner of the panel (the y-axis points down).
G We have placed the main method into the same class to simplify things. If you wish,
you can split our HelloGraphics class into two separate classes: one, call it
HelloPanel, will extend Janel and have the paintComponent method; the
other, call it HolloGraphics, will have main and nothing else (it doesn’t have to
‘Lextend any library class). Your project then would include both classes.
Hello, Action
‘And now, just for fun, let’s put some action into our program (Figure 2-9). Compile
the Banner class from Jy\Cho2\#e11oGui and run the program.
Look at the code in Banner. java. The main method creates a Timer object called
clock, “attaches” it to the panel on which the message moves, and starts the timer.
The timer is programmed to “fire” every 30 milliseconds, Whenever the timer fires,
it generates an event that is captured in the actionPerformed method. This
method adjusts the position of the message and repaints the screen.36 (CiaPTER 2 ~ AN INTRODUCTION To SOFTWARE ENGINEERING
ye
* This program displays a message that moves horizontally
* across the window.
+
import java.awt.Graphics;
import java.awt.color;
import java.awt.Container;
import javax.swing.grrame;
import javax.swing.gpanel;
import javax.swing Timer;
import java.awt,event ActionListener;
import java.awt.event ActionEvent;
public class Banner extends JPanel
implements ActionListener
(
private int xPos, yP0s; // hold the coordinates of the message
// Called automatically after a repaint request
public void paintComponent (Graphics 9)
{
super .paintComponent (g); // Paint the background
g- SetColor (Color.RED) ;
g-draustring("Hello, Action!", xPos, yPos);
,
// called automatically when the timer "fires"
public void actionPerformed (ActionEvent @)
1
(/ Adjust the horizontal position of the messag
xpos; // subtract 1
Af (xPos < -100)
xPos = getWidth();
repaint);
)
public static void main(stringI] args)
{
gerame window = new gerame("Action Demo");
// Set this window's location and size:
(/ agper-left corner at 300, 300; width 300, height 100
window. seteounds(300, 300, 300, 100);
// Create panel, a Banne:
Banner panel = new Bano:
panel .setbackground (col
object, which is a kind of JPanel:
di
cyan); // che default color is light gray
Continued x