Professional Documents
Culture Documents
Two possible activities for this chapter are to look inside of an old computer and to inventory the programs
installed on a new one.
The Internet is the best resource for more detailed information on hardware and software and the Internet
itself.
Early computers used vacuum tubes and relay switches. Semiconductor technology allows manufacturers to
etch microscopic devices into layers in a silicon chip.
Other types of gates work as combinations of these three: e.g., NAND is NOT and AND. An XOR gate
(exclusive OR) has the output TRUE when one of the inputs, but not both, is TRUE.
ROM is tiny as compared to RAM: ROM may be a few KB, while RAM size on personal computers and
laptops is getting to be over 1 GB.
A memory address is represented as a binary number. An address is “sent” via the memory bus; the data is
written or retrieved via the data bus. A “bus” is a logical device.
The CPU chip is packaged inside a ceramic case. The chip itself is as small as 3/4".
Logically ROM and RAM form contiguous memory space; the CPU can’t just write into ROM (and never
needs to try). Physically ROM is on a separate chip.
Extension slots are used for plugging in additional adapter boards: internet adapter, graphics card, sound
card, disk controller, etc. In newer systems many of these functions are built directly into the motherboard.
The idea that a computer can hold its own program in RAM is attributed to von Neumann; it was not obvious
at first. The very first computers were programmed by connecting wires to sockets.
The term “peripheral devices” comes from the old era; in a laptop, most devices are integrated into one small
unit. A printer or a scanner remains “peripheral.”
8
The first IBM PC’s CPU, Intel 8088, ran at 4.77 Mhz; now the speeds are reaching 2 Ghz, 500 times faster.
Additional technologies, such as cashing and pipelining (fetching the next instruction while the current one is
being executed) increase the speed even more. A modern microprocessor has a built-in co-processor for
floating-point arithmetic.
Memory size is measured using powers of 2 because memory addresses are binary numbers. A 32-bit
address bus can directly address 232 = 4 GB of memory.
10
Operating system software arranges files into a tree-like structure of folders (directories).
Data compression can further expand the storage capacity of different devices.
By comparison, the first IBM PC/XT (c. 1983) had 512 KB of RAM and a 10 MB hard disk. Thus RAM has
increased 1000 times and disk space has increased 10,000 times, while the price has decreased 5 times.
11
The Internet adapter is used to connect to the Internet via a high-speed connection.
A/D and D/A converters are used to convert analog signals into digital and vice versa. They are used to
connect analog scientific instruments or industrial controllers to a digital computer.
New types of devices and new hardware standards for connecting devices to a computer are emerging all the
time. More recent computers have high-speed USB (Universal Serial Bus) ports for connecting peripherals.
USB replaces old serial and other ports.
12
BIOS stands for Basic Input-Output System. BIOS is in ROM; it controls the keyboard, disk drives, etc.
A device driver is a specialized program that knows how to handle a particular device or hardware adapter.
For example, a printer or a scanner needs a device driver.
A few popular operating systems: Windows, Mac OS, Unix and its derivatives (e.g., Linux), OS/2, etc.
Common applications on personal computers: word processing, databases, spreadsheets, Internet browsers,
music and movie players, games.
13
17 = 1 * 24 + 0 * 23 + 0 * 22 + 0 * 21 + 1 * 20
Negative numbers use twos-complement representation; i.e., -17 is represented as 232 - 17, and the sign bit is
set to 1. So -17 + 17 gives you 0 (plus the overflow bit, which disappears):
15
You have to be careful when adding a very small (by absolute value) number to a very large number, because
the contribution of the very small number will be lost. The range for doubles is large, but the precision is
more limited.
16
“The Unicode Consortium is a non-profit organization founded to develop, extend and promote use of the
Unicode Standard, which specifies the representation of text in modern software products and standards. The
membership of the consortium represents a broad spectrum of corporations and organizations in the
computer and information processing industry. The consortium is supported financially solely through
membership dues. Membership in the Unicode Consortium is open to organizations and individuals
anywhere in the world who support the Unicode Standard and wish to assist in its extension and
implementation.”
Unicode represents all major alphabets of the world as well as special characters. There are provisions for
ideographic characters from Japan, Korea, China, and more.
17
A network requires network hardware (adapters, switches, etc.), communication lines (cable, phone lines,
wireless, etc), and, most importantly, communication protocols, i.e., technical standards for different devices
to talk to each other.
18
The two most popular browsers are Netscape Navigator and Internet Explorer, but there are many others.
Google has become a popular search engine. Its success is due to a simple innovative idea: it ranks the “hits”
(matching documents) based on how many web pages are linked to a document as opposed to how many
times a search keyword appears in a document.
20
With the appropriate software and an Internet connection, you can turn your computer into a host that will
hold your web site. But small end-users have their web sites “hosted” by one of the commercial ISPs
(Internet Service Providers). The largest is AOL.
21
Describe the outputs of an AND gate for all possible combinations of the two inputs.
T, T ==> T
T, F ==> F
F, T ==> F
F, F ==> F
One of the main reasons for Java’s popularity is the proliferation of Java applets on the Internet. An applet is
a little program “embedded” in a web page. While this chapter has nothing to do with programming, we feel
it is important to give students the necessary background information: what a web page is and how it is put
together and linked to other pages. This also gives students a chance to get familiar with the computer
environment, be successful in a creative and fun activity, and acquire a useful skill.
If pressed for time, you can skip this chapter without affecting the rest of the material in the book. (Though
it’s a good idea to cover Section 2.9 before running applets in Chapter 3.) On the other hand, you can spend
as much as four weeks teaching HTML and designing web pages of increasing complexity, adding more
advanced features from online documentation and tutorials.
The Hypercard software for Mac (1987) made the hypertext concept popular.
Markup: you can take a plain text file, open it in a simple text editor (such as Notepad), and mark it up by
embedding HTML tags.
A text with embedded HTML tags is stored in a plain text file called “source.”
The source file can be viewed in a plain text editor, such as Notepad.
Exercise: Open a web page (e.g., www.skylit.com) in your browser, then on the “View” menu click “Source”
– you’ll see HTML source for that page.
You can type an HTML document using a plain text editor. But then you have to open your HTML file in a
browser and switch between the editor and a browser to see how your page looks. This is not very
convenient: it is not WYSIWYG. There are many WYSIWYG tools that help design an HTML document
interactively, then generate HTML source automatically for you.
Microsoft Word is a WYSIWYG editor for formatted text documents. It also has a simple WYSIWYG
capability for HTML documents. Exercise: create a simple HTML document in Microsoft Word, save it,
then open the .html file as a “text only” document and examine the html source generated by Word.
5
An HTML document may look different when displayed in different software or on different devices: the
appearance may depend on the size and resolution of the screen, the number of colors, etc. So WYSIWYG
can never be fully achieved. Designers have to test their web pages in all popular browsers.
Some authors prefer to write all HTML tags in all caps to make them more visible; others prefer all lower
case.
<img> and <hr> (horizontal rule) do not have a closing tag. Sometimes the closing tag is optional: for
example, </p> (end of paragraph) is not required.
Some attributes are required, such as <img src="..."> (the source of an image). Other attributes are
optional, such as <hr width="50%"> (alone, <hr> draws a horizontal rule across the whole window, width
= 100%).
It is better to keep the tags nested correctly, as in <a><b>...</b></a> and avoid interspersed tags, as in
<a><b>...</a></b>.
There is one exception: the <xmp> tag suspends the processing of HTML tags between <xmp> and </xmp>,
so the fragment from the source document between these tags will be displayed exactly as in the source,
including all the tags and line breaks. This is useful, for example, when you want to show a fragment of
HTML source on your web page.
10
The document’s title is displayed in the browser window title bar. More importantly it is used when you
bookmark the page. Choose a descriptive title.
It is customary to put webmaster contact information, last revision date, copyright notices, etc, in the address
section.
11
HTML interpreters do not care how the text is split between lines. All contiguous white space (spaces, tabs,
line breaks) is replaced by one space. use <p> to indicate a new paragraph and <br> to indicate a line break.
A non-breaking space ( ) can be used to prevent splitting two words between lines and to increase the
spacing between words.
<hr> also has a “size” attribute which determines the thickness of the rule (e.g., <hr size="6">). Some
browsers, but not all, support the color attribute for the rule.
12
<strong> is the same as <b>, but it is more abstract and can be redefined in style sheets (advanced topic,
not covered). <cite> by default is the same as <i>.
<font size="+..."> increments the font size relative to the current size.
13
When a browser is sent to an anchor, the text or the picture that follows the anchor is positioned at the top of
the browser window, and the scrollbar position is adjusted accordingly.
14
The # in the href attribute indicates that this is an anchor in the current document and not the name of
another file.
15
The resource’s type is often defined by the extension in the file name: .htm or .html — an HTML
document; .pdf — a PDF (Portable Document Format) file; .jpg or .gif — an image file; .txt — a text
file; .wav or .au — an audio clip; etc.
16
A browser can find an absolute URL regardless of which document points to it.
http stands for HyperText Transfer Protocol. Thus a URL that starts with http:// indicates that the
resource it points to is within the realm of HTML documents, a file used in web pages.
17
Use forward slashes in file pathnames for compatibility with all systems.
19
An <ul> tag without items indents the text within, like <blockquote>.
20
Where do image files come from? Scanners, digital cameras, collections of icons and pictures, and so on.
Images can be edited and converted to different file formats using Adobe Photoshop or other imaging
software.
21
The text from the alt attribute comes up when you move the mouse over the image.
An image can be inserted in a line of text; then the align attribute indicates how the image is aligned relative
to the text.
22
Map coordinates are in “pixel” units with the origin in the upper-left corner of the image.
23
Tables are the most important page layout tool available in HTML.
A table cell can contain text, images, lists, other tables, applets
24
25
The <th>, <tr>, <td>, and <caption> tags each have their own attributes for horizontal and vertical
alignment and background color; <td> has the width attribute. See the example in the book for details.
26
The applets on the Internet are what made Java popular. Java was initially intended for programming
microprocessors embedded in kitchen appliances and other embedded systems.
27
Java may pose security risks, so a user may choose to disable Java in the browser. Then the browser will
ignore <applet> tags.
An <applet> tag may have several <param> tabs embedded in it. Each <param> tag defines the name and
value of a parameter to be passed to the applet.
28
A web page is an HTML document. A web site is a set of related web pages and supporting files, such as
image files, pdf files, audioclips, applets, and so on, on the same host computer.
Hypertext Markup Language, Hypertext Transfer Protocol, What You See Is What You Get
Hypertext is text with embedded “hot links” which, when clicked, take the user to specified locations
associated with the links.
HTML source is an HTML document viewed as a text file with the HTML tags exposed.
29
What are the supported HTML list types and their respective tags?
<ul> <li> Unordered list
<ol> <li> Ordered list
<dl> <dt> <dd> Definition list
This chapter gives a glimpse of how software development evolved from artisanship into a professional
engineering discipline. At the same time, students will get familiar with Java development tools and run
their first programs.
Students with a penchant for history can find a lot of interesting historical data on programming languages
and software methodologies on the Internet. Those who are more interested in algorithms may be intrigued
by recursion and may try to come up with recursive versions of common algorithms.
A Google search for SOFTWARE results in over 80 million hits. Computers run everything from power
grids, water utilities, TV satellites, and telephone networks to cars and coffee makers. Try to envision our
lives if all programs were suddenly wiped out. Also try to appreciate the total effort that was needed to
develop this invisible universe.
The idea of developing intelligent computers (AI, or artificial intelligence) came about as soon (or perhaps
before) as the first computer. Over the years the expectations turned out to be too optimistic. Little progress
to report so far.
The main premise of the current software development culture is that hardware keeps getting faster and
cheaper, so efficiency is no longer an issue. As a result, the performance of some programs even on fast
computers may be rather sluggish, and we are forced to upgrade our computers every couple of years. This
arrangement is good for both hardware and software companies: new computers have room for new
software, bigger and slower software calls for new computers. This disregard for efficiency and economy in
commercial software may be partly intentional.
Thousands of programming languages and dialects have been described; many evolved over the years, others
have disappeared, some existed for years but recently gained new popularity (e.g., Perl, Python). Java was
initially meant for embedded systems (like home appliances) and for “interactive TV” but has survived due
to the Internet.
Machine code is called “first generation”; assembly languages are second generation; “high-level languages”
(Fortran, Basic, Pascal, Smalltalk, etc.) are third generation. Fourth generation — visual prototyping systems
with automatic code generation — was a buzzword in the 1980s (in the field called CASE, Computer-Aided
Software Engineering), but the promise never really materialized.
7
This is the time to play the “I’m thinking of a number from one to one hundred” game. Other simple
algorithms (e.g., bubble sort) can be staged with students. Students should be encouraged to come up with
their own examples of “interesting” algorithms.
Iterations and recursion make an algorithm different from a cookbook recipe. In most cookbook instructions,
each step is performed once. This works because the chef is slow. But a computer is very fast, billions of
times faster than a programmer. If we had to write out separately every instruction that a computer executes,
we wouldn’t be able to take advantage of its speed. In non-trivial algorithms, the same sequences of steps
are repeated multiple times (but the values of variables are updated at each step).
Flowcharts are pretty much history: they are really not used in software development any more since
programming has switched to OOP.
One should specify when a given algorithm applies (preconditions) and its final state (postconditions). What
are the preconditions here?
The room is rectangular; the robot is placed next to a wall.
What if the preconditions aren’t satisfied? Infinite loop, the program “hangs.”
10
“Methods” in Java are like functions in C or C++. Calling an object’s method is often phrased as “sending a
message” to the object.
11
In the previous example, the program may have a class Robot and an object of that class. A Robot object
keeps in its memory its initial and current position. A robot has methods to step forward and to turn.
Another class may be Position; the initial and current positions may be objects of that class. Robot’s
methods “forward” and “turn” may call Position’s methods “move” and “turn.”
The number of classes in a project may be quite large, but they are usually short. In Java each class is stored
in a separate file. (An exception are the so-called inner classes that are embedded inside another class. They
are not discussed in this book.) The name of the file must be exactly the same as the name of the class
(including upper and lower case) with the extension .java.
12
Event-driven applications are necessitated by GUI: the program cannot predict which button or menu the
user will click next; it reacts to different events as they come. The robot program may have a step button, for
instance.
Inheritance allows you to reuse most of the code in a class and redefine or add a couple of things. We could
extend Robot into a JumpingRobot, adding a method “jump.”
These concepts will become clearer in the next chapter and in the subsequent chapters.
13
At least these are the claims. OOP is definitely good for GUI development. But is it universally applicable
in any type of project? OOP originated in academia; in a rather unique situation, businesses have spent
millions of dollars converting to OOP and retraining their programmers without serious formal cost-benefit
analysis. Prior to OOP the big thing was structured programming and top-down development.
14
A programming language has a strict syntax. A compiler parses the source code and checks the syntax.
There are other programming tools. “Make” keeps track of the project and the time marks on files and
recompiles only those files whose source code has changed. Version control software allows a team of
programmers to keep track of changes to files, so that two programmers are not working with the same file at
the same time.
15
This is a neat legend, but actually the term “bug” was used earlier.
16
If you read your code carefully and reason about it before compiling, the number of cycles through Edit-
Compile-Link-Run will be reduced, perhaps even to one!
17
An IDE is especially helpful in Java because a project may have a large number of source files (each class is
in a separate file).
18
A Java interpreter is built into a Java-enabled browser for running applets. Due to a legal dispute between
Sun and Microsoft, Internet Explorer does not have the latest version of Java built in, but Sun provides a Java
“plug-in” for it. Netscape 6.0 has the latest version of Java.
19
Java Virtual Machine is an imaginary computer with a CPU instruction set that is “the least common
denominator” for typical real CPUs.
20
There is also JIT (Just In Time) compiler technology where the program is interpreted and compiled at the
same time. On subsequent runs the compiled code is used; there is no need to reinterpret it.
21
Java’s culture is pretty open, and many applets are available on the Internet with their source code. Still,
software vendors may want to protect their source code.
For obvious reasons, the interpreter wouldn’t allow an applet to read or write files on your computer.
Hackers have peculiar ethics (or rather, a gap in ethics): they won’t go around checking locks on the doors of
houses or cars or spread real disease germs (even if nonlethal ones), but they will break into your computer
system (which may be much more harmful and expensive) and spread computer viruses.
22
SDK lacks an editor, so we use non-SDK software to create the source code.
Our main tools are javac, java, and appletviewer. IDE usually has a more convenient debugger than SDK’s
debugger. We recommend not using a debugger at all.
23
It may be better to download Java docs together with the SDK and install them on the school server.
24
Most Java IDEs are written in Java. JCreator is an exception: it is written in C++ and is a little more
compact and faster. It requires that SDK be installed.
If an IDE does not come with an SDK, then install the SDK first, before the IDE.
25
Console applications emulate a teletype device; they are sometimes called terminal applications (comes from
old text-only terminals).
26
Console applications may be not much fun, but they do the job when you need to test a simple calculation or
algorithm.
27
We supplied EasyReader and EasyWriter because native Java IO classes are quite confusing and rather
hard to use.
28
Command-line arguments are not specific to Java: C and C++ have them, as well as other languages under
Unix, DOS, etc. In Windows, use the Command Prompt application. There’s no command-line mode on a
Mac.
The Java source file name is a command line argument for javac. Likewise, the HTML file name is a
command-line argument for appletviewer.
29
An IDE usually provides a way to set command-line args (on a Mac, too) or prompts for them when you run
your program.
30
This screen is from the Marine Biology Simulation case study, developed by Alyce Brady for the College
Board and used on the AP CS exams.
31
The ExitButtonListener class is tiny and its code could be written “inline” in the program itself, but we
didn’t want to clutter the program with cryptic code and syntax.
In a GUI program the program itself defines the initial dimensions of the program window. In an applet, the
dimensions are defined in the <applet> tag in the HTML file.
32
Like JFrame, JApplet is also a Swing library class — but for an applet. We redefine its init method.
33
What is OOP?
Object-Oriented Programming — a program simulates a world of active objects.
Define inheritance.
Inheritance is when one class (a subclass) extends another class (the superclass), adding new features and/or
redefining some of the features.
Define IDE.
Integrated Development Environment — combines software development tools under one GUI.
34
Where does the EasyReader class come from? What does it do?
It comes from Maria and Gary Litvin with the Java Methods book. It simplifies console input and reading
files.
Chapter 40
The Ramblecs case study in this chapter is rich enough to illustrate the main OOP concepts and give students
some material for fun exercises.
This chapter gives an introduction to the main Java and OOP concepts but does not require their full
understanding. In terms of grasping the big picture, each student proceeds at his or her own pace. The same
concepts are covered later in more depth. Here students get a general idea of how things are put together, get
a feel for OOP, and work on exercises that require rearranging small pieces of code.
Class names start with a capital letter, while object names start with a lowercase letter. This is a stylistic
convention, not strictly required by Java.
The string of letters in the FallingCube class is also an object; its name is letters and its class is
String. Other objects are used in the program, e.g., Timer t, ActionEvent e.
In the Unix operating system, where Java started, file names are case sensitive. In Windows the names can
use upper- and lowercase letters, but names that differ only in case are deemed the same. But javac and java
still care.
Note that in command-line use of SDK, javac takes a file name SomeThing.java, while java takes a class
name SomeThing (no extension).
We will talk more about stylistic conventions vs. the required Java syntax in Chapter 5.
In OOP, the correct attitude is reusability: “Where can I find the needed code already written?” not “What is
the best way to write this code?” But don’t try this with your homework.
6
An arrow from A to B indicates that A uses B: either creates an object of this type or calls its methods. In
other words, A won’t compile if it can’t find B in the current project folder, along classpath, or in the library.
An applet always has one “main” class that extends JApplet and has an init method. But it does not have
the main method.
It is very easy to convert an applet into an application by slightly changing this “main” class:
2. Add a constructor:
public Ramblecs()
{
super ("The Ramblecs Game"); // Calls JFrame’s
// constructor to add the title bar
init();
}
3. Add main:
Even if you are using an IDE, you have to learn to use Windows Explorer (or Mac folders) to copy, move,
and delete files.
When you run applets from the book, you have to make sure that the HTML file is in the same folder as the
class files (or add the codebase attribute to the <applet> tag). An IDE usually allows you to tell it where to
put class files.
A package name implies the location of the class files in the package. For example, java.awt.event
implies that the classes are in the java/awt/event subfolder. In reality, packages are compressed into .jar
files that have this path information for classes saved inside. A .jar file is like a .zip file; in fact, it can be
opened with the pkzip program that normally reads and creates .zip files.
import is simply a substitution directive that says: Whenever you see JButton, treat it like
javax.swing.JButton. No files are moved or included. If you want a parallel to C++, import is more
like #define than #include.
10
Some programmers do not like .* and prefer to list all imported classes individually. Once the number of
library classes used becomes large, this becomes too tedious. It is also harder to change the class: you need
to add import statements for each library name added.
11
Some programming languages (Pascal, e.g.) distinguish between functions and procedures. A function
performs a calculation and returns the resulting value. A procedure does something but does not return any
value. In Java, a method is like a function, but it can be declared void, meaning it does not return any value.
A constructor is like a special procedure for constructing an object. It has no return value and it is not even
declared void. Other than that, constructors are similar to methods.
12
The name of the constructor is the same as the name of the class, so it starts with a capital letter. The
programmer gives names to fields and methods. Style: by convention, the names of methods and fields start
with a lowercase letter. Names of fields should sound like nouns, and names of methods should sound like
verbs.
13
Programmers strive to make their programs readable. One of the important tools in this struggle is to give
meaningful names to classes, fields, variables, and methods: not too short, not too long, and descriptive.
14
There are other built-in primitive data types: long, float, double, etc; more in Chapter 6.
String is built in but not “primitive”; a String is an object. Primitive types do not have
constructors/methods; objects belong to classes that do.
Some OOP purists consider it an unfortunate compromise that Java (like C or C++) has primitive data types.
They believe that in an OOP language everything should be an object, even a number. Java has Character,
Integer and other classes that parallel primitive data types. These can “wrap around” primitive types when
you need to treat them as objects.
15
If a field is an object, you need to create or initialize that object, either in the declaration itself or in the
class’s constructor or one of the methods. It is null by default.
16
It is usually a good idea to provide a so-called “no-args” constructor that takes no arguments. If no
constructors are supplied at all, then Java provides one default no-args constructor that only allocates
memory for the object and initializes its fields to default values (i.e., numbers to zero, booleans to false,
objects to null).
A class may have only one no-args constructor. In general, two constructors for the same class with exactly
the same number and types of arguments cannot coexist.
17
JButton’s constructors (from API docs, Release 1.3). JButton has five constructors; when we created the
“Go” button we used the fourth one: the one that takes a string as an argument and displays it on the button.
18
Some library methods return new objects, but these methods still have the new operator hidden in them. One
exception is literal strings: text in double quotes creates a String object and it is just there; no new is
needed.
19
As the capital M in “Math” indicates, Math is a class, not an object. (That’s what naming conventions are
for.) There are no objects of the Math type: all the methods are class methods. A class may have both static
(class) and non-static (instance) methods.
20
Public/private designations help to isolate programmers from each other: one programmer needs to know
little about other programmers’ classes: only their public interface. Even if the same programmer writes two
classes, they are isolated from each other. If a change in private fields or methods occurs, then only that
class has to change; other classes are not affected. This is called “information hiding.”
21
Two methods in the same class may have the same name, too, but then they must differ in the number or
types of arguments. Then the compiler figures out which one to call. These are called “overloaded
methods.”
22
In a console application, things happen in an orderly fashion: prompt - response - result. So such programs
can be controlled in a sequential manner. In a GUI application, different types of events may occur in any
order. So we need “listeners” that respond to specific events.
23
Some types of listeners may have several methods. For example, MouseListener has five methods:
mousePressed, mouseReleased, mouseClicked, mouseEntered, and mouseExited. An
ActionListener, used here with the “Go” button, requires only one method, actionPerformed.
24
To serve as an action listener, the object must belong to a class that “implements” ActionListener and
has an actionPerformed method. In this example the applet itself serves as a listener. We could define a
separate class whose object would serve as an action listener for the button.
A button or another GUI component may have several action listeners attached to it. Then each one of the
listeners will be activated when an event occurs.
25
So the Ramblecs class has two methods, init and actionPerformed, but we never call them explicitly.
The first is called when the applet starts, the second is called whenever the “Go” button is clicked.
26
We do explicitly call the dropCube method in the LetterPanel class. But we never call
paintComponent directly; we call repaint() instead. repaint issues a repaint event, and this event
eventually triggers a call to paintComponent.
The type of an event and a listener is the same for a Timer as for a JButton: ActionEvent and
ActionListener. Here the whiteboard object itself serves as a listener for the Timer t.
27
The FallingCube object cube does not respond directly to events: its methods are called by other objects as
necessary.
28
29
It creates a new object of the ExitButtonListener type and adds it to w as a WindowListener. This is
necessary to handle events from the “close window” button (a little X button in the upper-right corner)
because JFrame does not “listen” to this button by default (i.e., ignores its events). 1.3 and later releases of
the SDK have an option to activate this button when you define a JFrame object, so our own
ExitButtonListener is not needed.
Chapter 50
This is an important chapter because it explains and contrasts two related aspects of writing code in a high-
level programming language: language syntax rules and good programming style.
An unstated objective is to give students some appreciation for what is involved in creating working code
and the required level of attention to detail.
How detailed should comments be? In general, self-documenting, clear code is better than obscure, heavily
commented code. Use comments to mark important sections and occasionally explain unexpected twists of
logic or use, but do not comment every statement.
Sometimes you need to comment out a fragment of code to try a variation or to test the remaining code
separately.
Make sure you do not carry a // comment over to the next line. If you do, you need another // mark on that
line.
Java does not allow nested /* */ comments: /* ... */ within /* ... */ does not work. Be careful
when you use /* ... */ to comment out a fragment of code that itself contains a /* ... */ comment.
javadoc.exe is in the JDK...\bin folder. To run javadoc from the command line, enter:
C> javadoc MyFile1.java MyFile2.java ...
Enter
C> javadoc ?
to see the list of all the options and the general command syntax.
So, as far as a Java compiler is concerned, a documentation comment is simply a special case of a
/* ... */ comment.
All the documentation of Java library packages is generated using javadoc. This forced the authors to worry
about the documentation while they were working on the code (or even before they started writing the code).
Embedded HTML tags make the resulting documentation look better. <code> is the most commonly used
tag. javadoc also has the @see tag that generates hyperlinks automatically.
7
Note that the same words with a capital letter or in all caps are not reserved, but it is not a good idea to use
them in programs anyway.
Programmers often give the same name to methods in different classes or use the names of library methods,
if they perform similar tasks. One must be careful, though, not to inadvertently override in a subclass a name
of a method from the superclass.
Underscore in names is not common in Java. Names can also contain $, but this is not common either.
10
Descriptive but not too long. Very long names can be hard to read and may get annoying.
11
Boolean methods (discussed in Chapter 7) often start with “is” or “has” (e.g., boolean isEmpty()).
12
If you do not follow conventional style, you look like a dunce. Remember that your product is the source
code, not the executable program.
Syntax is needed to avoid any possible ambiguity. Syntax also makes the program more readable in a way.
The beginner may find it difficult to get used to. Just be very careful.
13
Reading and checking your code before compiling saves you a lot of time.
Some errors look like acceptable syntax to the compiler, so they pass syntax checks. The compiler cannot
follow your intentions; it is pretty dumb.
14
For example, & is also an operator in Java, but it is different from &&.
15
Extraneous semicolons are especially bad: they are not detected but can break your code. Even experienced
programmers occasionally have one.
16
Always assume that others will look at your code. Make it look good.
17
Style is for humans; the compiler doesn’t care. For a compiler, one space looks the same as 100 spaces or
tabs. The compiler requires spaces only to separate variable names and constants.
18
Some people get too fancy, adding spaces around all ( ) and [ ] and even around dots. This is a matter of
taste but not common style. Math . PI compiles but it is surely not conventional (just Math.PI is better).
19
int x, y, z;
20
if (...) {
...
}
and
if (...)
{
...
}
Each has minor advantages and disadvantages, but basically it is a matter of habit. Once you are used to one
style, the other looks ugly. But one can adjust. (C++ for You++ uses the former style and Java Methods the
latter.)
21
Indenting each level by two spaces is customary in Java. Your IDE lets you set the tab to a specified number
of spaces. Many editors and IDEs support the auto-indent feature: they start indenting automatically after an
opening brace.
22
23
Which of the following are syntactically valid names for variables: C, _denom_, my.num, AvgScore?
Which of them are in good style?
All are valid except my.num. None is in good style.
Java’s primitive data types and arithmetic operators are the same as in C / C++. They can be hazardous due
to integer division and arithmetic overflow. Take your time with this chapter until your students are
comfortable with arithmetic.
Also review the style: naming variables and using symbolic constants.
The code in the green box is 8086 assembly language for IBM PC; ax and bx are general-purpose registers;
move is the move instruction.
More precisely, variables that represent objects hold references to (i.e., addresses of) objects. The space to
hold the actual object is allocated elsewhere.
Names of variables must be meaningful, not too long, not too short. If a name consists of several words, the
subsequent words are capitalized. A name cannot start with a digit.
Several variables of the same type can be declared in the same statement, separated by commas. A
declaration ends with a semicolon.
The variable go’s value is the address of the memory location where this JButton object is stored.
count = count + 1;
In the same declaration, some variables may be initialized and others not.
So scope is a compile-time concept, not a run-time concept. The compiler reports a syntax error, “Cannot
resolve symbol.”
If the scopes of two variables intersect, the variable defined in the inner scope takes precedence over the
variable with the same name in the outer scope. It is easy to make a mistake and override a field with a local
variable of the same name, as explained later.
8
Local variables are for temporary use; they are created when you call a method and destroyed when you
return from a method call. Fields have the lifetime of the object and are destroyed only when the object is
destroyed.
If your goal is only to use the class, it is better to have private fields out of the way, at the bottom, because
you are interested only in the public members. If your goal is to study how the class works, it is better to
have the fields at the top, so you can see right away what attributes and variables describe an object of the
class and their types.
10
Regardless of where you place a field declaration, the field is “visible” in the whole class. The compiler
scans the class’s code to locate and tabulate all the fields, then parses the code again and checks the syntax.
A field’s value can be set in its declaration, in a constructor, or in one of the methods. Uninitialized fields
get default vales: 0 for numbers, null for objects (references), false for booleans (see Chapter 7).
11
If you create a temporary object in a method using new and then assign it to a local variable, then the object
is destroyed automatically when the method is exited and its memory is released. Java has a “garbage
collector" run-time mechanism to do that.
12
Until you understand all the rules, it is safer to declare all the local variables at the top of a constructor or a
method.
Some people declare a loop control variable inside the for statement:
This is OK in a simple method with one loop, but not recommended when you have more than one loop,
potentially with the same loop control variable.
int i;
...
for (i = 0; i < 100; i++)
13
Suppose several methods have a for loop and use k as a loop control variable. You may be tempted to make
k a field to avoid declaring it in each method. Never do that! If you call one method from inside the loop in
another method, you’ll get a nasty bug. It is good style to keep things that are needed locally local. But do
give these variables the same name k to emphasize their similar roles in the program.
14
Worse, if the second declaration is inside a nested { } block, no syntax error is reported, but the outer
variable is overridden in the block. As a novice, do not declare variables inside blocks.
15
Again, give fields prominent names and never use a data type with a field except in the field’s declaration.
Attention to detail is the key.
16
17
\... are called escape sequences from the old printer terminology. '\\' represents a backslash character.
18
19
a = -a;
All unary operators have a higher rank than binary operators and are executed first.
21
If an expression has several binary operators of the same rank with no parentheses, the intermediate results
are calculated from left to right. For example:
x = a / b * c;
is the same as
temp = a / b;
x = temp * c;
22
Integer truncation can be useful, too. For example, find the whole number of weeks in a given number of
days or the number of whole hours in a given number of minutes:
23
Another reason for symbolic constants: if you declare a symbolic constant as a double, then casts to double
are unnecessary and arithmetic errors are avoided. A few redundant casts are OK, and they make your code
self-documenting.
24
109 is OK, but 1010 is already wrong. When you eventually overflow and hit the leftmost bit in an integer
variable, the number becomes negative because this is the sign bit. 12 factorial is OK but 13 factorial is
wrong, which is not immediately obvious if you don’t see the preceding factorial values. Java has a type
long that uses eight bytes and can hold integer values from -263 to 263-1.
25
a = a + b;
a += a + b++;
26
For now we cannot control the speed of falling cubes, but we will add this feature later. Here we prepare the
display for it.
27
28
Now it is more logical to make controlpanel listen to “Go” button events. The main applet is really
shortand doesn’t even know about the “Go” button. This is good design: to keep classes short and limit the
responsibilities of their objects.
29
We need degrees to be an int because the drawArc method expects an int. So we cast the result of the
calculation into an int. Without this cast, the compiler will report an error: “truncation may occur.”
30
What is a variable?
A named container that can hold a value.
Is it OK to give the same name to a field and to a local variable of the same class?
Never.
31
Given
double dF = 68.0;
double dC = 5 / 9 * (dF - 32);
what is the value of dC?
0 (5/9 gives 0 first, the rest doesn’t matter).
C (and early C++) didn’t have boolean data type: boolean values were represented as integers: 1 for true, 0
for false. This could lead to obscure code, such as
if (a - b)...
meaning
if (a - b != 0)...
Later the bool type was added to C++. It is better to keep booleans and integers separate. In Java the
reserved word is boolean.
Another objective is to discuss team development and illustrate software reusability in the context of a
simple but realistic case study, the Craps applet.
When the if or else clause contains only one statement, the braces are optional, but it is safer to always
keep them. With braces it is also easier to add a statement to an if or else clause.
There is no point, really, in using boolean symbolic constants because you can just use true and false in
the code.
You can assign the result of an arithmetic expression to an int or double variable. Similarly, you can
assign the result of a Boolean expression to a boolean variable. For example, rather than writing
boolean exceedsLimit;
if (x > limit)
exceedsLimit = true;
else
exceedsLimit = false;
<= and >= are OK with doubles, because in this type of comparison the program usually doesn’t care about
the situation when the numbers are exactly equal.
In Java you have to always be aware when two variables refer to the same object and when to two different
objects, perhaps with equal values.
The “value” may be defined differently for different types of objects. For strings, the value is the characters
in the string; for “employees,” equals may mean the same social security number. A programmer defines the
meaning of “equals” for the objects of his or her class.
10
11
12
13
In formal logic there is a duality principle: if you take an equality made with &&, ||, and ! and replace all &&
with || and vice versa, you’ll get another equality. De Morgan’s laws are dual.
14
Thus you can string several && with no parentheses: a && b && c. The rank of || is lower than &&, so
a && b || c && d is the same as (a && b) || (c && d), but the expression is more readable with
parentheses.
15
Java has another set of operators, & (and), | (or), ~ (not), and ^ (xor). These are bitwise logical operators
that work on bit patterns. Unfortunately, these can be also used with boolean variables. When applied to
booleans, & and | do NOT follow the short-circuit evaluation rule. So be very careful to make sure you
have && and ||.
16
If you nest if-else to more than two levels, it may be hard to read. Reconsider your design: perhaps you
need helper methods that handle different cases.
17
In the if-else-if sequence, the second if-else is actually nested within the preceding else clause, but
this layout is conventional and more readable. The sequence remains readable even if it is quite long.
18
if (...) do nothing
perform statements in braces (unconditionally)
The second example of missing braces is known as a “dangling” else: the else clause actually pairs with
the inner if, not the outer if as the programmer intended and as the indentation implied.
19
There is a legend in software folklore that a missing break in a program caused the whole telephone grid of
New York to go down, costing millions of dollars. You have to be careful about breaks; they are among the
many opportunities to make a stupid mistake not caught by the compiler. Attention to detail is key.
20
The purpose of this case study is both to practice with if-else and boolean expressions and to discuss
OO design, team development, and software reusability.
21
Your assignment is placed into the context of a larger team effort. All you need to know is the public
interface for your class CrapsGame, i.e., its two public methods.
22
It would take a long time to test your class in the real applet, with random numbers of points coming up on
the dice. You want a more controlled test, in which you can specify the outcome of a “dice roll,” and you
need to run through all relevant sequences of “roll” outcomes.
23
Note how the CrapsGame class is used first in the Craps applet, then in the CrapsStats application. This is a
simple example of reusability.
24
How can you test whether two Strings have the same values?
if (str1.equals(str2)) ...
Which binary operators have the higher rank (are executed first), relational or logical?
Relational. First arithmetic (*, /, and %, then + and -), then relational, and logical last.
26
What are breaks used for in a switch? What happens if you forget one?
A break instructs the code to break out of the switch and go to the statement after the switch. If a break is
missing, the code “falls through” and continues with the statements in the next case.
This is a rather technical chapter: it deals with several important Java concepts and syntax details.
These objectives are within the AP Java Subset for the A-level exam. There are many other details that are
left out. Java is a big language.
Occasionally a class may have a private method that is used within the class but is not callable from methods
of other classes.
A method’s arguments of primitive data types are treated differently from arguments that are objects. More
about this later.
If a name consists of several words, the second and subsequent words are capitalized.
Like other variables, the names of method’s arguments start with lowercase letters.
Note that we talk about the types of the arguments, not their names.
The return type alone is not sufficient for distinguishing between overloaded methods.
Ambiguity may still remain if the types do not match exactly. For example, if there are overloaded methods
for (int,double) and for (double,int), and you call a method with (int,int), then the compiler
reports an error.
A method is normally called for a particular object; a constructor cannot be called for a particular object,
because that object does not yet exist. Constructors then are more like static methods (discussed later).
The default values for fields are as follows: 0 for numbers, false for booleans, and null for objects. Any
constructor sets a field to the default, unless the field is explicitly set to some value. If a field is an object, a
constructor may create that object by invoking a constructor for that object’s class.
10
This example shows four constructors for the Fraction class, including the no-args constructor and the
“copy” constructor.
11
If the fields change, only one constructor will have to be modified. Here we don’t gain much by using this,
but in other situations where we have rather big constructors that are almost identical, we can avoid
duplicating a large chunk of code. Easier to debug and test, too.
12
The operator new returns a reference to (address of) the newly created object.
A copy constructor
Fraction f4 = f3;
does not create a copy of f3; it simply sets f4 to refer to the same object as f3 — two references refer to the
same place in memory. Each form has its use.
13
Java VM keeps track of how many variables refer to an object. Once this count becomes 0, the object is
disposed of and its memory released. This is roughly how the automatic garbage collection mechanism
works.
14
“Static” is basically a memory category. When a program is loaded, a chunk of memory is allocated to hold
the program’s code and permanent data. This memory is called “static,” as opposed to the “dynamic”
memory allocated for each newly created object. Dynamic memory is allocated and freed as objects are
created and disposed of. If you have a constant that is the same for all objects of the class, there is no need to
duplicate it in each object; instead you may declare this constant as static to store it once in static memory,
together with the class’s code. Hence the term “static.” Instance variables are held in “dynamic” memory.
15
Static fields are also called “class” fields because they belong to the whole class and you access them using
the class’s name, not a particular object’s name. The latter is allowed but is bad style.
16
If you initialize a static field in a constructor, it will be reset each time you create an object of the class. This
defeats the purpose of a static field.
Classes such as Math or System have no public constructors. A class like this cannot be instantiated: you
cannot create instances (objects) of the class.
17
It is only natural that static methods cannot access instance variables: the latter belong to a particular object,
and a static method doesn’t know which object to use.
18
Of course, the method’s code is not duplicated for each object but stored in static memory. But the local
variables and the parameters passed to the method are dynamically allocated, usually on the system stack.
When the method is exited, the stack space is deallocated.
The object for which the method is called basically serves as an implicit argument passed to the method.
The code
obj.myMethod(x, y, z);
is similar to:
myMethod(obj, x, y, z);
OOP uses the former syntax because it is more expressive and is needed for polymorphism.
19
Again, instance methods and constructors can access all fields (both static and instance fields) and call all
methods (both static and instance methods) of the class. Static methods can access only static fields and call
only static methods.
20
If you want to call non-static methods or access non-static fields in main, you have to first create an object of
the class, then call its methods or access its fields. The following will work:
It is a bit of a paradox that main constructs the first object of the class of which it is a method. On the other
hand, why not: main is a static (class) method, so it doesn’t belong to any particular object.
21
This applies to Boolean expressions, too. If an expression cannot be converted to the appropriate type (e.g.,
if a method expects an int and the expression’s result type is a double), then the compiler reports an error.
22
The compiler first looks for the exact match between the types of arguments in a call and the available
overloaded methods; if there is no exact match but some arguments may be promoted to make a match, the
compiler does that.
23
So, there is no way to write a swap(int x, int y) method in Java. A method cannot change the value of
a variable (of a primitive data type) passed to it. Actually, this is not such a big limitation as it might first
appear. If a method needs to change a variable’s value, that variable is usually a field in an object or an
element in an array or in some data structure.
24
It is OK stylistically to use the same name for a variable passed to a method as an argument and for the
method’s own formal parameter. Their scopes are different.
The method can treat its formal parameter as a local variable and do whatever it wants to it, but the original
value remains unchanged.
25
This is different from other languages, such as C++, where you can pass an object either “by value” (copy
the whole object and pass the copy to the method), or “by reference” (pass the address of the same object to
the method). In Java the object is NOT copied and a duplicate reference of the original reference is passed to
a method.
Still there is no way to write swap(SomeClass obj1, SomeClass obj2) in Java. If we try:
this code only swaps copies of the references passed to it. Strictly speaking, references to objects are passed
by value.
26
The first situation is not very common: in a good OOP design a method is supposed to work on the object for
which it is called, not an object passed to it as an argument. The second situation is commonplace.
27
The ChessGame object creates a Player object and passes it a reference to this game (e.g., to let the player
report its moves back to the game object).
28
So a return statement does two things: quits the method and returns a value to the calling method.
It is up to the calling method to decide whether it wants to use the returned value —
sometype x = someMethod(...);
— or ignore it:
someMethod(...);
29
If more than one return is unconditional, the compiler will report an “unreachable code” error.
30
if (n % 2 == 0)
return true;
else
return false;
as opposed to simply
return n % 2 == 0;
31
Some people insist on having only one return statement in a method (and having no return in a void
method), but there is no real justification for that. There is nothing wrong with
return false;
32
For example,
A programmer tries to minimize what others (clients) need to know about her class, even if she herself is
“one of the others” when working on other classes. The idea is to keep things localized, so that if something
changes in the implementation of one class, other classes remain unaffected.
Programmers agree on the public interfaces for their classes, then go to work on their classes and often test
them separately, too.
34
Static public constants (e.g., Math.PI or Color.blue) do not violate the spirit of encapsulation because
they are specifically intended to be used by the class’s clients.
35
The class’s public interface is everything other programmers need to know to use the class.
36
num is private to the class Fraction. It is totally fine to refer to this.num and other.num in Fraction’s
methods.
37
Thanks to accessors, you can change the type of a field or even the whole structure of fields but leave the
class’s interface unchanged. Modifiers provide an opportunity to perform additional checks and make sure
that fields are getting valid values.
38
This applet creates three objects of the same class, three “vending machines.” Each machine handles its own
events; the buttons on different machines can be pressed in any order.
39
Each vending machine has a Vendor object attached to it that keeps track of the inventory for that machine
and processes its sales. The Vendor class also defines a static field totalSales that accumulates total
sales from all vending machines.
40
41
What is the syntax for referring to a public static field outside the class?
ClassName.fieldName
42
Are arguments of primitive data types passed to methods “by value” or “by reference”?
By value.
Can a method create a new object and return it to the calling method?
Yes.
43
Define encapsulation.
Hiding the implementation details of a class (by making fields and helper methods private).
Are private fields of an object hidden from other objects of the same class?
No, a method has access to private fields of other objects of the class.
In the Snack Bar applet, is Vendor derived from VendingMachine or vice versa?
Neither: A Vendor object is a field in a VendingMachine object.
Chapter 90
Processing text is what computers do much of the time. Your Java compiler is one example of a program
that does a lot of handling and parsing of strings. Handling strings is pretty straightforward and convenient
in Java.
The char data type is not in the AP Java subset, while strings are. However, any reasonable course will
teach chars. One of the reasons for excluding char from the subset was the perceived danger of confusing a
char constant 'x' with a string constant "x". An unstated objective of this chapter is to get a clear
understanding that char and String are two different data types. char is a primitive data type; strings are
objects.
There is no need to import java.lang.String because the java.lang package is imported automatically
into all classes.
The + and += operators for strings are an exception in Java, the only example of overloaded operators for
objects.
Like the char type, String objects internally represent characters using Unicode.
If all the instance fields in a class are private and none of the methods can directly or indirectly set the field
values, then the class’s objects are immutable. A few String methods create and return a different string,
but none of them changes the string for which they were called. The Integer, Character, and Double
classes, discussed later, are immutable, too.
Thus it is safe for immutable objects to copy references rather than the contents. Cloning (creating copies of
objects) is not required. This may save time when Strings are stored in lists, etc.
8
On the other hand, the immutability may result in tremendous inefficiency when strings are modified often,
especially when a string is gradually built by appending characters or numbers to it. Programmers should
use the StringBuffer class for these tasks.
You may need an empty string as a starting point when you plan to append items to a string.
10
11
Character positions in strings are counted starting from 0, so str.charAt(0) returns the first character and
str.charAt(str.length() - 1) returns the last character. This is consistent with indices in arrays
(Chapter 10): the index of the first element is 0.
12
It is actually convenient that the k-th char is excluded from the substring. The length of the substring is
k - i.
13
It looks like the += operator for strings violates immutability. In fact the string is not changed, rather the
reference is reassigned. s1 += s2 is the same as s1 = s1 + s2. So if you have
14
String has four overloaded versions of indexOf and four versions of lastIndexOf.
lastIndexOf(ch, fromPos) starts looking at fromPos and goes backwards towards the beginning of the
string.
15
You cannot use relational operators for comparing the contents of strings.
s1.compareTo(s2) returns an int. Basically if s1 is “smaller” than s2, the result is negative, and if s1 is
“larger” the result is positive. compareTo returns 0 whenever equals returns true.
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The
character sequence represented by this String object is compared lexicographically to the character sequence represented by the
argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is
a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal;
compareTo returns 0 exactly when the equals(Object) method would return true.
This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some
index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more
index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as
determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of
the two character values at position k in the two string — that is, the value:
this.charAt(k)-anotherString.charAt(k)
If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case,
compareTo returns the difference of the lengths of the strings — that is, the value:
this.length()-anotherString.length()
16
Note that these methods do not change the string s1 but create and return a new string.
trim() only removes whitespace at the ends of the string, not in the middle.
17
s1.toUpperCase();
s1 = s1.toUpperCase();
The variable s1 is reassigned to the new string returned by s1.toUpperCase(); the old string is disposed
of.
18
The Object class (and therefore any object) has a toString method that returns a cryptic description of the
object. It is a good idea to override this default method and define a more suitable one for your class. As the
example shows, this method is used for implicit “casting” of objects of your class into strings. It works with
the print and println methods and with the + operator for strings.
19
A wrapper class has a constructor that takes an item of the “wrapped” type as an argument. For example,
Integer is a wrapper for int:
int x = 5;
Integer obj = new Integer(x);
The wrapped type can be a class, too. The wrapper class adds run-time functionality to the wrapped object.
In this case, Integer and Double just provide handy static methods for numbers.
20
By convention, a static method valueOf in a class converts something (its arguments) into an object of this
class. For example:
21
As usual in Java, there is a hierarchy of subclasses and rather elaborate rules for specifying different formats.
For example, you can define
Then
System.out.println (dollars.format(12345678.987));
displays
$12,345,678.99
22
In a real program you should use exception handling with number conversions to avoid aborting the program
when the user mistypes a character:
try
{
String str = input.readLine();
int x = Integer.parseInt(str);
{
catch (NumberFormatException e)
{
... // show a friendly message that an error has
// occurred and give a chance to reenter
}
23
24
25
26
The StringTokenizer’s constructor takes a string, extracts all the tokens, and places them into a queue.
Then the nextToken method retrieves and returns the next token from the queue.
27
You can either call the countTokens() method to find out how many tokens you have or call
hasMoreTokens() to see if there are any tokens left in the queue.
28
This applet uses the same text field for input and for output. The initial version requires spaces around + and
- signs. The version extended in the lab assignment can handle input with no spaces: it adds spaces around
arithmetic operation signs.
29
This lab and the end-of-chapter exercises give you a chance to get comfortable with String methods and
number-to-string conversions.
30
How can you include a double quote character into a literal string?
\"
31
What is more efficient for strings: == and other relational operators or equals and compareTo methods?
This is not a matter of efficiency: you must use equals and compareTo to compare the contents of strings;
== compares references, which are equal only if they refer to exactly the same string.
33
Name a few Character methods that help identify the category to which a given char belongs.
isDigit, isLetter, isUpperCase, isLowerCase, isWhitespace.
This chapter is only an introduction. More on arrays in Section 11.6, “Iterations and Arrays,” and in
Chapter 12.
There is indeed some confusion in the usage of “element.” In some situations, the word refers to the location
in an array, as in “set the value of the k-th element.” In other situations it refers to a value stored in the array,
as in “find the smallest element.” This dual usage is somewhat similar to the situation with the term
“variable.” This is no big deal, as long as everyone understands the difference between a location and a
value stored in it.
The idea is not to save names, of course, but to be able to handle an array’s elements uniformly, using
algorithms.
The convention of starting indices from 0 comes from C. It is easy to get used to.
That’s the beauty of it: the index may be a variable calculated at run time; it can be used in algorithms.
does not really resize arr: it simply throws away the old array and allocates a new one with default values.
“Throws an exception” means reports a run-time error with rather detailed information about where in the
code it occurred and aborts the program.
Without arrays it would be difficult to process a collection of items algorithmically. Difficult but possible:
with linked lists (one of the subjects in Java Methods AB).
“Direct access” means you can go directly to where the item is stored (like a particular track on a CD), as
opposed to scanning from the beginning to find an item (as on a tape).
10
This has several implications: you have to create (initialize) it before you can use it, it is passed to methods
as a reference, etc. You can pass an array to any method that expects an Object type of argument. If you
want to test it, try:
11
The second form, with a list of initial values, is not in the AP subset.
12
As for fields: 0 for numbers, false for booleans, null for objects. The elements get default values even if an
array is a local variable. You can think of an array’s elements as sort of like its “fields.”
13
14
If you try to use it, (e.g., arr.length or arr[k]), you’ll get a null reference exception.
15
16
It is important to understand this two-step process for initializing an array of objects: first you create the
array object as a whole; then you create each element.
17
This example shows three ways to get an object: set it to a constant, create it with new, or get it from a
method call.
18
The for loop has not been formally introduced yet, but you can sort of see what’s going on.
19
So you can write a method that swaps two elements of an array (next slide).
20
22
Since any type of reference can be set to null, it is legal to return null from a method that is supposed to
return an array. This means the array has not been created in the method (not to be confused with an array
that has been created but whose elements are set to null).
Again, the form with a list of values in braces {...}, called “anonymous initialized array,” is not in the AP
subset.
23
For some reason, 2-D arrays have been excluded from the AP-A subset, and remain only in the AP-AB
subset.
24
25
Nothing unusual: an array of rows contains objects; each object happens to be an array.
26
27
29
Many people prefer to always use braces, as it is easier to add statements to the body of the loop.
When we say “increment” we really mean any change in the variables tested in the condition.
Another example would be reading a file. When the end of a file is reached, its state changes and this can be
tested in the condition.
One of the branches of computer science aims at developing techniques for proving the correctness of
programs mathematically (rather than testing them). Iterations cause a bit of a problem in this effort, and
loop invariants were introduced as a tool to overcome this difficulty.
10
11
12
The first idiom assumes that only the first n elements of the array are used.
13
14
15
16
17
18
Some people believe a method should have only one return statement. Instead of using a return statement
inside the loop, they would set a Boolean flag in the loop and test it in the condition; this would make their
code more cumbersome.
19
20
21
22
23
24
25
26
To find the sum of an arithmetic sequence, take the average of the first and the last terms and multiply it by
the number of terms.
27
28
29
30
This chapter is a survey of the basic array algorithms including the three standard sorting algorithms. It
covers all the related material within the scope of the A-level AP CS course outline.
An unstated objective is to get a feel for the big-O of different algorithms without introducing this concept
formally.
The average number of comparisons only makes sense if we always choose one of the elements randomly as
a target. If the target-not-found situation is allowed, and we don’t know how often it happens, we can’t talk
about the average. Also the average doesn’t make sense if the target is more often equal to, say, one of the
first elements.
The method is familiar to anyone who has ever played the “guess a number” game.
Sounds like a recursive algorithm but, as we’ll see shortly, there is an equally simple iterative
implementation.
The while loop always terminates, because the difference right - left is always decreased at least by 1.
Typically, in divide and conquer algorithms, the difference between the average case and the worst case time
is negligible.
10
11
12
In many applications it is faster to keep the array sorted rather than to resort it every time a value is added or
removed.
13
14
Or it could return a boolean telling whether the insertion was successful, or just “throw” an
IndexOutOfBoundsException.
15
At this point, a list is represented as an array. In general the term “sorting” can apply to any list (e.g., a
linked list).
16
What kind of tricks? Well suppose we know that the list contains only values 0 through 9. We can scan the
list once and count the number of times each value occurs, then generate a new list with the appropriate
number of 0s, 1s, etc.
17
When n is large enough, An2 eventually overtakes Bn⋅ log n no matter how small A is and how large B.
18
19
This situation, where a recursive call is the last statement in the method, is called “tail recursion.”
20
21
22
Here we search for the place to insert the value starting from the end, not from the beginning. This works
better when the array is already sorted.
23
24
25
26
Another divide-and-conquer algorithm. All the work actually happens at the merging phase.
27
Mergesort needs a temporary array, but it is not a good idea to allocate a large array in a recursive method
because it will be allocated at each level of recursion, which may take too much space. Luckily, in this
algorithm we can reuse the same temporary array at all levels of recursive calls. For example, we can make
temp a private static field in the Mergesort class.
28
The suggested shortcut is not a canonical “textbook” feature. It’s just an example of how a minor change can
dramatically improve a recursive algorithm.
29
The Arrays class lacks obvious methods such as sequentialSearch or methods for copying arrays.
30
31
In this applet we want to be “fair” and run each sorting algorithm on the same set of “random” data. We use
the java.util.Random class, which allows us to generate the same “random” sequence several times.
32
33
How many comparisons are needed in the worst case to find the target value among 15 values using
Sequential Search? Using Binary Search?
15 and 4 (assuming we want to make sure that the value is in the array).
How many comparisons are needed to find the smallest element in a random array of length n?
n-1
Name methods of the Random class that return a random int; a random double.
nextInt(n) and nextDouble().
Chapter 120 1/2
This chapter covers the required AP topics and, with minor exceptions, stays within the A-level subset.
The last bullet has to do with the so-called “multiple inheritance.” In Java a class can extend only one
superclass, so there is no multiple inheritance for classes. Otherwise it would be confusing if both
superclasses had the same method. But it is often useful to consider the same object from many different
points of view. For example, the same person can be a student, an athlete, and an AP scholar. If a class
implements multiple interfaces, its objects can be treated as any of the interface types.
Interfaces can also define public static constants, but this is outside of the subset and not very important here.
Different classes can implement the same interface in completely different ways.
Many library methods (e.g., addActionListener) expect a parameter of an interface type. If my class
implements that interface, I can pass an object of my class to the library method as an argument.
This is an occasion for polymorphism. The correct method will be called for each object in the array
automatically. For example:
The compareTo method defines the ordering for the objects of a class. If defined, it is called natural
ordering.
The parameter has the type Object, so that the signature of the compareTo method does not depend on a
particular class. As a rule, other is an object of the same class whose compareTo is running and it is cast
to that class type.
Several library classes implement Comparable. Some library methods expect Comparable objects (e.g.,
Arrays.sort).
9
The compareTo method is not required to return the actual “difference” between the objects. Try, for
example,
10
11
Unfortunately, two overloaded add methods, and they have different return types. add(obj) is inherited
form Collection, while add(i, obj) is specific to List. Perhaps “insert” would be a better name for
the latter.
contains tells you whether the list contains an object that equals to obj, but it does not tell you its
position. This method is also inherited from Collection. indexOf is more specific to List: it returns the
index of the first occurrence of obj in List (again, using equals for comparison), or -1 if not found.
12
As opposed to a regular array, ArrayList’s methods check that an index is from 0 to size, not just from 0 to
capacity.
13
14
For example:
15
If you know the maximum number of items you are going to store in the list, use the third constructor, setting
the initial capacity to the maximum number of items to avoid costly reallocation and copying of the array.
16
When you retrieve a value, cast it into appropriate type if you need to call its specific methods. Otherwise,
polymorphism can take over. For example:
— no need to cast.
17
It is a common mistake to forget that remove(i) and add(obj, i) shift the values that follow the i-th
value and change their indices. They also change the size of the list.
18
This type of index file allows you to quickly find any word or a combination of words in a large document.
19
This could be a team project: one programmer writes DocumentIndex; the other IndexEntry.
The arrows on this picture follow the UML (Universal Modeling Language) notation. DocumentIndex
extends ArrayList, while IndexEntry has an ArrayList as a field.
20
Name the List methods that can add a value to the list.
add(obj) and add(i, obj).
Name the List methods that can tell you whether a given value is in the list.
contains(obj) and indexOf(obj).
In an ArrayList, should the indices be less than the size or the capacity?
The size. For example list may have capacity 100 but be empty. Then list.get(0) generates
IndexOutOfBoundsException.
What happens when the size has reached the capacity and you try to add a value?
A new array of a bigger capacity (usual of the double capacity) is allocated and all the values are copied into
it. The old array is discarded.
Chapter 130
If you want to learn the technical details about Java’s IO package, this is the wrong place. The main
objective here is to provide conceptual background on files and streams, with only a glimpse at their
implementation in Java. For student projects, EasyReader and EasyWriter are adequate.
Recall that a file is a software entity. The hardware knows nothing about files. The operating system does.
The file name may give a hint as to how it “prefers” to be treated. Surely, a file that contains only ASCII
characters and has CR+LF every so often is likely to have been created as an ASCII file and is probably
intended to be used that way. But nothing in a file’s contents specifically demands a particular treatment.
There have been reports in the press of terrorists using software that hides secret encoded messages in
harmless-looking image files.
There is also the matter of displaying a file. For example, an HTML file is an ASCII file and may be
presented as such in a plain-text editor, but it appears differently in a browser.
The reverse is true, too: you can treat a binary file as a text file. Whenever you encounter a byte that
contains a value corresponding to LF, the program will decide that this is the end of a line. In the early
releases of MS DOS, files contained a special EOF (end of file) marker at the end. The only problem was
that a binary file could have this value in the middle by accident, and the copy command would stop at that
place. You needed to add a command switch /b (for binary) to tell the program to treat the file as a binary
file.
The hex dump of a text file in this slide has been produced by the ancient program debug (c. 1982, still
included with Windows). The display on the right shows those values that correspond to printable ASCII
characters.
10
The advantage of streams is that they provide a uniform way of treating files and devices. For example, in
Unix and other operating systems it is easy to “redirect” screen output to a file.
11
For text files it is especially important to be able to treat various data sources (a file, an Internet data stream,
etc.) uniformly. It is also more common to read or search text files sequentially, from the beginning.
12
Thus you can open the same file as a stream in one situation and as a random-access file in another.
13
Random-access is convenient. That’s why people have switched from tapes to CDs and from videotapes to
DVDs.
14
15
Java IO is not for the faint at heart. It looks like the developers went all out to confuse programmers. That’s
why programmers are such well-paid specialists.
16
The developer of the RandomAccessFile class probably was not a “team player,” as they say in the
industry. Or this part of the project was assigned to a different group.
17
18
19
20
EasyReader treats a file as a text stream and has methods for reading numbers, words , and lines.
EasyWriter allows you to create a new file or to append data to an existing file. Both are based on
java.io.
21
Be careful: if readInt or readDouble is followed by readLine, the latter will read whatever remains on
the line, often just the end-of-line character. You need another readLine call to read the line that follows
the number(s).
22
new EasyWriter(filename, "app") opens an existing file and prepares it for appending data at the
end.
23
Name a few types of files that are normally treated as text files.
.txt files from various sources, program source files, HTML files.
Can you open the same file as a text file and as a binary file in different programs?
Yes. For example, an e-mail program may send all attachments as binary.
Do you think .jar (Java archives) files that contain compiled library classes are treated as streams or
random-access files?
Streams would make it too inefficient to find a particular class. They are indexed random-access files.
24
Which java.io stream classes have a method for reading a line of text?
BufferedReader and RandomAccessFile
Do EasyReader / EasyWriter use the java.io package or the system services directly?
java.io.
Chapter 140
This chapter introduces basic general computer graphics concepts as well as a few specifics for Java.
An example of a vector device is a plotter. Some models actually include a moving “hand” that grabs pens
of different colors from a pen holder.
The number of pixels in the raster vertically and horizontally is called the graphics resolution. For example,
a computer screen may have a resolution of 1024 by 768 (pixels).
More importantly, Graphics2D supports polymorphic treatment of shapes and lets you define your own
shapes.
The “paint” method comes from the very early versions of Windows.
How do we get hold of a Graphics2D object, then? Actually g is a Graphics2D object in disguise. All
you have to do is cast it into Graphics2D, if that’s what you need:
10
11
repaint places a “repaint” request into the application’s events queue. It won’t be processed until the
earlier events have been processed.
12
The translate method in graphics shifts the origin to a specified location. Graphics2D has a method to
rotate the coordinates by a certain angle.
13
14
This is a uniform way to specify the positions of different shapes. To draw a circle with a radius r and
center (x, y), you need to write
15
16
17
clearRect fills the rectangle with the component’s current background color.
In drawRoundRect, horzD and vertD are the horizontal and vertical diameters of the oval used to round
the corners.
18
In the drawString method, x, y are the coordinates of the left end of the base line.
19
Serifs are the small horizontal strokes in letters. The main categories of fonts are serif vs. sans serif and
fixed-pitch vs. proportional. In a fixed-pitch (monospace) font, the width of all letters is the same, as on a
typewriter. A program editor uses a fixed-pitch font, too (e.g. Courier).
Java has a way to get a list of all the fonts available in a system and choose one of them.
20
This chapter is only a brief overview of Java’s Swing package and event handling classes.
After studying this chapter, the reader should be able to get enough background to research the remaining
classes and methods from Java’s API docs.
Components don’t just “hang there”; they all are attached to each other and eventually to an application
window’s content pane.
A listener is an object.
An interface can also have public static constants declared (see, for example, java.awt.Paint).
Inner classes are a later addition to java. They are not in the AP subset.
We believe inner classes are a cop-out, a step back toward procedural programming. We don’t use them in
this book, but we start using them a little in Java Methods AB because they may be convenient.
10
11
You have to cast the object returned by getSource into the type that caused event. For example
You can attach the same listener to different types of components; then getSource is not very useful.
12
Writing code for menus manually is rather tedious. Some automation is required.
13
The appendix also has an index of examples for each component, listing the case studies, labs, and exercises
where that component is used.
14
15
16
17
18
19
20
There is a way to left-justify or right-justify components, too, by passing an additional argument to the
FlowLayout constructor. For example:
21
FlowLayout is not very precise: it’s hard to control beyond one row.
22
GridLayout is very precise, but components may be forced into funny shapes. Also there is no convenient
way to skip a cell: you have to put a dummy component (e.g., an empty panel) into it.
23
24
25
26
A combination of nested horizontal and vertical boxes is often a flexible way to achieve a desired layout.
27
28
29
30
mouseClicked checks that the button was pressed and released in the same place, which may result in
missed clicks.
For example, typing Shift+A, causes five calls: Shift pressed, ‘a’ pressed, ‘a’ released, Shift released, ‘A’
typed.
10
11
Working with bit masks requires bit-wise logical operators, explained in Section 16.3 of the book.
12
13
14
15
16
17
In this example, the file Bells.wav is located in the audio subdirectory of the directory that contains the
applet’s HTML file.
18
19
20
There is an error in the book: it says ImageIcon’s constructor takes a relative URL. This is true in
applications (it takes a relative pathname) and works in the applet viewer, but not in applets run in browsers
or IDEs. See http:/www.skylit.com/javamethods/errata.txt.
21
22
What are the units and the origin for the coordinates returned by the MouseEvent’s getX and getY
methods?
Coordinates are in pixels, relative to the upper-left corner of the component to which the listener is attached.
23
The industry has embraced OOP, but no formal studies of these claimed benefits have been carried out.
“D is a B” meaning “D is a more specialized kind of a B.” This contrasts with “W has a P” meaning P is a
part of W (in Java, P is a field in W).
If a class D could extend two classes, B1 and B2, and both B1 and B2 had the same method or field, which
one would be inherited? That is why multiple inheritance in Java is limited to interfaces.
A concrete class can redefine some of the methods defined higher in the hierarchy.
10
11
12
A programmer can extend a library hierarchy, adding his or her own classes.
13
14
15
16
Implementing a hierarchy of classes is not necessarily a good team project. One person may have a better
grasp of the whole tree (or at least a manageable part of it).
GUI components are a nice example of a hierarchy; that is what made OOP popular to begin with.
It is not easy to make changes in a hierarchy of classes, because it is may be hard to figure out which class
does what, and they are all interdependent.
17
18
Making classes concrete too soon reduces the opportunities for reuse. On the other hand, a large hierarchy of
abstract classes may be hard to follow.
19
Again, instance methods and constructors can access all fields (both static and instance fields) and call all
methods (both static and instance methods) of the class. Static methods can access only static fields and call
only static methods.
20
21
22
23
Programmers on a team only need to know the public interfaces of other classes.
Objects with more abstract classes are more likely to be reused. Classes with limited public interfaces are
easier to document and reuse.
Program maintenance is easier due to encapsulation: if a class’s fields change, only that class is affected.
24
25
Here we want to put both a HumanPlayer and a ComputerPlayer into the same array. We also want to
pass each of them to the addPlayer method that expects a Player argument.
26
27
28
29
In effect OOP passes the burden of software development from implementation to design.
30
31
Name the main software development concerns that are believed to be addressed by OOP.
Team development, reusability, friendly GUI, easier maintenance.
Can an interface extend another interface? If so, what does that mean?
Yes it can. A subinterface inherits specifications for all the methods from the superinterface.
Why do you think Java does not allow a class to extend several classes?
If two base classes have the same field or method, the subclass won’t know which one to inherit.
32
What is abstraction?
Ignoring irrelevant details and focusing on the relevant ones.
What is polymorphism?
Automatically calling correct methods for objects disguised as more generic types.