Top Banner
Chapter 1 1 Two possible activities for this chapter are to look inside of an old computer and to inventory the programs installed on a new one. 2 The Internet is the best resource for more detailed information on hardware and software and the Internet itself. 3 Early computers used vacuum tubes and relay switches. Semiconductor technology allows manufacturers to etch microscopic devices into layers in a silicon chip. 4 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. 5 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. 6 The CPU chip is packaged inside a ceramic case. The chip itself is as small as 3/4".
111

java notes

Nov 18, 2014

Download

Documents

aniran

condensed notes on java
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: java notes

Chapter 1

1

Two possible activities for this chapter are to look inside of an old computer and to inventory the programs installed on a new one.

2

The Internet is the best resource for more detailed information on hardware and software and the Internet itself.

3

Early computers used vacuum tubes and relay switches. Semiconductor technology allows manufacturers to etch microscopic devices into layers in a silicon chip.

4

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.

5

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.

6

The CPU chip is packaged inside a ceramic case. The chip itself is as small as 3/4".

SIMM stands for Single Inline Memory Module.

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.

7

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

Page 2: java notes

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.

9

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

A modem is used to connect to a host computer via a telephone line.

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

More on different types of applications and OOP in Chapter 3.

Page 3: java notes

14

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

17 ==> 00000000 00000000 00000000 00010001-17 ==> 11111111 11111111 11111111 11101111

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

From the Unicode page:

“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 forideographic 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

FTP — File Transfer Protocol.AIM — AOL Instant Messenger.e-mail uses SMTP — Simple Mail Transfer Protocol.www uses HTTP — HyperText Transfer Protocol.

These application-level protocols sit on top of TCP/IP.

Page 4: java notes

19

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.

Yahoo is a popular general-purpose portal.

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 ==> TT, F ==> FF, T ==> FF, F ==> F

What are CPU, RAM, and ROM?Central Processing Unit (microprocessor in personal computers), Random-Access Memory (for holding data and programs), Read-Only Memory (for holding the start-up program, hardware diagnostics, and configuration program).

Approximately how many bytes are in a megabyte? In a gigabyte?One million. One billion.

Name six I/O devices.Display, keyboard, mouse, sound card, printer, scanner

Is a device driver a hardware or a software entity?Software

Is a file a hardware or a software concept?Software

Page 5: java notes

22

Describe the main difference between a console and a GUI application.A console application uses a simple text user interface. A GUI application uses graphics, menus, icons, etc.

What is the 8-bit binary representation for 6?00000110

In Java, how many bytes are used to represent an integer?Four.

What is a search engine?A program that helps to find documents on the Internet containing specified keywords or phrases.

Name three applications that run on the Internet.The World Wide Web, e-mail, AIM.

Page 6: java notes

Chapter 2

1

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.

2

An unstated objective is to make students comfortable and successful in simple projects.No programming is involved. (Programming usually includes conditional and iterative statements.)

3

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.

The languages we know:* Natural languages: English, Spanish, etc.* Sign languages: ASL (American Sign Language), Semaphore Flag Signaling, etc.* Programming languages: Basic, C++, Java, etc.

4

A text with embedded HTML tags is stored in a plain text file called “source.”

An HTML source file usually has the extension .htm or .html.

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.

Page 7: java notes

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.

A program such as an Internet browser has a built-in HTML interpreter.

6

The HTML tags can be roughly grouped into * Document structure tags: <html>, <head>, <meta>, <title>, <body>, <address>, etc.* Text layout and formatting tags: <h1>...<h6>, <p>, <br>, <hr>, <font>, <i>, <u>, <b>, etc.* Anchors and hyperlinks: <a name=...>, <a href=...>* Lists, tables, images, applets: <ul>, <ol>, <dl>, <table>, <img>, <applet>, etc.

7

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.

8

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

9

In fact, all tags are nested within <html> ... </html>.

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.

The keywords help search engines find the page.

It is customary to put webmaster contact information, last revision date, copyright notices, etc, in the address section.

Page 8: java notes

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 (&nbsp;) 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.

<blockquote> tags can be nested to increase the indent.

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

#panda an anchor in the same documentvoleyball.html a file in the same folderathletics.html#swimteam a particular location (anchor) in another file in the same folderimages/lucie.jpg an image file lucie.jpg in the subfolder images../courses/webdesign.htm go one level up to the parent folder, then to its subfolder courses; take the file webdesign.htm

Page 9: java notes

18

Why use relative URLs?

1. Relative URLs work faster.2. Relative URLs allow you to test and easily move a set of pages to a different host, e.g., from your local computer to your web site hosted by an Internet provider.

