### Introduction to Programming Using Java, Fifth Edition

## Source Code

This page contains links to the source code for examples appearing in the free, on-line textbook Introduction to Programming Using Java, Version 5.0. You should be able to compile these files and use them. Note however that some of these examples depend on other source files, such as TextIO.java and MosaicPanel.java, that are not built into Java. These are classes that I have written. Links to all necessary non-standard source code files are provided below. To use examples that depend on my classes, you will need to compile the source code for the required classes and place the compiled classes in the same directory with the main class file. If you are using an integrated development environment such as Eclipse, you can simply add any required source code files to your project.

Most of the solutions to end-of-chapter exercises are not listed on this page. Each end-of-chapter exercise has its own Web page, which discusses its solution. The source code of a sample solution of each exercise is given in full on the solution page for that exercise. If you want to compile the solution, you should be able to cut-and-paste the solution out of a Web browser window and into a text editing program. (You can't cut-and-paste from the HTML source of the solution page, since it contains extra HTML markup commands that the Java compiler won't understand; the HTML markup does not appear when the page is displayed in a Web browser.)

Note that many of these examples require Java version 5.0 or later. Some of them were written for older versions, but will still work with current versions. When you compile some of these older programs with current versions of Java, you might get warnings about "deprecated" methods. These warnings are not errors. When a method is deprecated, it means that it should not be used in new code, but it has not yet been removed from the language. It is possible that deprecated methods might be removed from the language at some future time, but for now you just get a warning about using them.

### Part 1: Text-oriented Examples

Many of the sample programs in the text are based on console-style input/output, where the computer and the user type lines of text back and forth to each other. Some of these programs use the standard output object, System.out, for output. Many of them use my non-standard class, TextIO, for both input and output. For the programs that use TextIO, one of the files TextIO.java or TextIO.class must be available when you compile the program, and TextIO.class must be available when you run the program. There is also a GUI version of TextIO; you can find information about it at the end of this web page.

The programs listed here are stand-alone applications, not applets, but I have written applets that simulate many of the programs. These "console applets" appear on Web pages in the on-line version of this textbook. They are based on TextIOApplet.java, which provides the same methods as TextIO, but in an applet instead of in a stand-alone application. It is straightforward to convert a TextIO program to a TextIOApplet applet. See the comments in the TextIOApplet.java file for information about how to do it. One example of this can be found in the file Interest3Console.java.

