Introduction to Programming Using Java, Fourth 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 4.0, which is available at https://math.hws.edu/javanotes/. You should be able to compile these files and use them. Note however that some of these examples depend on other classes, such as TextIO.class and MosaicFrame.class, that are not built into Java. These are classes that I have written. Links to the source code 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 CodeWarrior or JBuilder, you can simply add any required source code files to your project. See Appendix 2 for more information on Java programming environments and how to use them to compile and run these examples.
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.)
Note that many of these examples require Java version 1.3 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. Most of them use my non-standard class, TextIO for both input and output. The programs are stand-alone applications, not applets, but I have written applets that simulate many of the programs. These "console applets" appear on the Web pages that make up the text. The following list includes links to the source code for each applet, as well as links to the source code of the programs that the applets simulate. All of the console applets depend on classes defined in the files ConsoleApplet.java, ConsolePanel.java, and ConsoleCanvas.java. These three files, or the class files compiled from them, must be available when you compile any console applet. The class files must be available when the applet is used. (Being "available" means being in the same directory where you are compiling the program, or being in the same directory as the HTML file that uses the applet.) Most of the standalone programs depend on the TextIO class, which is defined in TextIO.java. Either TextIO.java or TextIO.class must be available when you compile the program, and TextIO.class must be available when you run the program. These programs and applets will work with Java 1.1, as well as with later versions.
- ConsoleApplet.java, a basic class that does the HelloWorld program in Section 2.1. (The other console applets, below, are defined as subclasses of ConsoleApplet.)
- Interest1Console.java, the first investment example, from Section 2.2. Simulates Interest.java.
- TimedComputationConsole.java, which does some simple computations and reports how long they take, from Section 2.3. Simulates TimedComputation.java.
- PrintSquareConsole.java, the first example that does user input, from Section 2.4. Simulates PrintSquare.java.
- Interest2Console.java, the second investment example, with user input, from Section 2.4. Simulates Interest2.java.
- Interest3Console.java, the third investment example, from Section 3.1. Simulates Interest3.java.
- ThreeN1Console.java, the "3N+1" program from Section 3.2. Simulates ThreeN1.java
- ComputeAverageConsole.java, which finds the average of numbers entered by the user, from Section 3.3. Simulates ComputeAverage.java
- CountDivisorsConsole.java, which finds the number of divisors of an integer, from Section 3.4. Simulates CountDivisors.java
- ListLettersConsole.java, which lists all the letters that occur in a line of text, from Section 3.4. Simulates ListLetters.java
- LengthConverterConsole.java, which converts length measurements between various units of measure, from Section 3.5. Simulates LengthConverter.java
- PrintProduct.java, which prints the product of two numbers from Section 3.7. (This was given as an example of writing console applets, and it does not simulate any stand-alone program example.)
- GuessingGameConsole.java, the guessing game from Section 4.2. Simulates GuesingGame.java. A slight variation of this program, which reports the number of games won by the user, is GuesingGame2.java.
- RowsOfCharsConsole.java, a useless program that illustrates subroutines from Section 4.3. Simulates RowsOfChars.java.
- TheeN2Console.java, an improved 3N+1 program from Section 4.4. Simulates ThreeN2.java
- RollTwoPairsConsole.java rolls two pairs of dice until the totals come up the same, from Section 5.2. Simulates RollTwoPairs.java. The applet and program use the class PairOfDice.java.
- HighLowConsole.java plays a simple card game, from Section 5.3. Simulates HighLow.java. The applet and program use the classes Card.java and Deck.java. (The Deck class uses arrays, which are not covered until Chapter 8.)
- BlackjackConsole.java lets the user play a game of Blackjack, from the exercises for Chapter 5. Uses the classes Card.java, Hand.java, BlackjackHand.java and Deck.java.
- BirthdayProblemConsole.java is a small program that uses arrays, from Section 8.2. Simulates BirthdayProblemDemo.java.
- ReverseIntsConsole.java demonstrates a dynamic array of ints by printing a list of input numbers in reverse order, from Section 8.3. Simulates ReverseWithDynamicArray.java, which uses the dynamic array class defined in DynamicArrayOfInt.java. A version of the program that uses an ordinary array of ints is ReverseInputNumbers.java.
- LengthConverter2Console.java, an improved version of LengthConverterConsole.java. It converts length measurements between various units of measure. From Section 9.2. Simulates LengthConverter2.java
- LengthConverter3.java is a version of the previous program, LengthConverter2.java, which uses exceptions to handle errors in the user's input. From the user's point of view, the behavior of LengthConverter3 is identical to that of LengthConverter2, so I didn't include an applet version in the text. From Section 9.4.
- ReverseFile.java, a program that reads a file of numbers and writes another file containing the same numbers in reverse order. From Section 10.2. This file depends on TextReader.java. Since applets cannot manipulate files, there is no applet version of this program.
- WordList.java, a program that makes a list of the words in a file and outputs the words to another file. From Section 10.3. Depends on TextReader.java. There is no applet version of this program.
- CopyFile.java, a program that copies a file. The input and output files are specified as command line arguments. From Section 10.3. There is no applet version of this program.
- Two pairs of command-line client/server network applications from Section 10.5: DateServe.java and DateClient.java; CLChatServer.java and CLChatClient.java. There are no corresponding applets.
- TowersOfHanoiConsole.java, a console applet that gives a very simple demonstration of recursion, from Section 11.1.
- ListDemoConsole.java demonstrates the list class that is defined in StringList.java, from Section 11.2. Simulates ListDemo.java.
- PostfixEvalConsole.java uses a stack to evaluate postfix expressions, from Section 11.3. The stack class is defined in NumberStack.java. Simulates PostfixEval.java.
- SortTreeConsole.java demonstrates some subroutines that process binary sort trees, from Section 11.4. Simulates SortTreeDemo.java.
- SimpleParser3Console.java reads expressions entered by the user and builds expression trees to represent them. From Section 11.5. Simulates SimpleParser3.java. Related programs, which evaluate expressions without building expression trees, are SimpleParser1.java and SimpleParser2.java.
- ListInsert.java, a very short program that demonstrates a subroutine for inserting a new item into a sorted generic List, from Section 12.2. There is no corresponding Console applet.
- WordListWithTreeSet.java, another demonstration program from Section 12.2. It makes a list of distinct words from a file. This is a version of WordList.java that uses a TreeSet to store the words. There is no corresponding Console applet.
- SimpleParser5Console.java uses a HashMap as a symbol table in a program that can evaluate expressions that contain variables, from Section 12.4. This applet simulates the program SimpleParser5.java.
- WordCount.java uses Maps, Sets, and Lists to make a list of all the words in a file along with the number of times that each word occurs in the file, from Section 12.4. This program requires TextReader.java. There is no applet version.
Part 2: Graphical Examples from the Text
- GUIDemo.java and GUIDemo2.java, simple GUI demo applets from Section 1.6. These applets demonstrate AWT and Swing components, respectively. (You won't be able to understand the source code until you read Chapters 6 and 7.)
- StaticRects.java, a rather useless applet from Section 3.7 that just draws a set of nested rectangles.
- MovingRects.java, the sample animation applet from Section 3.7. (This depends on SimpleAnimationApplet2.java.)
- RandomMosaicWalk.java, a standalone program that displays a window full of colored squares with a moving disturbance, from Section 4.6. (This depends on MosaicCanvas.java and Mosaic.java.) The applet version of the random walk, which is shown on the web page, is RandomMosaicWalkApplet.java. The source code for the applet uses some advanced techniques.
- RandomMosaicWalk2.java is a version of the previous program, RandomMosaicWalk.java, modified to use a few named constants. From Section 4.7.
- ShapeDraw.java, the applet with dragable shapes, from Section 5.4. This file produces six class files when it is compiled. You won't be able to understand everything in this file until you've read Chapters 6 and 7.
- HelloWorldApplet.java and HelloWorldApplet2.java, the utterly basic first sample applet, from Section 6.1. The second version has an init() method to set its foreground and background colors.
- HelloSwing.java and HelloSwing2.java, a very basic sample applet using Swing, events, and a dialog box, from Section 6.1. The second version uses an anonymous nested class to respond to clicks on a button.
- ColorChooserApplet.java, an applet for investigating RGB and HSB colors. This is a Java 1.1 applet which uses the AWT rather than Swing. From Section 6.3.
- RandomStrings.java, which draws randomly colored and positioned strings, from Section 6.3.
- ClickableRandomStrings.java, an extension of the previous applet in which the applet is redrawn when the user clicks it with the mouse, from Section 6.4. (ClickableRandomStrings2.java is an equivalent class that uses an anonymous subclass of MouseAdapter to do the event handling.)
- SimpleStamper.java, a basic demo of MouseEvents, from Section 6.4.
- SimpleTrackMouse.java, which displays information about mouse events, from Section 6.4.
- SimplePaint.java, a first attempt at a paint program in which the user can select colors and draw curves, from Section 6.4.
- KeyboardAndFocusDemo.java, which demos keyboard events, from Section 6.5.
- SubKillerGame.java, a simple arcade-style game, from Section 6.5. This applet is based on KeyboardAnimationApplet2.java.
- HelloWorldJApplet.java, a fairly simple example of using layouts and multiple buttons, from Section 6.6.
- HighLowGUI.java, a simple card game, from Section 6.5. This file defines two classes used by the applet. The program also depends on Card.java, Hand.java, and Deck.java
- SimplePaint2.java, a second attempt at a paint program in which the user can select colors and draw curves, from Section 6.5. This file defines two classes that are used by the applet.
- HighLowGUI2.java, a version of the simple card game, HighLowGUI.java. This version gets pictures of cards from an image file. From Section 7.1.
- DoubleBufferedDrag.java and NonDoubleBufferedDrag.java, two little applets that demonstrate double buffering. In the second, double buffering is turned off. From Section 7.1.
- RubberBand.java, a little applet that illustrates using an off-screen image and rubber band cursor, from Section 7.1.
- SimplePaint3.java, an improved paint program that uses an off-screen canvas to back up the on-screen image, from Section 7.1.
- LayoutDemo.java, which demos a variety of layout managers, from Section 7.2.
- BorderDemo.java, which shows six different type of Borders, from Section 7.2.
- RGBColorChooser.java, a simplified version of ColorChooserApplet.java that lets the user select a color with three sliders that control the RGB components, from Section 7.4.
- SimpleCalculator.java, which lets the user do arithmetic operations using JTextFields and JButtons, from Section 7.4.
- StopWatch.java and MirrorLabel.java, two small custom component classes, and ComponentTest.java, an applet that tests them. From Section 7.4.
- NullLayoutDemo.java, which demonstrates how to do your own component layout instead of using a layout manager, from Section 7.4.
- ShapeDrawWithMenus.java, an improved version of ShapeDraw.java that uses a menu bar, menus, and a pop-up menu, from Section 7.5.
- HelloWorldSpectrum.java, an applet that displays the message "HelloWorld" in animated color, from Section 7.6. A first example of using a Timer directly to animate an applet.
- ScrollingHelloWorld.java, an applet that scrolls a message, from Section 7.6. Shows how to animate an applet with a Timer created in the applet's start() method.
- Mandelbrot.java, an applet that draws a representation of the famous Mandelbrot set, from Section 7.6. This applet creates a separate thread to do the long computation of the colors for the set.
- ShapeDrawFrame.java, another version of ShapeDraw as a JFrame instead of an JApplet. From Section 7.7. The ShapeDrawFrame class contains a main() routine and can be run as an application. The applet ShapeDrawLauncher.java, merely displays a button. When you click on the button, a ShapeDrawFrame window is opened.
- HighLowFrame.java, another version of HighLowGUI2 as a JFrame instead of an JApplet, and with a main program to run it as an application. The applet HighLowLauncher.java is a button that can be used to open a HighLowFrame window.
- SimpleDialogDemo.java, a little applet that just demonstrates four of Swing's standard dialog boxes. From Section 7.7.
- RandomStringsWithArray.java, which draws randomly colored and positioned strings and uses an array to remember what it has drawn, from Section 8.2.
- SimpleDrawRects.java, in which the user can place colored rectangles on a canvas and drag them around, from Section 8.3. This simplified shape-drawing program is meant to illustrate the use of vectors. The file also defines a reusable custom component, RainbowPalette.
- Checkers.java, which lets two people play checkers against each other, from Section 8.5. At 702 lines, this is a relatively large program.
- TrivialEdit.java, a standalone application which lets the user edit short text files, from Section 10.3. This program depends on TextReader.java.
- ShapeDrawWithFiles.java, a final version of ShapeDraw.java that uses files to save and reload the designs created with the program. This version is an independent program, not as an applet. It is described at the end of Section 10.3.
- ReadURLApplet.java, an applet that reads data from a URL, from Section 10.4. This is similar to the command-line program ReadURL.java, from the same section.
- ChatSimulation.java, an that simulates a two-way network connection, using a thread, from Section 10.5.
- ChatWindow.java, a JFrame that supports chatting between two users over the network, from Section 10.5. This class depends on TextReader.java. This class can be run as a standalone application, as either a server or a client.
- BrokeredChat.java, an applet that sets up chat connections that use the previous example, ChatWindow.java. There is a server program, ConnectionBroker.java, which must be running on the computer from which the Web page containing the applet was downloaded. (The server keeps a list of available "chatters" for the applet.) From Section 10.5.
- Blobs.java, an applet that demonstrates recursion, from Section 11.1.
- DepthBreadth.java, an applet that uses stacks and queues, from Section 11.3.
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. Most of these are older applets will work with Java 1.1 or even Java 1.0.
- 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.)
- JavaPops.java, and applet that shows multi-colored "Java!"s, from the end of Section 2.5. (This depends on SimpleAnimationApplet.java.)
- MovingRects.java, the sample animation applet from Section 3.7. (This depends on SimpleAnimationApplet2.java.) This is also listed above, as one of the graphical examples from the text.
- 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.) (Another applet that shows an animation based on MosaicCanvas.java is MosaicStrobeApplet.java, the applet version of the solution to one of the exercises for Chapter 4.)
- SymmetricBrighten.java, a subclass of the previous example that makes a symmetric pattern, from the end of Section 5.6. Depends on MosaicCanvas.java and RandomBrighten.java.
- TrackLines.java, an applet with lines that track the mouse, from Section 6.6.
- KaleidaAnimate.java, an applet that shows symmetric, kaleidoscope-like animations, from Section 7.7. Depends on SimpleAnimationApplet.java.
- Maze.java, an applet that creates a random maze and solves it, from Section 8.5.
- SimpleCA.java, a Cellular Automaton applet, from the end of Section 9.4. This applet depends on the file CACanvas.java. For more information on cellular automata see https://math.hws.edu/xJava/CA/.
- TowersOfHanoi.java, an animation of the solution to the Towers of Hanoi problem for a tower of ten disks, from the end of Section 10.5.
- LittlePentominosApplet.java, the pentominos applet from the end of Section 11.5. This file defines two classes, LittlePentominosApplet and PentominosBoardCanvas. A pentomino is made up of five connected squares. This applet solves puzzles that involve filling a board with pentominos. If you click on the applet it will start a new puzzle. For more information see https://math.hws.edu/eck/xJava/PentominosSolver/ where you'll also find the big brother of this little applet.
- The applet at the end of Section 12.4 is the same Moire.java that was used at the end of ChapterĀ 1.
Part 4: Required Auxiliary Files
This section lists many 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 useful in other programming projects.
- TextIO.java which 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. The TextIO class defined in this file will be useless on a system that does not implement standard input. In that case, try using the following file instead.
- TextIO.java for GUI defines an alternative version of the TextIO class. It defines the same set of input and output routines as the original version of TextIO. But instead of using standard I/O, it opens its own window, and all 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.)
- ConsoleApplet.java, a class that can be used as a framework for writing applets that do console-style input/output. To write such an applet, you have to define a subclass of ConsoleApplet. See the source code for details. Many examples of applets created using ConsoleApplet are available above. Any project that uses this class also requires ConsolePanel.java and ConsoleCanvas.java.
- ConsolePanel.java, a support class that is required by any project that uses ConsoleApplet.
- ConsoleCanvas.java, a support class that is required by any project that uses ConsoleApplet.
- 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 SimpleAnimationApplet. This class uses Swing and requires Java 1.3 or higher. Section 3.7 has an example.
- SimpleAnimationApplet.java, a class that can be used as a framework for writing animated applets. This class has the same functionality as the previous class, but it is a Java 1.0 applet and so can be used even with very old versions of Java. This file is used as the basis for some of my end-of-chapter applets.
- Mosaic.java which let's you write programs that work with a window full of rows and columns of colored rectangles. Mosaic.java depends on MosaicCanvas.java. There is an example in Section 4.6.
- MosaicCanvas.java, a subclass of the built-in Canvas class that implements a grid of colored rectangles.
- KeyboardAnimationApplet2.java, a class that can be used as a framework for writing animated applets, which the user can interact with by using the keyboard. This framework can be used for simple arcade-style games, such as the SubKiller game in Section 6.5. To use the framework, you have to define a subclass of KeyboardAnimationApplet2. This requires Java 1.2 or higher.
- KeyboardAnimationApplet.java, an older version of the previous class that has essentially the same functionality but that works with Java 1.1. (This version is not used in this textbook.)
- Expr.java, a class for working with mathematical expressions that can include the variable x and mathematical functions such as sin and sqrt. This class was used in Exercise 9.4.
- TextReader.java, a class that can be used to read data from text files and other input streams. From Section 10.1.
David Eck ([email protected]), July 2002