Use forward slashes in file pathnames for compatibility with all systems.

19

<ul> Unordered list<ul type="circle/disk/square">

<ol> Ordered list<ol type="1/I/i/A/a" start="1/2/...">

<dl> Definition list<dl compact> — definitions are placed on the same line.

Lists can be nested.

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.

The usemap attribute associates a map with an image.

22

Map coordinates are in “pixel” units with the origin in the upper-left corner of the image.

Circle: xCenter, yCenter, radiusRect: x1, y1, x2, y2 -- coordinates of two opposite cornersPolygon: x1, y1, x2, y2, ...

23

Tables are the most important page layout tool available in HTML.A table cell can contain text, images, lists, other tables, applets

Page 10: java notes

24

It is usually better to set width in relative terms:width="75%" means the table takes three-quarters of the width of the browser window.But sometimes you may want to reserve a specific number of pixels, e.g., for a side bar or an image.

The width attribute is also available for individual cells.

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.

A browser has a built-in Java interpreter for running applets.

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.

Page 11: java notes

28

What is a web page? Web site? Java applet?

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.

A Java applet is a small Java program written for the Internet.

What do HTML, HTTP, WYSIWYG stand for?

Hypertext Markup Language, Hypertext Transfer Protocol, What You See Is What You Get

Define hypertext, HTML source

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.

Identify the file types by their extensions:.htm, .html HTML documents.txt Text files.pdf PDF files (Adobe Acrobat).jpg .gif Image files.wav Audioclip files.class Compiled Java code (class files)

29

Document structure tags:<html> <head> <title> <meta> <body> <address>

Document layout tags:<h1> ... <h6> <p> <br> <hr> <blockquote>

Text formatting tags:<b> <i> <u> <strong> <cite> <big> <small> <sup> <sub> <font>

Tags for creating hyperlinks:<a name=...> <a href=...> <a href="mailto:...">

What are the supported HTML list types and their respective tags?<ul> <li> Unordered list <ol> <li> Ordered list<dl> <dt> <dd> Definition list

Tags for working with images, tables, and applets:<img> <map> <area><table><th> <tr> <td> <caption><applet> <param>

Page 12: java notes

Chapter 3

1

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.

2

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.

3

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.

4

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.

5

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.

6

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.

Page 13: java notes

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.

8

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

9

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.

Page 14: java notes

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.

Page 15: java notes

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.

Classpath is explained at skylit.com/javamethods/faqs.html.

C:\javamethods\EasyIO presumably holds EasyReader.class (see the next slide).

27

We supplied EasyReader and EasyWriter because native Java IO classes are quite confusing and rather hard to use.

Page 16: java notes

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

JFrame is a Swing library class for a generic program window.

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.

Page 17: java notes

33

What are some of the current software development concerns?Team development, reusability, easier maintenance, portability, user-friendliness.

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.

What are editor, compiler, linker, debugger used for?Creating source code (program text); compiling source into object code (CPU instructions); combining object module(s) and libraries into an executable program; running a program in a controlled manner and correcting bugs, respectively.

Define IDE.Integrated Development Environment — combines software development tools under one GUI.

How is a compiler different from an interpreter?A compiler creates object modules that can be linked into an executable. The compiler is not needed to run the executable. An interpreter interprets the source and executes appropriate instructions. It must be installed and active to execute program statements.

34

Name some benefits of Java’s compiler + interpreter approach.Bytecodes are device-independent, load faster, allow for security checks, and don’t reveal source code.

What is a console application?An application in the style of the old teletype or terminal (console): uses a dialog with text prompts and user input.

What are command-line arguments?An array of strings passed to the program from the operating system command line that runs the program (or from a special option box in an IDE).

What is a GUI application?An application with a graphical user interface, often used with a mouse or another pointing device.

What is the difference between a GUI application and an applet?An application runs on the computer where it is installed. An applet is embedded in a web page and is usually downloaded from the Internet (or a local network) together with the HTML document.

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.

Page 18: java notes

Chapter 4

1

The Ramblecs case study in this chapter is rich enough to illustrate the main OOP concepts and give students some material for fun exercises.

2

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.

3

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.

4

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.

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.

Page 19: java notes

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:

1. Change extends JApplet to extends JFrame

2. Add a constructor:

public Ramblecs(){ super ("The Ramblecs Game"); // Calls JFrame’s // constructor to add the title bar init();}

3. Add main:

public static void main(String[] args){ JFrame window = new Ramblecs(); window.addWindowListener(new ExitButtonListener()); window.setBounds(100, 50, 160, 310); // x0, y0, width, height window.show();}

7

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.

8

Go to Java API docs (http://java.sun.com/j2se/1.3/docs/api/index.html) and examine the list of packages in the upper-left corner. We will mostly use classes from java.lang, java.util, java.awt, java.awt.event, and javax.swing.

Page 20: java notes

9

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

More on syntax for declaring fields in Chapter 6.

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.

Page 21: java notes

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

charAt is a String method.

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

Methods in different classes may have the same name.

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

Page 22: java notes

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.

Page 23: java notes

28

How many classes did we write for Ramblecs? Three: Ramblecs, LetterPanel, and FallingCube.

Name a few library classes that we used.JButton, JPanel, Timer.

What are import statements used for?To be able to use short names for library classes instead of fully-qualified names.

What is a field? A constructor? A method?A field is a data item in an object. A field describes an attribute or a variable value in an object.A constructor is like a method for creating objects of the class.A method is a fragment of code that performs a certain calculation or task and can be called from other constructors and methods. (In the case of a recursive method, it also calls itself.)

Which operator is used to construct an object?new

What is the difference between private and public methods?Private methods can be called only from constructors or methods of the same class. Public methods can be called from other classes as well.

Why are fields usually private?Because fields are more prone to change than are rules for calling constructors and methods. If a field changes, we want to be sure that other classes are not affected.

29

Define an event-driven application.In an event-driven application, some methods are called in response to events, which may occur in any sequence.

Why are GUI applications event-driven?Because different GUI components (menus, buttons, sliders, etc) can be activated in any order.

Is an event listener a class, an object, or a method?An object.

How many action listeners are used in Ramblecs?Two: one for the “Go” button and one for the timer.

What does the following statement do? w.addWindowListener (new ExitButtonListener());

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.

Page 24: java notes

Chapter 5

1

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.

2

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.

3

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.

4

Make sure you do not carry a // comment over to the next line. If you do, you need another // mark on that line.

Placing // at the beginning of a line comments out 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.

5

javadoc.exe is in the JDK...\bin folder. To run javadoc from the command line, enter:C> javadoc MyFile1.java MyFile2.java ...

EnterC> javadoc ?

to see the list of all the options and the general command syntax.

6

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.

Page 25: java notes

7

See Java Methods p. 125.

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.

8

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.

9

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

Class fields should have prominent names: i or x won’t do.

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.

Page 26: java notes

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

Individual elements in a declaration are separated by commas:

int x, y, z;

20

There are two common styles for braces:

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.

Page 27: java notes

22

Name as many uses of comments as you can.(1) document the program purpose, authors, copyright, revisions;(2) explain obscure logic or usage(3) temporarily comment out fragments of code

What does javadoc do?Automatically generates HTML documentation from “documentation” comments in the source code.

Explain the difference between syntax and style.Syntax is required by the language and checked by the compiler; style is a convention among programmers and is optional.

Why is style important?It makes programs easier to read and understand for your colleagues (and for you yourself).

Roughly how many reserved words does Java have?50

23

Explain the convention for naming classes, methods and variables.Class names start with a capital letter. Method and variables names start with a lowercase letter. Subsequent words are capitalized. Method names often sound like verbs, class and variable names like nouns.

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.

What can happen if you put an extra semicolon in your program?Depending where it is, it may either be caught by the compiler as a syntax error or not. If it isn’t caught, it may be harmless or it could cause a logical error that will break your program.

What are braces used for in Java?To mark the code of methods and to group several statements into one compound statement.

Is indentation required by Java syntax or style?Style. But it is essential for readability and helps avoid syntax errors.

Page 28: java notes

Chapter 6

1

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.

2

Also review the style: naming variables and using symbolic constants.

3

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.

4

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.

5

Several variables of the same type can be declared in the same statement, separated by commas. A declaration ends with a semicolon.

6

The variable go’s value is the address of the memory location where this JButton object is stored.

So assignment = is an action, not an equation. For example,

count = count + 1;

increments the value of the variable count.

In the same declaration, some variables may be initialized and others not.

7

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.

Page 29: java notes

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.

9

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:

for (int i = 0; i < 100; i++)

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.

for (int i = 0; i < 100; i++)

should be rewritten as:

int i;...for (i = 0; i < 100; i++)

Page 30: java notes

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

A byte represents small numbers, from -127 to 127. short uses two bytes to represent an integer from -215 to 215-1. Unlike C++, Java doesn’t have unsigned types.

17

\... are called escape sequences from the old printer terminology. '\\' represents a backslash character.

3.0 is better than 3. — more visible as a double.

18

In Java you can initialize a symbolic constant later, in a constructor.

19

But there is no need for symbolic constants like

pubic final int ONE = 1;

Page 31: java notes

20

*, /, and % have the same rank.

There is also the unary operator -, e.g.

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

This is another place to be very careful.

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:

int fullWeekCount = dayCount / 7;System.out.println(mins / 60 + " hours and " + mins % 60 + " 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;

gives away a novice. But so does

a += a + b++;

26

Page 32: java notes

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

controlpanel “knows” about whiteboard, but whiteboard is not aware of controlpanel.

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.

What is the type of a variable that holds an object?The class to which the object belongs.

What is meant by the scope of a variable?The area in the source code where the variable is visible.

What is the scope of a field?The whole class.

What is the scope of a local variable?From its declaration down to the closing brace of the block in which it is declared.

Is it OK to give the same name to variables in different methods?Yes, and moreover it is desirable if their roles are similar.

Is it OK to give the same name to a field and to a local variable of the same class?Never.

Page 33: java notes

31

What is the range for ints?from -231 to 231 - 1.

When is a cast to double used?When the operands are ints but we want the correct result as a double. (Be sure to cast an individual operand, not the final result.)

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

When is a cast to int used?To truncate the double result of a calculation and store it in an int. Should compound assignment operators be avoided?On the contrary, they should be used, but not inside fancy expressions.

Page 34: java notes

Chapter 7

1

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.

2

Another objective is to discuss team development and illustrate software reusability in the context of a simple but realistic case study, the Craps applet.

3

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.

4

There is no point, really, in using boolean symbolic constants because you can just use true and false in the code.

George Boole is a British mathematician who studied properties of formal logic.

5

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;

you can write simply:

boolean exceedsLimit = x > limit;

6

= is for assignment, == is for comparison.

Page 35: java notes

7

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

8

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.

9

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

Comparison to null works for all types of objects.

11

Logical operators parallel those in formal logic.

12

Note that || is inclusive or: either one or the other or both.

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.

Page 36: java notes

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

With the extra semicolon, the code will executed as follows:

if (...) do nothingperform 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

Step 3 is here to let you use a switch.

Page 37: java notes

25

What are the possible values of a boolean variable?true, false

What operators are used to compare values of numbers and chars?Relational operators <, <=, >, >=, ==, and !=.

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

Can you have an if statement without an else?Yes, else is optional.

What are De Morgan’s laws?! (a && b) is the same as (!a || !b);! (a || b) is the same as (!a && !b);

Explain short-circuit evaluation.In a sequence of && operators, once you encounter one condition that is false, the rest are not evaluated and the result is set to false. Likewise, in a sequence of || operators, once you encounter a condition that is true, the rest are not evaluated and the result is set to true.

How long can an if-else-if sequence be?As long as you need, usually quite readable. But if it is very long, you might consider a switch.

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.

Can the same case in a switch have two breaks?A case may have several breaks, but all except the last one must be inside an if or else.

Page 38: java notes

Chapter 8

1

This is a rather technical chapter: it deals with several important Java concepts and syntax details.

2

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.

3

Occasionally a class may have a private method that is used within the class but is not callable from methods of other classes.

4

A method’s arguments of primitive data types are treated differently from arguments that are objects. More about this later.

5

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.

6

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.

7

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.

8

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

9

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.

Page 39: java notes

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 = new Fraction(f3);

creates a copy of the object f3 and returns a reference to it.

By contrast, a simple assignment

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.

Page 40: java notes

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:

public static void main(String[] args){ Hello h = new Hello(); System.out.println(h.message);}

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.

Page 41: java notes

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:

private void swap(SomeClass obj1, SomeClass obj2){ SomeClass temp = obj1, obj1 = obj2, obj2 = temp;}

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

Page 42: java notes

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

This possibility is often overlooked: a novice is tempted to write

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

for (i = 0; i < n; i++) if (a[i] == target) return true;

return false;

32

For example,

public String makePrompt (String msg){ return String.toUpperCase(msg) + " ==>"; // toUpperCase is a static method in String that // returns a new string with all caps; // + means concatenation}

Page 43: java notes

33

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.

Page 44: java notes

40

What is the common Java style for method names?Start with a lowercase letter, with subsequent words capitalized. Methods should sound like verbs.

When is it appropriate to define overloaded methods?When two methods perform similar tasks for different types or numbers of arguments.

Are you allowed to define a class with no constructors?Yes. Then Java provides one default no-args constructor.

Can a class have two different no-args constructors?No. Constructors must have different numbers or types of arguments.

What is a good style for naming constructors?There is no choice: the names of all constructors are the same as the name of the class.

41

Describe the difference between class and instance variables.Class variables (declared static) are shared by all objects of the class; instance variables are different in different objects.

Can non-static methods access static fields?Sure.

Can static methods access instance variables?No. Static methods are not associated with any particular object, so how would they know which of an object’s instance variables to access?

Can static methods have local variables?Sure, why not?

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 have more than one return statement?Yes, but all except one must be inside an if or else (or a switch).

Can a method have no return statements?Yes, a void method doesn’t have to have a return.

Can a method create a new object and return it to the calling method?Yes.

Page 45: java notes

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.

Do public static final variables violate encapsulation?Not really: they are global constants intended to be used by other classes.

In the Snack Bar applet, is Vendor derived from VendingMachine or vice versa?Neither: A Vendor object is a field in a VendingMachine object.

Page 46: java notes

Chapter 9

1

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.

2

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.

3

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.

4

\" stands for the double quote character.

Like the char type, String objects internally represent characters using Unicode.

5

Calling a method of a literal string, as in "sometext".someMethod(...), may seem unusual to programmers who are used to other languages. "sometext".equals(str) is often used instead of str.equals("sometext") because the former version works even when str is null, while the latter would throw a null reference exception.

6

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.

7

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.

Page 47: java notes

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.

9

You may need an empty string as a starting point when you plan to append items to a string.

10

As explained earlier, it is a good idea to avoid the copy constructor.

One useful constructor converts an array of chars into a String.

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.

str.substring (i) is the same as str.substring(i, str.length()).

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

String s = "Nice ", t = s;s += "day";

the value of t remains "Nice ".

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.

Page 48: java notes

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.

Here is how Java docs describe compareTo:

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();

doesn’t do anything. The correct statement is:

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.

Page 49: java notes

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

You can also convert a char to a string by using

String s = "" + ch;

By convention, a static method valueOf in a class converts something (its arguments) into an object of this class. For example:

public class Fraction{ public static Fraction valueOf(double x) {...}

should take a double and return a corresponding Fraction.

Here String.valueOf(x) returns a string.

21

As usual in Java, there is a hierarchy of subclasses and rather elaborate rules for specifying different formats. For example, you can define

DecimalFormat dollars = new DecimalFormat("$#,##0.00");

Then

System.out.println (dollars.format(12345678.987));

displays

$12,345,678.99

Page 50: java notes

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

Character is a wrapper class for char.

24

See Java docs for the formal definition of whitespace characters.

25

For example Character.digit('7',10) returns 7 and Character.digit('A', 16) returns 10. Character.forDigit(7,10) returns '7'.

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.

Page 51: java notes

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

What makes the String class unusual?+ and += operators

How can you include a double quote character into a literal string?\"

Is "length".length() allowed syntax? If so, what is the returned value?Yes, it is valid and returns 6

Define immutable objects.Objects that cannot be changed by calling their methods (nor by directly manipulating their fields).

Does immutability of strings make Java more efficient or less efficient?It depends. It may be more efficient if the code involves making many copies of strings. It is less efficient if the code involves changing characters in strings or assembling strings from separate items (chars or numbers). Actually the latter situation is more common. You should then use the StringBuffer class rather than String.

31

How do you declare an empty string?String s = "";

Why are String constructors not used very often?Because you can simply assign a literal string to a variable, so there is no need to make copies of strings.

If the value of String city is "Boston", what is returned by city.charAt(2) ?By city.substring(2,4) ?'s' and "st", respectively.

How come String doesn’t have a setCharAt method?To keep it immutable. StringBuffer has setCharAt(ch,pos).

Is s1 += s2 the same as s1 = s1 + s2 for strings?Yes

Page 52: java notes

32

What do the indexOf methods do? Name a few overloaded versions.Find a character or a substring in a string. indexOf(char), indexOf(String), indexOf(char, int fromPos), indexOf(String, int fromPos)

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.

What does the trim method do?It returns a new string which contains this string with whitespace removed at the ends.

What does s.toUpperCase() do to s?Nothing: s is immutable.

What does the toString method return for a String object?This string

33

Name a simple way to convert a number into a string"" + num;

Which class has a method for converting a String into an int?Integer (the method parseInt)

Name a few Character methods that help identify the category to which a given char belongs.isDigit, isLetter, isUpperCase, isLowerCase, isWhitespace.

What is the StringTokenizer class used for?To extract tokens (contiguous blocks of characters) separated by delimiters.

Page 53: java notes

Chapter 10

1

Note: 2-D arrays are not in the A-level AP subset.

2

This chapter is only an introduction. More on arrays in Section 11.6, “Iterations and Arrays,” and in Chapter 12.

3

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.

4

The idea is not to save names, of course, but to be able to handle an array’s elements uniformly, using algorithms.

5

The convention of starting indices from 0 comes from C. It is easy to get used to.

6

That’s the beauty of it: the index may be a variable calculated at run time; it can be used in algorithms.

7

arr = new int[newSize];

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.

8

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

9

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

Page 54: java notes

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:

Object x = new int[100];

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

Nothing new here: this is true for any object.

14

If you try to use it, (e.g., arr.length or arr[k]), you’ll get a null reference exception.

15

As opposed to String, where length() is a method.

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

A swap method would work for an array of objects, too.

Page 55: java notes

21

It is helpful to think of someType[ ] as a data type designation, “array of someType elements.”

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

Rugged 2-D arrays are not in the AP subset.

27

Why are arrays useful?They allow a program to process a collection of related values algorithmically.

What types of elements can an array have?Any data type that a variable can have.

How do we refer to an array element in Java?whateverArrayName[index].

What happens if an index has an invalid value?The program reports a run-time error (throws IndexOutOfBoundsException).

How do we refer to the length of an array?whateverArrayName.length

Page 56: java notes

28

Can we resize an array after it has been created?No. But we can throw away the old array and declare a new one of a different size.

Are arrays in Java treated as primitive data types or as objects?Objects

What values do an array’s elements get when the array is created?If it is created with an { } list of initial values, these values; otherwise the default values: 0 for numbers, false for booleans, null for objects.

Are the array’s elements copied when an array is passed to a method?No

Can a method return an array?Yes

29

Name a few applications of two-dimensional arrays.Tables, images, board games, etc.

If m is a 2-D array of ints, what is the type of m[0]?int[]

How do we get the numbers of rows and cols in a 2-D array?number of rows: whateverArrayName.length;number of cols: whateverArrayName[0].length;

Page 57: java notes

Chapter 11

1

2

3

Iterations are what makes a program different from a cookbook recipe.

4

Many people prefer to always use braces, as it is easier to add statements to the body of the loop.

5

When we say “increment” we really mean any change in the variables tested in the condition.

6

7

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.

8

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.

9

10

It is very easy to replace any for loop with a while loop.

11

Simple idioms make your code instantly understandable to others.

12

The first idiom assumes that only the first n elements of the array are used.

13

14

Page 58: java notes

15

16

17

do-while is probably used 1% of the time.

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

It can be a while loop nested within a for loop, etc.

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

Looks like a case for a 2-D array of chars.

28

Page 59: java notes

29

Name three iterative control statements in Java.while, for, do-while

What is the difference between while and do-while?while checks the condition before each iteration; if the condition is false at the outset, the while loop is never entered. do-while checks the condition afterward, so it always goes through the body of the loop at least once.

Can any for loop be rewritten with a while loop?Yes, easily.

Does short-circuit evaluation apply to conditions in loops?Yes, conditions are logical expressions and they are evaluated the same way everywhere in the program.

Which operators can be used in the “increment” part of a for loop?Any operators, but that part of the loop usually has an assignment operator, a compound assignment, or an increment or decrement operator.

30

Are method calls allowed in a condition in a while loop?Sure: just like in any other expression.

Is return allowed in a loop?Yes, it immediately quits the loop and the whole method.

What is a nested loop?A loop within a loop.

Name a couple of common situations where nested loops are used.Processing the elements in a 2-D array; finding duplicates in a list.

Can you have nested while loops?Sure, why not?

Page 60: java notes

Chapter 12

1

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.

2

An unstated objective is to get a feel for the big-O of different algorithms without introducing this concept formally.

3

4

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.

5

The method is familiar to anyone who has ever played the “guess a number” game.

6

Sounds like a recursive algorithm but, as we’ll see shortly, there is an equally simple iterative implementation.

7

8

The while loop always terminates, because the difference right - left is always decreased at least by 1.

9

Typically, in divide and conquer algorithms, the difference between the average case and the worst case time is negligible.

10

For “comparable” objects (e.g., Strings) we’d use a[i].compareTo(max) > 0.

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.

Page 61: java notes

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 Bnlog 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

As we see here, it is easy to replace tail recursion with iterations.

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

Should we call it “head recursion”? But no such term exists...

24

25

But the number of moves may be larger than in Selection Sort.

26

Another divide-and-conquer algorithm. All the work actually happens at the merging phase.

Page 62: java notes

27

Both copy and merge are private helper methods.

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

Needs import java.util.Arrays;

The Arrays class is not in the AP subset.

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

Describe briefly the main idea of Selection Sort.Find the largest element; swap it with the last element; decrement the “logical” size of the array by one; repeat until the size of the array becomes 1.

Page 63: java notes

34

Describe briefly the main idea of Insertion Sort.Keep the first k elements in order (starting from k = 1); take the next element, insert in the right place among the first k and increment k; repeat until k becomes equal the size of the array.

Is it easier to implement Mergesort recursively or iteratively?Recursively.

What is the average number of comparisons in Mergesort?Roughly nlog2 n

Name methods of the Random class that return a random int; a random double.nextInt(n) and nextDouble().

Page 64: java notes

Chapter 12 1/2

1

This chapter covers the required AP topics and, with minor exceptions, stays within the A-level subset.

2

3

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.

4

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.

5

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.

6

This is an occasion for polymorphism. The correct method will be called for each object in the array automatically. For example:

double total = 0.0; for (int i = 0; i < items.length; i++) total += items[i].getPrice();

7

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.

8

Several library classes implement Comparable. Some library methods expect Comparable objects (e.g., Arrays.sort).

Page 65: java notes

9

The compareTo method is not required to return the actual “difference” between the objects. Try, for example,

Integer a = new integer(100); Integer b = new Integer(1); System.out.println(a.compareTo(b));

10

Indices start from 0, as in an array and String.

A list can also contain a null if you add it to the list.

An object can be changed after it is added to the list (unless it is immutable).

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

Object[] temp = items[2 * items.length]; for (int i = 0; i < size(); i++) temp[i] = items[i]; items = temp;

The old items array goes into the garbage collection.

14

For example:

ArrayList birthdays = new ArrayList(); birthdays.add("Laura"); birthdays.add(new Date(5, 23, 1985));

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.

Page 66: java notes

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:

for (int i = 0; i < list.size(); i++) System.out.print(list.get(i) + " ");

— 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

How is an interface different from a class?A class usually has some code for at least some of its methods. An interface lists methods without any code.

Can a class implement several interfaces?Yes.

Can an interface have more than one method?Yes, any number.

If C is a class, when is the following statement valid?

Comparable x = new C();

When C implements Comparable (and has a no-args constructor).

What are the methods of Comparable?int compareTo(Object obj);

Page 67: java notes

21

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.

Page 68: java notes

Chapter 13

1

The material in this chapter is not tested on the AP CS exams.

2

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.

3

To look at or print out a file you must use some program.

4

Recall that a file is a software entity. The hardware knows nothing about files. The operating system does.

5

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.

6

7

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.

8

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.

9

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.

Page 69: java notes

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

Page 70: java notes

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.

Can you open a text file as a random-access file?Yes

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

What is a wrapper class?It is a class designed to add functionality to an object (or a primitive data type, for that matter) and has constructors that take the “to-be-decorated” type of object as an argument.

Which java.io stream classes have a method for reading a line of text?BufferedReader and RandomAccessFile

What does this method return?A String: either the line read or, if unsuccessful (end of file), null.

Do EasyReader / EasyWriter use the java.io package or the system services directly?java.io.

Page 71: java notes

Chapter 14

1

This chapter introduces basic general computer graphics concepts as well as a few specifics for Java.

2

3

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.

4

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

5

Special graphics co-processors may assist in generating graphics. 6

More importantly, Graphics2D supports polymorphic treatment of shapes and lets you define your own shapes.

7

8

The “paint” method comes from the very early versions of Windows.

9

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:

Graphics2D g2d = (Graphics2D)g;

10

JPanel is convenient for drawing, but other components can be used.

11

repaint places a “repaint” request into the application’s events queue. It won’t be processed until the earlier events have been processed.

Page 72: java notes

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

You can call getWidth, getHeight from you paintComponent method.

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

g.drawOval(x - r, y - r, 2*r, 2*r);

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.

Page 73: java notes

20

Explain the difference between vector and raster graphics.In vector graphics the device directly draws strokes on the surface. A raster device keeps an array of pixels. To draw a stroke you need to set certain pixels to a particular color.

In what units are the coordinates measured in Graphics?In display pixels.

Where is the origin of the coordinate system?By default it is in the upper-left corner.

How is the position and size of a rectangle or an oval defined?By describing the bounding rectangle with the coordinates of its upper-left corner, its width and its height.

How do you set a drawing color?By calling g.setColor(...)

Name a few drawing methods.drawLine, drawRect, fillRect, drawOval, fillOval, drawString.

Page 74: java notes

Chapter 15

1

This chapter is only a brief overview of Java’s Swing package and event handling classes.

2

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.

3

Components don’t just “hang there”; they all are attached to each other and eventually to an application window’s content pane.

4

A listener is an object.

5

An interface can also have public static constants declared (see, for example, java.awt.Paint).

6

7

8

Inner classes are a later addition to java. They are not in the AP subset.

9

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

JButton btn = (JButton).getSource();

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.

Page 75: java notes

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

There is also a more complicated GridBagLayout.

20

There is a way to left-justify or right-justify components, too, by passing an additional argument to the FlowLayout constructor. For example:

c.setLayout (new FlowLayout(FlowLayout.RIGHT));

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

Page 76: java notes

28

Boxes stand apart a little conceptually and idiomatically.

29

30

Can a container contain another container?Sure, containers can be nested to any depth.

Is an action listener a class, an interface, an object, or a method?An object. The question means an entity attached to a component that listens to its events. ActionListener is an interface.

What type of objects can you add to a JMenu?other JMenus, JMenuItems, JMenuRadioButtons, JMenuCheckBoxes, etc.

How do FlowLayout and GridLayout deal with the sizes of components?In FlowLayout, each component assumes its natutral (preferred) size. In GridLayout each component occupies the whole grid cell.

What is the default layout manager for the content pane?BorderLayout.

Page 77: java notes

Chapter 16

1

This is essentially a “learning by doing” chapter. Not much theory here.

2

3

4

5

mouseClicked checks that the button was pressed and released in the same place, which may result in missed clicks.

6

7

8

For example, typing Shift+A, causes five calls: Shift pressed, ‘a’ pressed, ‘a’ released, Shift released, ‘A’ typed.

9

10

11

Working with bit masks requires bit-wise logical operators, explained in Section 16.3 of the book.

12

13

14

15

16

Getting audio in applications (not applets) is more involved.

17

In this example, the file Bells.wav is located in the audio subdirectory of the directory that contains the applet’s HTML file.

Page 78: java notes

18

Again, this works only in applets. Use ImageIcon in applications.

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

Name the five methods of the MouseListener interface.mousePressed, mouseReleased, mouseClicked, mouseEntered, mouseExited.

Can a class implement MouseMotionListener but not MouseListener?Yes, but it would be a little unusual.

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.

How many methods does the KeyListener interface specify?Three: keyPressed, keyReleased, keyTyped.

23

Which KeyListener method is used to capture an action key event?keyPressed or keyReleased.

Which KeyEvent method returns the actual character typed?keyTyped.

Which KeyEvent methods return the status of modifier keys?isAltDown, isShiftDown, isControlDown, etc., or getModifiers.

When do we need a requestFocus() call?When a component needs to listen to keyboard events, but doesn’t get the keyboard focus automatically.

Page 79: java notes

24

What does an applet’s getDocumentBase() method return?It returns the path part of the absolute URL that contains the applet’s HTML file.

Which class was written earlier, Image or ImageIcon?Image — ImageIcon is in Swing, which was added later.

How can we display an icon in a panel (a JPanel object)?We can call drawIcon(this, g, 0, 0) from the panel’s paintComponent method.

How can we display an icon on a button (a JButton object)?We can call the button’s setIcon method or add the icon as an argument for the button’s constructor.

Page 80: java notes

Chapter 17

1

2

This is a review of OOP concepts.

3

The industry has embraced OOP, but no formal studies of these claimed benefits have been carried out.

4

5

6

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

7

8

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.

9

A concrete class can redefine some of the methods defined higher in the hierarchy.

10

Inheriting data types is useful for polymorphism, as we’ll see shortly.

11

12

A programmer can extend a library hierarchy, adding his or her own classes.

13

14

15

Page 81: java notes

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

It is easy to reuse code by extending classes through inheritance.

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

The term interface is highly “overloaded” in the computer lingo.

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.

No particular benefits for GUI programming.

Program maintenance is easier due to encapsulation: if a class’s fields change, only that class is affected.

24

setAge is a method in HumanPlayer, but not in ComputerPlayer.

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.

Page 82: java notes

26

An example of the last point:

public abstract class GameFor2{ private Player player1; private Player player2; ... public GameFor2(Player player1, Player player2) { this.player1 = player1; this.player2 = player2; } }

public class Chess extends GameFor2{ public Chess { super (new HumanPlayer(“Nancy”, 8), new ComputerPlayer(1)); ... }}

27

28

Each object has a table of entry points for its methods.

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.

Explain the dual role of inheritance.A subclass inherits fields and methods from the superclass and inherits the superclass’s data type.

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.

Can an interface extend a class? If so, what does that mean?No way.

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.

Page 83: java notes

32

What is abstraction?Ignoring irrelevant details and focusing on the relevant ones.

Explain how encapsulation helps in software maintenance.A change in the private fields or methods of a class does not affect other classes.

Why do objects sometimes end up disguised as objects of more generic types?For example, this happens when we put different types of objects into the same collection or pass an object to a method that expects a more generic type of argument.

What is polymorphism?Automatically calling correct methods for objects disguised as more generic types.