- Interest.java, from Section 2.2, computes the interest on a specific amount of money over a period of one year.
- TimedComputation.java, from Section 2.3, demonstrates a few basic built-in subroutines and functions.
- EnumDemo.java, from Section 2.3, a very simple first demonstration of enum types.
- PrintSquare.java, from Section 2.4, reads an integer typed in by the user and prints the square of that integer. This program depends on TextIO.java.
- Interest2.java, from Section 2.4, calculates interest on an investment for one year, based on user input. This program depends on TextIO.java. The same is true for almost all of the programs in the rest of this list.
- CreateProfile.java, from Section 2.4, a simple demo of output to a file, using TextIO.
- Interest3.java, from Section 3.1, the first example that uses control statements.
- ThreeN1.java, from Section 3.2, outputs a 3N+1 sequence for a given stating value.
- ComputeAverage.java, from Section 3.3, computes the average value of some integers entered by the user.
- CountDivisors.java, from Section 3.4, counts the number of divisors of an integer entered by the user.
- ListLetters.java, from Section 3.4, lists all the distinct letters in a string entered by the user.
- LengthConverter.java, from Section 3.5, converts length measurements input by the user into different units of measure.
- ReadNumbersFromFile.java, from Section 3.7, finds the sum and the average of numbers read from a file. Demonstrates try..catch statements.
- GuessingGame.java, from Section 4.2, lets the user play guessing games where the computer picks a number and the user tries to guess it. A slight variation of this program, which reports the number of games won by the user, is GuessingGame2.java.
- RowsOfChars.java, from Section 4.3, a rather useless program in which one subroutine calls another.
- ThreeN2.java, from Section 4.4, is an improved 3N+1 program that uses subroutines and prints its output in neat columns.
- HighLow.java, from Section 5.4, a simple card game. It uses the classes Card.java and Deck.java, which are given as examples of object-oriented programming. Also available, the card-related classes Hand.java and, from Subsection 5.5.1, BlackjackHand.java.
- BirthdayProblemDemo.java, from Section 7.2, demonstrates random access to array elements using the "birthday problem" (how many people do you have to choose at random until two are found whose birthdays are on the same day of the year).
- ReverseInputNumbers.java, from Section 7.3, is a short program that illustrates the use of a partially full array by reading some numbers from the user and then printing them in reverse order.
- ReverseWithDynamicArray.java, from Section 7.3, reads numbers from the user then prints them out in reverse order. It does this using the class DynamicArrayOfInt.java as an example of using dynamic arrays.
- LengthConverter2.java, from Section 8.2, converts measurements input by the user to inches, feet, yards, and miles. This improvement on LengthConverter.java allows inputs combining several measurements, such as "3 feet 7 inches," and it detects illegal inputs.
- LengthConverter3.java, from Section 8.3, a revision of the previous example that uses exceptions to handle errors in the user's input.
- ThreadTest1.java, from Section 8.5, runs several threads all computing the same task to test whether there is any speedup when more than one thread is used.
- ThreadTest2.java, from Section 8.5, divides a task among several threads and combines the results from all the threads. Also shows how to wait for all threads to finish. And ThreadTest3.java from the same section performs the same task but uses the producer/consumer pattern for communication between threads.
- TowersOfHanoi.java, from Section 9.2, prints out the steps in a solution to the Towers of Hanoi problem; an example of recursion.
- StringList.java, from Section 9.2, implements a linked list of strings. The program ListDemo.java tests this class.
- PostfixEval.java, from Section 9.3, evaluates postfix expressions using a stack. Depends on the StackOfDouble class defined in StackOfDouble.java.
- SortTreeDemo.java, from Section 9.4, demonstrates a binary sort tree of strings.
- SimpleParser1.java, from Section 9.5, evaluates fully parenthesized expressions input by the user.
- SimpleParser2.java, from Section 9.5, evaluates ordinary infix expressions input by the user.
- SimpleParser3.java, from Section 9.5, reads infix expressions input by the user and constructs expression trees that represent those expressions.
- WordListWithTreeSet.java, from Section 10.2, makes an alphabetical list of words from a file. A TreeSet is used to eliminate duplicates and sort the words.
- SimpleInterpreter.java, from Section 10.4, demonstrates the use of a HashMap as a symbol table in a program that interprets simple commands from the user.
- WordCount.java, from Section 10.4, counts the number of occurrences of each word in a file. The program uses several features from the Java Collection Framework.
- ReverseFile.java, from Section 11.2, shows how to read and write files in a simple command-line application; uses the non-standard class TextReader.java.
- DirectoryList.java, from Section 11.2, lists the contents of a directory specified by the user; demonstrates the use of the File class.
- CopyFile.java, from Section 11.3, is a program that makes a copy of a file, using file names that are given as command-line arguments.
- PhoneDirectoryFileDemo.java, from Section 11.3, demonstrates the use of a file for storing data between runs of a program.
- ShowMyNetwork.java, mentioned in Section 11.4, is a short program that prints information about each network interface on the computer where it is run, including IP addresses associated with each interface.
- DateClient.java and DateServer.java, from Section 11.4, are very simple first examples of network client and server programs.
- CLChatClient.java and CLChatServer.java, from Section 11.4, demonstrate two-way communication over a network by letting users send messages back and forth; however, no threading is used and the messages must strictly alternate.
- CLMandelbrotMaster.java, CLMandelbrotWorker.java, and CLMandelbrotTask.java, from Section 11.5, are a demonstration of distributed computing in which pieces of a large computation are sent over a network to be computed by "worker" programs.

### Part 2: Graphical Examples from the Text

