Introduction to Programming Using Java, Seventh 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, Seventh Edition. The index page has links for downloading the entire web site. If you do that, you will find the source code files in a directory named sources. There is also a link for downloading just the source code. The README file from the download includes some instructions for compiling and running the programs. Note however that some of these examples depend on other source files, such as TextIO.java, that are not built into Java. These are classes that I have written. All necessary files are included in the downloads, and links to the individual files are provided below.
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 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.) Exercise solutions are also available as a download from the front page of the web site. The README file from the download has more information.
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 input. 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.
- HelloWorld.java, from Section 2.1, a trivial program that does nothing but print out the message, "Hello World!". A Hello World program is typically the first program for someone learning a new programming language.
- 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. The same is true for almost all of the programs in the rest of this list.
- Interest2.java, from Section 2.4, calculates interest on an investment for one year, based on user input. Uses TextIO for user input.
- CreateProfile.java, from Section 2.4, a simple demo of output to a file, using TextIO.
- Interest2WithScanner.java, from Section 2.4, is a version of Interest2.java that uses Scanner instead of TextIO to read input from the user.
- 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.
- ComputeAverage2.java, from Section 3.7, computes the average value of some real numbers entered by the user. Demonstrates the use of try..catch for Double.parseDouble.
- AverageNumbersFromFile.java, from Section 3.7, finds the sum and the average of numbers read from a file. Demonstrates the use of try..catch statements with TextIO.
- BirthdayProblem.java, from Section 3.8, 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 3.8, illustrates the use of a partially full array by reading some numbers from the user and then printing them in reverse order.
- 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.
- CopyTextFile.java, from Section 4.3, demonstrates the use of command-line arguments by using file names from the command line.
- ThreeN2.java, from Subsection 4.4.3, is an improved 3N+1 program that uses subroutines and prints its output in neat columns.
- RollTwoPairs.java, from Subsection 5.2.2, uses PairOfDice.java to simulate rolling two pairs of dice until the same total is rolled on both pairs.
- 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.
- ReverseWithDynamicArray.java, from Section 7.2, 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. ReverseWithArrayList.java, from Section 7.3, is functionally identical, but it uses an ArrayList<Integer> instead of a DynamicArrayOfInt.
- SymmetricMatrix.java, from Section 7.5, implements a symmetric 2D array of double. The program TestSymmetricMatrix.java tests the SymmetricMatrix class.
- 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.
- TryStatementDemo.java, from Section 8.3, a small demo program with a try..catch statement that includes autoclosing of a resource.
- LengthConverter3.java, from Section 8.3, is a revision of the previous example that uses exceptions to handle errors in the user's input.
- TowersOfHanoi.java, from Section 9.1, 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, SimpleParser1.java, and SimpleParser1.java, from Section 9.5, are three programs that parse and evaluate arithmetic expressions input by the user. SimpleParser1 only handles fully parenthesized expressions. SimpleParser2 evaluates ordinary expressions where some parentheses can be omitted. SimpleParser3 constructs expression trees to represent input expressions and uses the expression trees to evaluate the 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.
- WordListWithPriorityQueue.java, from Section 10.2, makes an alphabetical list of words from a file. This is a small modification of the previous example that uses a PriorityQueue instead of a TreeSet. The result is an alphabetical list of words in which duplicates are not removed.
- 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. ReverseFileWithScanner.java is a version of the program that uses a Scanner instead of a TextReader. And ReverseFileWithResources.java is a version that uses the "resource" pattern in try..catch statements.
- 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. CopyFileAsResources.java is a version of the program that also demonstrates uses the "resource" pattern in a try..catch statement.
- PhoneDirectoryFileDemo.java, from Section 11.3, demonstrates the use of a file for storing data between runs of a program.
- FetchURL.java, from Section 11.4, reads and displays the contents of a specified URL, if the URL refers to a text file.
- 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.
- ThreadTest1.java, from section Section 12.1, runs one or more threads that all perform the same task, to demonstrate that they run simultaneously and finish in an indeterminate order.
- ThreadTest2.java, from section Section 12.1, divides up a task (counting primes) among several threads, to demonstrate parallel processing and the use of synchronization.
- DateServerWithThreads.java and DateServerWithThreadPool.java, from Section 12.4, are modifications of chapter11/DateServer.java (Subsection 11.4.4) that use threads to handle communication with clients. The first program creates a new thread for each connection. The second uses a thread pool, and it uses a blocking queue to send connections from the main program to the pool. The threaded servers will work with original client program, chapter11/DateClient.java.
- CLMandelbrotMaster.java, CLMandelbrotWorker.java, and CLMandelbrotTask.java, from Section 12.4, 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 sample programs use a graphical user interface.
- 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.
- RandomCircles.java, from Section 3.9, draws a large number of randomly colored, randomly positioned disks. his simple graphics program is our first example of a GUI program.It is meant both as an introduction to graphics and as an example of using control structures.
- MovingRects.java, from Section 3.9, draws a set of nested rectangles that seem to move infinitely towards the center. Both this program and the previous one are based on SimpleAnimationStarter.java, which can be used as a starting point for writing similar programs.
- 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 MosaicPanel.java and Mosaic.java.
- RandomMosaicWalk2.java is a version of the previous example, modified to use a few named constants. From Section 4.7.
- GrowingCircleAnimation.java, from Section 5.3, shows an animation of growing, semi-transparent circles. Requires CircleInfo.java. Used as a simple example of programming with object.
- ShapeDraw.java, from Section 5.5, is a program 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."
- SimpleColorChooser.jav, used in Section 6.2 to demonstrate RGB and HSB colors. This program uses techniques that are not covered until later in the text, and it is not presented as a programming example. You can run it to experiment with colors.
- RandomStringsPanel.java, from Section 6.2, shows 25 copies of the string "Java!" (or some other string specified in it constructor) in random colors and fonts. The program RandomStrings.java uses a RandomStringsPanel as its content pane. And RandomStringsPanelWithMain.java is a program that combines the main() routine and the definition of the panel into one file. Finally, ClickableRandomStrings.java from Section 6.3 is a modification of RandomStrings.java with a mouse listener that redraws the panel when the user clicks on it.
- SimpleStamper.java, from Section 6.3, lets the user place rectangles and ovals on a drawing area by clicking with the mouse.
- SimpleTrackMouse.java, from Section 6.3, shows information about mouse events as the user moves and clicks with the mouse.
- SimplePaint.java, from Section 6.3, lets the user draw curves in a drawing area and select the drawing color from a palette.
- RandomArt.java, from Section 6.4, shows a new random "artwork" every four seconds. This is an example of using a Timer.
- KeyboardAndFocusDemo.java, from Section 6.4, shows how to use keyboard and focus events.
- SubKiller.java, from Section 6.4, lets the user play a simple arcade-style game. Uses a timer as well as keyboard and focus events.
- SliderDemo.java and TextAreaDemo.java, small programs that demonstrate basic components, used as examples in Section 6.5
- BorderDemo.java and
- BorderDemo.java, from Section 6.6, a very simple program that demonstrates six types of border.
- SliderAndButtonDemo.java, from Section 6.6, shows how to create several components and lay them out in a GridLayout.
- SimpleCalc.java, from Section 6.6, 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.
- NullLayoutDemo.java, from Section 6.6, shows how to lay out the components in a container for which the layout manager has been set to null.
- HighLowGUI.java, from Section 6.6, implements a GUI version of the card game HighLow.java, in which the user sees a playing card and guesses whether the next card will be higher or lower in value. This program depends on Card.java, Hand.java, and Deck.java.
- MosaicDraw.java, from Section 6.7, 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, and it uses MosaicDrawController.java to create the panel and menu bar and to handle events.
- SimpleDialogDemo.java, from Section 6.7, is a small program that demonstrates JColorChooser and some dialogs from JOptionPane.
- RandomStringsWithArray.java, from Section 7.2, shows multiple 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.
- 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>.
- Life.java, from Section 7.5, implements John H. Conway's game of life and is an example of using 2D arrays. This program depends on MosaicPanel.java.
- 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 and a variety of programming techniques. (This is the longest program in the book so far, at over 700 lines!)
- Maze.java and LittlePentominos.java are demo programs mentioned in Section 9.1 as examples of recursion. They use techniques that have not covered until Chapter 12. Note that LittlePentominos depends on MosaicPanel.java.
- Blobs.java, from Section 9.1, uses recursion to count 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.
- SimplePaintWithXML.java, from Section 11.5, demonstrate saving data from a program to a file in XML format. This program is a modification of SimplePaintWithFiles.java.
- XMLDemo.java, from Section 11.5, 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.
- RandomArtWithThreads.java, from Section 12.2, uses a thread to drive a very simple animation. Compare to RandomArt.java, which does the same thing with a timer.
- QuicksortThreadDemo.java, from Section 12.2, demonstrates using a separate thread to perform a computation, with simple inter-thread communication.
- BackgroundComputationDemo.java, from Section 12.2, demonstrates using a thread running at a lower priority to perform a lengthy computation in the background. BackgroundCompWithInvoke.java is very small modification of the same program that uses SwingUtilities.invokeLater instead of synchronization. (The program computes a visualization of a small piece of the Mandelbrot set, but the particular computation that is done is not important.)
- MultiprocessingDemo1.java, from Section 12.2, is a modification of the previous example that uses several threads to perform the background computation. This speeds up the computation on multi-processor machines.
- MultiprocessingDemo2.java, from Section 12.3, is a modification of the previous example that decomposes its task into a large number of fairly small subtasks, in order to achieve better load balancing. The program uses a thread pool and a queue of tasks.
- MultiprocessingDemo3.java, from Section 12.3, is yet another version of the previous examples. This one uses a pool of threads that run forever, taking tasks from a queue and executing them. To make this possible, a blocking queue is used, defined by the standard LinkedBlockingQueue class. MyLinkedBlockingQueue.java is a simple example of using wait() and notify() directly that can be used as a replacement for LinkedBlockingQueue in MultiprocessingDemo3.
- TowersOfHanoiGUI.java, from Section 12.3, shows an animation of the famous Towers Of Hanoi problem. The user can control the animation with Run/Pause, Next, and StartAgain buttons. The program is an example of using wait() and notify() directly for communication between threads.
- GUIChat.java, from Section 12.4, is a simple GUI program for chatting between two people over a network. It demonstrates using a thread for reading data from a network connection.
- netgame.common, from Section 12.5, is a package that defines a framework for networked games. This framework is used in several examples: A chat room, defined in package netgame.chat; a tic-tac-toe game, defined in package netgame.tictactoe; and a poker game, defined in package netgame.fivecarddraw.
- HighLowWithImages.java, from Section 13.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 13.1, is a little paint program that illustrates the use of a BufferedImage as an off-screen canvas.
- SoundAndCursorDemo.java, from Section 13.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 13.2, demonstrates using the alpha component of colors. It is also an example of using FontMetrics.
- StrokeDemo.java, from Section 13.2, demonstrates the use of various BasicStrokes for drawing lines and rectangles. Also demonstrates antialiasing.
- PaintDemo.java, from Section 13.2, demonstrates using a GradientPaint and using a TexturePaint to fill a polygon. Uses the image resource files TinySmiley.png and QueenOfHearts.png.
- ChoiceDemo.java, discussed in Section 13.3, demonstrates radio buttons, combo boxes, and Actions.
- ToolBarDemo.java, from Section 13.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 13.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 13.4, is a completely trivial demo of a JTable.
- ScatterPlotTableDemo.java, from Section 13.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 13.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 13.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 13.4, are classes that implement custom components. CustomComponentTest.java is a program that tests them.
- The Mandelbrot program from Section 13.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: Auxiliary Files
This section lists some of the extra source files that are required by various examples in the previous sections. The files listed here are those which are general enough to be potentially useful in other programming projects. Links to these files are also given above, along with the programs that use 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. The TextIO class defined by this file is only useful in a command-line environment, and it might be inconvenient to use in integrated development environments such as Eclipse in which standard input does not work particularly well. In that case, you might want to use the following file instead.
- textiogui/TextIO.java, a GUI version of TextIO that opens a window where TextIO I/O operations are performed. This is part of a package named textiogui to distinguish it from the normal TextIO. A companion class in that package, textiogui/System.java, is a fake System class that makes it possible to use System.out and other features of System in the same window. I use these classes to build executable jar files for my text-oriented examples that run in a window instead of on the command line. See the comments in the source code files for more information.
- SimpleAnimationStarter.java is a small class that you can edit to make very simple animations, in which every frame is drawn using basic drawing commands. This was used in Chapter 3.
- Mosaic.java contains subroutines for opening and controlling a window that contains a grid of colored rectangles. It depends on MosaicPanel.java. This is a toolbox for writing simple stand-alone applications that use a "mosaic window." It is used in several examples and exercises in Chapter 4 and Chapter 6.
- chapter4/MosaicPanel.java defines a subclass of JPanel that shows little rectangles arranged in rows and columns, with many options.
- StatCalc.java is a simple class that computes some statistics of a set of numbers. It is used only for a couple exercises in Chapter 5 and Chapter 6.
- Expr.java defines a class Expr that represent mathematical expressions involving the variable x. It is used only in a couple of the exercises in Chapter 8.
- TextReader.java, from Subsection 11.1.4, for reading character data from input streams. Input methods in an object of type TextReader are similar to the static input methods in TextIO.
- netgame.common is a package that defines a framework for networked games, which is discussed in detail in Section 12.5. The netgame packages also includes several examples.
- PokerRank.java can be used to assign ranks to hands of cards in poker games. The cards are defined in the class PokerCard.java. There is also a PokerDeck.java All of these classes are part of the package netgame.fivecarddraw, which is discussed in Subsection 12.5.4, but these classes can be used independently of the netgame framework.