Introduction to Programming Using Java, Eighth 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, Eighth 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 copy-and-paste the solution out of a Web browser window and into a text editing program. (You can't copy-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. Almost all 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. Since TextIO is defined in a package named textio, this means that TextIO.java and/or TextIO.class must be in a directory named textio, which must be in the same directory as 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. The enum types used in this program are defined in the same file as the program. An alternative version, SeparateEnumDemo.java, uses the same enums, but the enums are defined in separate files, Day.java and Month.java
- 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 LengthConverter2.java 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, SimpleParser2.java, and SimpleParser3.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.
- RiemannSumStreamExperiment.java, from Section 10.6, demos Java's stream API. Runs an experiment to measure the compute time for a problem when it is solved using a for loop, using a sequential stream, and using a parallel stream.
- ReverseFileWithScanner.java, from Section 11.2, shows how to read and write files in a simple command-line application. 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. ThreadTest3.java, from the same section, is a minor modification of ThreadTest2.java that uses an AtomicInteger instead of synchronization to safely add up values from several threads.
- 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. All of these programs use JavaFX as the GUI toolbox.
- GUIDemo.java is a simple demonstration of some basic GUI components from the JavaFX 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.
- RSimpleGraphicsStarter.java, from Section 3.9, draws a large number of randomly colored, randomly positioned disks. This 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. This program is based on SimpleAnimationStarter.java, which can be used as a starting point for writing similar animation programs. RandomCircles.java is another animation in which the computer continuously adds random colored disks to an image.
- RandomMosaicWalk.java, a program that displays a window full of colored squares with a moving disturbance, from Section 4.7. 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.8.
- 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.
- HelloWorldFX.java from Section 6.1, displays a the message in a window, with three buttons for changing the message and quitting the program. One of the messages is "Hello World", and this program is used as the first example for learning about JavaFX programming.
- SimpleColorChooser.jav, used in Section 6.3 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.
- RandomStringl.java, from Section 6.2, shows 25 copies of the string "Hello JavaFX!" in random colors and fonts.
- RandomCards.java, from Section 6.2, shows 5 cards selected at random from a deck. Depends on the files Deck.java Card.java, and the image resource file Cards.png
- 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.
- KeyboardEventsDemo.java, from Section 6.5, shows how to use keyboard events.
- SubKiller.java, from Section 6.3, lets the user play a simple arcade-style game. Uses an AnimationTimer as well as keyboard events.
- SliderDemo.java and TextInputDemo.java, small programs that demonstrate basic components, used as examples in Section 6.4
- OwnLayoutDemo.java, from Section 6.5, shows how to lay out the components in a Pane, which allows you to do your own layout.
- SimpleCalc.java, from Section 6.5, 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.
- HighLowGUI.java, from Section 6.5, 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, Deck.java, and an image resource file, cards.png.
- MosaicDraw.java, from Section 6.6, demonstrates menus. In this program, the user colors the squares of a mosaic by clicking-and-dragging the mouse. It uses MosaicCanvas.java to define the mosaic itself.
- RandomStringsWithArray.java, from Section 7.2, shows multiple copies of a message in random colors, sizes, and positions. There is an animation in which the copies move around in the window. This is an improved version of RandomStrings.java that uses an array to keep track of the data.
- 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 MosaicCanvas.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 MosaicCanvas.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.
- 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.
- 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.
- MultiprocessingDemo4.java, from Section 12.3 has the same functionality as MultiprocessingDemo3, but uses an ExecutorService, from package java.util.concurrent, to execute the tasks.
- 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.
- BoundPropertyDemo.java, from Section 13.1, demonstrates bindings and bidirectional bindings of JavaFX observable properties.
- CanvasResizeDemo.java, from Section 13.1, shows how to use property bindings to resize a Canvas whenever the Pane that contains the Canvas is resized.
- StrokeDemo.java, from Section 13.2, demonstrates the use of various line properties for stroking lines and rectangles.
- PaintDemo.java, from Section 13.2, demonstrates using a LinearGradient paint and using an ImagePattern paint to fill a polygon. Uses the image resource files tile.png and face-smile.png.
- TransformDemo.java,from Section 13.2, demonstrates applying various transforms, such as scale and rotate, to the drawing that is done in canvas. Uses the image resource file face-smile.png.
- ToolPaint.java, from Section 13.2, is a little paint program that illustrates pixel manipulation and the use of a transparent overlay canvas for some drawing operations. This program requires SimpleDialogs.java.
- SillyStamper.java, from Section 13.3, demonstrates using a ListView whose items are ImageViews. 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.
- SimpleTableDemo.java, from Section 13.3, is a small demo of an uneditable TableView.
- ScatterPlotTableDemo.java, from Section 13.3, demonstrates an editable TableView. The table holds (x,y) coordinates of points, and the user can edit the coords. A scatter plot of points is displayed.
- SimpleDialogs.java, from Section 13.4, contains static methods for showing several kinds of dialog box. The program TestDialogs.java tests the dialog methods by letting the user click buttons to open the different kinds of dialog.
- WebBrowser.java, from Section 13.4, is a simple web browser based on JavaFX's WebView control. This program shows how to manage multiple windows in a JavaFX application. It requires BrowserWindow.java, a subclass of Stage that does most of the work, and on SimpleDialogs.java.
- 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.mdbfx. The source code files can be found in the directory edu/hws/eck/mdbfx.
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 stream, System.in. TextIO also has methods for printing to System.out. It also supports other input sources and output destinations, such as files. TextIO is in a package named textio. The TextIO class 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. (Note that this GUI version of TextIO uses the Swing GUI toolkit rather than JavaFX.)
- SimpleGraphicsStarter.java and SimpleAnimationStarter.java are small programs that you can edit to make very simple pictures and animations These programs were used in Section 3.9 and in some of the exercises for Chapter 3.
- Mosaic.java contains subroutines for opening and controlling a window that contains a grid of colored rectangles. It depends on MosaicCanvas.java. It is used in several examples and exercises in Chapter 4.
- chapter4/MosaicCanvas.java defines a subclass of Canvas 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 is not used in this textbook, but it might be useful to some readers. A TextReader reads 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.
- SimpleDialogs.java contains easy-to-use static methods for showing several kinds of JavaFX dialog box and getting back the results of user interaction when appropriate.