The following programs use a graphical user interface. The majority of them can be run both as stand-alone applications and as applets. (If you have downloaded the web site for this book, note that most of the jar files for Chapter 6 and Chapter 12 are executable jar files which can be be run as applications.)

- GUIDemo.java is a simple demonstration of some basic GUI components from the Swing graphical user interface library. It appears in the text in Section 1.6, but you won't be able to understand it until you learn about GUI programming.
- StaticRects.java is a rather useless applet that simply draws a static image. It is the first example of GUI programming, in Section 3.8.
- MovingRects.java, also from Section 3.8, draws an animated version of the image in the preceding example. This applet depends on SimpleAnimationApplet2.java, which is a simple framework for writing animated applets.
- RandomMosaicWalk.java, a standalone program that displays a window full of colored squares with a moving disturbance, from Section 4.6. This program depends on MosaicCanvas.java and Mosaic.java.
- RandomMosaicWalk2.java is a version of the previous example, modified to use a few named constants. From Section 4.7.
- ShapeDraw.java, from Section 5.5, is an applet that lets the user place various shapes on a drawing area; an example of abstract classes, subclasses, and polymorphism.
- HelloWorldGUI1.java and HelloWorldGUI2.java, from Section 6.1, show the message "Hello World" in a window, the first one by using the built-in JOptionPane class and the second by building the interface "by hand." Another variation, HelloWorldGUI4.java, from Section 6.4, uses anonymous nested classes where HelloWorldGUI1.java uses named nested classes.
- HelloWorldApplet.java, from Section 6.2, defines an applet that displays the message "Hello World" or "Goodbye World". The message changes when the user clicks a button.
- HelloWorldPanel.java, from Section 6.2, is a panel that displays a message. The panel is used as the content pane both in the applet HelloWorldApplet2.java and in the window of the stand-alone application HelloWorldGUI3.java. This example illustrates the technique of using the same panel class in both an applet and a stand-alone application, a technique that will be used in many examples in the rest of the book.
- ColorChooserApplet.java, used in Section 6.3 to demonstrate RGB and HSB colors. This old applet uses the AWT rather than Swing for its user interface. Since it is not presented as a programming example, it has not been revised.
- RandomStringsApplet.java, from Section 6.3, shows 25 copies of the string "Java!" (or some other string specified in an applet param) in random colors and fonts. The applet uses RandomStringsPanel.java for its content pane, and there is a stand-alone application RandomStringsApp.java that uses the same panel class.
- ClickableRandomStringsApp.java, from Section 6.4, is similar to RandomStringsApp.java except that the window is repainted when the user clicks the window. This is a first example of using a mouse listener. The applet version is ClickableRandomStringsApplet.java.
- SimpleStamper.java, from Section 6.4, lets the user place rectangles and ovals on a drawing area by clicking with the mouse. The applet version is SimpleStamperApplet.java. Both versions use SimpleStamperPanel.java for their content panes.
- SimpleTrackMouse.java, from Section 6.4, shows information about mouse events. The applet version is SimpleTrackMouseApplet.java. Both versions use SimpleTrackMousePanel.java for their content panes.
- SimplePaint.java, from Section 6.4, lets the user draw curves in a drawing area and select the drawing color from a palette. The class SimplePaint can be used either as as applet or as a stand-alone application.
- RandomArtPanel.java, from Section 6.5, shows a new random "artwork" every four seconds. This is an example of using a Timer. Used in an applet version of the program, RandomArtApplet.java, and a stand-alone application version, RandomArt.java.
- KeyboardAndFocusDemo.java, from Section 6.5, shows how to use keyboard and focus events. This class can be run either has an applet or as a stand-alone application.
- SubKillerPanel.java, from Section 6.5, lets the user play a simple game. Uses a timer as well as keyboard and focus events. The applet version is SubKillerApplet.java, and the stand-alone application version is SubKiller.java.
- SliderDemo.java, a simple demo from Section 6.6, is an applet that shows three JSliders.
- TextAreaDemo.java, from Section 6.6, is an applet that demonstrates a JTextArea in a JScrollPane.
- BorderDemo.java, from Section 6.7, a very simple applet that demonstrates six types of border.
- SliderAndComboBoxDemo.java, from Section 6.7, shows how to create several components and lay them out in a GridLayout. Can be used either as an applet or as a stand-alone application.
- SimpleCalc.java, from Section 6.7, lets the user add, subtract, multiply, or divide two numbers input by the user. A demo of text fields, buttons, and layout with nested subpanels. Can be used either as an applet or as a stand-alone application.
- NullLayoutDemo.java, from Section 6.7, shows how to lay out the components in a container for which the layout manager has been set to null. Can be used either as an applet or as a stand-alone application.
- HighLowGUI.java, from Section 6.7, is a GUI version of HighLow.java, a game where the user sees a playing card and guesses whether the next card will be higher or lower in value. This program also requires Card.java, Hand.java, and Deck.java. Can be used as a stand-alone application and also contains a nested class HighLowGUI.Applet that represents the applet version of the program
- MosaicDrawController.java, from Section 6.8, demonstrates menus and a color chooser dialog. This is used in a program where the user colors the squares of a mosaic by clicking-and-dragging the mouse. It uses MosaicPanel.java to define the mosaic panel itself. MosaicDrawController is used in the stand-alone application MosaicDrawFrame.java, in the applet MosaicDrawApplet.java, and in the applet MosaicDrawLauncherApplet.java. The latter applet appears as a button on a web page; clicking the button opens a MosaicDrawFrame.
- SimpleDialogDemo.java, from Section 6.8, is an applet that demonstrates JColorChooser and some dialogs from JOptionPane.
- RandomStringsWithArray.java, from Section 7.2, shows 25 copies of a message in random colors, sizes, and positions. This is an improved version of RandomStringsPanel.java that uses an array to keep track of the data, so that the same picture can be redrawn whenever necessary. (Written only as an applet.)
- SimpleDrawRects.java, from Section 7.3, lets the user place colored rectangles in a drawing area. Illustrates the use of an ArrayList. An applet version is SimpleDrawRectsApplet.java. This program uses and depends on RainbowPalette.java.
- SimplePaint2.java, from Section 7.3, lets the user draw colored curves and stores the data needed for repainting the drawing surface in a list of type ArrayList<CurveData>.
- Checkers.java, from Section 7.5, lets two users play a game of checkers against each other. Illustrates the use of a two-dimensional array. (This is the longest program in the book so far, at over 750 lines!)
- Blobs.java, from Section 9.1, recursively counts groups of colored squares in a grid.
- DepthBreadth.java, from Section 9.3, demonstrates stacks and queues.
- TrivialEdit.java, from Section 11.3, lets the user edit short text files. This program demonstrates reading and writing files and using file dialogs.
- SimplePaintWithFiles.java, from Section 11.3, demonstrates saving data from a program to a file in both binary and character form. The program is a simple sketching program based on SimplePaint2.java.
- ChatSimulation.java, from Section 11.5 (on-line version only), is an applet that simulates a network chat. There is no networking in this applet. The only point is to demonstrate how a thread could be used to process (simulated) incoming messages.
- GUIChat.java, from Section 11.5, is a simple GUI program for chatting between two people over a network.
- BuddyChat.java, BuddyChatServer.java, BuddyChatWindow.java, and BuddyChatServerShutdown.java, from Section 11.5, represent a multithreaded server and a client program for the service that it offers. The BuddyChatServer program is a non-GUI server that keeps a list of connected clients. These clients are available to chat to other clients. The client program is BuddyChat. Each client connects to the server and gets a list of other clients that are connected. A BuddyChat user can request a connection to one of the other clients in the list; when a connection is made, a pair of BuddyChatWindows is used for chatting between the two clients. (The server has no part in the chat connections.) BuddyChatServerShutdown can be used to shut down the server cleanly. This example is not scalable; that is, it should only be used for fairly small numbers of clients. There is absolutely no defense against denial of service attacks, such as someone opening a very large number of connections. It is just an example of basic client/server programming using threads.
- XMLDemo.java, from Section 11.6, is a simple program that demonstrates basic parsing of an XML document and traversal of the Document Object Model representation of the document. The user enters the XML to be parsed in a text area. The nested class XMLDemo.XMLDemoApplet runs the program as an applet.
- SimplePaintWithXML.java and SimplePaintWithXMLEncoder.java, from Section 11.6, demonstrate saving data from a program to a file in XML format. The first program uses an invented XML language, while the second uses an XMLEncoder for writing files and an XMLDecoder for reading files. These programs are modifications of SimplePaintWithFiles.java.
- HighLowWithImages.java, from Section 12.1, is a variation of HighLowGUI.java that takes playing card images from an image file. Requires the image file cards.png and depends on Card.java, Deck.java, and Hand.java.
- PaintWithOffScreenCanvas.java, from Section 12.1, is a little paint program that illustrates the use of a BufferedImage as an off-screen canvas.
- SoundAndCursorDemo.java, from Section 12.1, lets the user play a few sounds and change the cursor by clicking some buttons. This demonstrates using audio resource files and using an image resource to create a custom cursor. Requires the resource files in the directory snc_resources.
- TransparencyDemo.java, from Section 12.2, demonstrates using the alpha component of colors. It is also an example of using FontMetrics.
- StrokeDemo.java, from Section 12.2, demonstrates the use of various BasicStrokes for drawing lines and rectangles. Also demonstrates antialiasing.
- PaintDemo.java, from Section 12.2, demonstrates using a GradientPaint and using a TexturePaint to fill a polygon. Uses the image resource files TinySmiley.png and QueenOfHearts.png.
- RadioButtonDemo.java, from Section 12.3, does what its name indicates.
- ToolBarDemo.java, from Section 12.3, uses a JToolBar that holds a group of 3 radio buttons and a push button. All the buttons use custom icons, and the push button is created from an Action.
- SillyStamper.java, from Section 12.4, demonstrates using a JList of Icons. The user can "stamp" images of a selected icon onto a drawing area. This program uses the icon images in the directory stamper_icons as resources.
- StatesAndCapitalsTableDemo.java, from Section 12.4, is a completely trivial demo of a JTable.
- ScatterPlotTableDemo.java, from Section 12.4, uses a TableModel to customize a JTable. The table is a list of xy-points that the user can edit. A scatter plot of the points is displayed.
- SimpleWebBrowser.java and SimpleWebBrowserWithThread.java, from Section 12.4, implement a simple web browser using JEditorPane (which is ridiculously easy). The difference between the programs is that the first loads documents synchronously, which can hang the program in an unpleasant way, while the second uses a thread to load documents asynchronously.
- SimpleRTFEdit.java, mentioned but just barely discussed in Section 12.4, lets the user edit RTF files, which are text files in a format that include style information such as bold and italics. This is mainly a simple demo of using Actions defined by "editor kits."
- StopWatchLabel.java and MirrorText.java, from Section 12.4, are classes that implement custom components. CustomComponentTest.java is a program that tests them.
- The Mandelbrot program from Section 12.5, which computes and displays visualizations of the Mandelbrot set, is defined by several classes in the package edu.hws.eck.mdb. The source code files can be found in the directory edu/hws/eck/mdb.

### Part 3: End-of-Chapter Applets

This section contains the source code for the applets that are used as decorations at the end of each chapter. In general, you should not expect to be able to understand these applets at the time they occur in the text. Many of these are older applets that will work with Java 1.1 or even Java 1.0. They are not meant as examples of good programming practice for more recent versions of Java.

1. Moire.java, an animated design, shown at the end of Section 1.7. You can use applet parameters to control various aspects of this applet's behavior. Also note that you can click on the applet and drag the pattern around by hand. See the source code for details.
2. JavaPops.java, from Section 2.6 is a simple animation that shows copies of the string "Java!" in various sizes and colors appearing and disappearing. This is an old applet that depends on an old animation framework named SimpleAnimationApplet.java
3. MovingRects.java shows a simple animation of rectangles continuously shrinking towards the center of the applet. This is also a programming example in Section 3.8. It depends on SimpleAnimationApplet2.java.
4. RandomBrighten.java, showing a grid of colored squares that get more and more red as a wandering disturbance visits them, from the end of Section 4.7. Depends on MosaicCanvas.java
5. SymmetricBrighten.java, a subclass of the previous example that makes a symmetric pattern, from the end of Section 5.7. Depends on MosaicCanvas.java and RandomBrighten.java.
6. TrackLines.java, an applet with lines that track the mouse, from Section 6.8.
7. KaleidoAnimate.java, from Section 7.5, shows moving kaleidoscopic images.
8. SimpleCA.java, a Cellular Automaton applet, from the end of Section 8.4. This applet depends on the file CACanvas.java For more information on cellular automata see http://math.hws.edu/xJava/CA/.
9. TowersOfHanoiGUI.java, from Section 9.5, graphically shows the solution to the Towers of Hanoi problem with 10 disks.
10. LittlePentominosApplet.java, from Section 10.5, solves pentominos puzzles using a simple recursive backtracking algorithm. This applet depends on MosaicPanel.java. For a much more complex Pentominos applet, see http://math.hws.edu/xJava/PentominosSolver/.
11. Maze.java, an applet that creates a random maze and solves it, from Section 11.6.
12. The applet at the end of Section 12.5 is the same Mandelbrot program that is discussed as an example in that section, with source files in the directory edu/hws/eck/mdb.

### Part 4: Required Auxiliary Files

This section lists some of the extra source files that are required by various examples in the previous sections, along with a description of each file. The files listed here are those which are general enough to be potentially useful in other programming projects. All of them are also referred to above, along with the programming examples that depend on them.

- TextIO.java defines a class containing some static methods for doing input/output. These methods make it easier to use the standard input and output streams, System.in and System.out. TextIO also supports other input sources and output destinations, such as files. Note that this version of TextIO is new with the fifth edition of this textbook and requires Java 5.0 (or higher). The TextIO class defined by this file will be useless on a system that does not implement standard input, and might be inconvenient to use in integrated development environments such as Eclipse in which standard input works poorly. In that case, you might want to use the following file instead.
- TextIO.java for GUI defines an alternative to the preceding file. It defines a version of TextIO with the same set of input and output routines as the original version. But instead of using standard I/O, this GUI version opens its own window, and the input/output is done in that window. Please read the comments at the beginning of the file. (For people who have downloaded this book: The file is located in a directory named TextIO-GUI inside the source directory.)
- TextIOApplet.java can be used for writing applets that simulate TextIO applets. This makes it possible to write applets that use "console-style" input/output. Such applets are created as subclasses of TextIOApplet. See the comments in the file for more information about how to convert a TextIO program into a TextIOApplet applet. An example can be found in the file Interest3Console.java.
- TextReader.java can be used to "wrap" an input stream in an object that makes it easy to read data from the stream. A TextReader object has basically the same input methods as the TextIO class. The TextReader class is introduced in Subsection 11.1.4
- SimpleAnimationApplet2.java, a class that can be used as a framework for writing animated applets. To use the framework, you have to define a subclass of SimpleAnimationApplet2. Section 3.8 has an example.
- Mosaic.java contains subroutines for opening and controlling a window that contains a grid of colored rectangles. It depends on MosaicCanvas.java. This is a toolbox for writing simple stand-alone applications that use a "mosaic window". This is rather old code, but it is used in examples in Section 4.6 and Section 4.7.
- MosaicPanel.java is a greatly improved version of MosaicCanvas.java that has many options. This class defines a subclass of JPanel that shows little rectangles arranged in rows and columns. It is used in the "mosaic draw" example in Section 6.8.
- Expr.java defines a class Expr that represent mathematical expressions involving the variable x. It is used in some of the exercises in Chapter 8.
- I18n.java is a class that can be used to help in internationalization of a program. See Subsection 12.5.3.

David Eck, December 2006