Java, Java, Java Study Guide and Chapter Summaries – Morelli & Walde (3rd Edition) BSCS BSSE

BSCS and BSSE students can use this guide to study Java, Java, Java: Object-Oriented Problem Solving, Third Edition, a free CS1 textbook by Ralph Morelli and Ralph Walde of Trinity College in Hartford. It teaches Java with an objects-first approach: you meet objects, classes and UML designs in the first chapters, then learn data types, control structures, strings, inheritance and arrays, and finish with exceptions, files, recursion, GUIs, threads, networking and data structures. The authors got the copyright back from Pearson and released the PDF under CC BY 4.0.

Be aware of its age. The book was written for Java 5.0 in 2005, and the open PDF edition is dated June 2017. The object-oriented design lessons and most of the core language still apply, but applets, Vector and StringTokenizer are legacy, and there are no lambdas or newer file APIs. At about 850 pages it is also big, so most courses use Parts I and II and choose from Part III. Treat it as a thorough introduction to thinking in objects, and pair it with current Java documentation.

Book Overview

CourseObject-Oriented Programming (Java) / Introduction to Programming (CS1)
Degree ProgramsBSCS, BSSE
LevelIntroductory (first-year undergraduate)
EditionThird Edition (open-source PDF dated 25 June 2017; first published by Pearson Education in 2006)
AuthorsRalph Morelli and Ralph Walde, Trinity College, Hartford, CT
PublicationPreviously published by Pearson Education, Inc.; copyright reassigned to the authors in 2010
LanguageEnglish
Total Chapters17 chapters (0 to 16) in three parts, plus 8 appendices (A to H)
Programming LanguageJava (written for Java 5.0)
ExercisesSelf-Study Exercises with about 180 worked solutions, plus end-of-chapter exercises in most chapters
LicenseCreative Commons Attribution 4.0 International (CC BY 4.0), as printed in the PDF
FormatFree PDF (about 850 pages) from the authors’ site, with Java source code archives

Chapter List

Chapter 0: Computers, Objects, and Java

Part I · Difficulty: Easy · Key topics: hardware and software, fetch-execute cycle, compilers and interpreters, client/server, class, object, inheritance, UML

The opening chapter asks three questions: why study programming, why study Java and what is object-oriented programming. It tours the parts of a computer, from the CPU and main memory to secondary storage, and separates application software from system software. After a short look at networks, the Internet and the World Wide Web, it explains why programs are written in high-level languages and translated by compilers or interpreters. The second half introduces objects, classes, inheritance and the class hierarchy, then lists the principles that guide every later design chapter.

Key Points:

  • A computer runs only machine language, so source code in a high-level language is translated into object code by a compiler or interpreter.
  • Main memory (RAM) is volatile; secondary storage such as disks keeps data when the power is off.
  • The CPU repeats the fetch-execute cycle, and the ALU does the calculations and comparisons.
  • An object bundles attributes (variables) and actions (methods), and you send it messages by calling its methods.
  • A class is a template and an object is an instance of it; the Object class sits at the top of Java’s class hierarchy.
  • The design principles are divide and conquer, encapsulation, public interface, information hiding, generality and extensibility.

Memory Tip: Read the six principles as one sentence about a team: split the job, give each member one role, publish how to contact them, hide how they work, keep them general and leave room to grow.

Common Mistake: Mixing up a class with an object. The class is the blueprint, and each object made from it has its own copy of the instance variables.

Important Questions:

  • What is the difference between a compiler and an interpreter? Both translate high-level source code into machine language; a compiler produces an object code program, while an interpreter translates and runs the instructions as it goes.
  • What does information hiding mean? Each object shields its users from unnecessary details of how it does its job, so the way it works can change without breaking the objects that use it.

Chapter 1: Java Program Design and Development

Part I · Difficulty: Easy · Key topics: algorithm, pseudocode, stepwise refinement, syntax and semantic errors, identifiers, data types, bytecode, JVM, System.out

Chapter 1 argues that the sooner you start typing code, the longer the program takes, so it begins with design. A riddle-asking program is designed step by step, using pseudocode and stepwise refinement. Then the Java language elements arrive: comments, identifiers, keywords, primitive types, variables, assignment, operators, class definitions, object instantiation and dot notation. You see how a source file is edited, compiled to bytecode and run by the Java Virtual Machine, and how an application differs from an applet. The chapter ends with the System and PrintStream classes for printing output.

Key Points:

  • A syntax error breaks a grammar rule and is caught by the compiler; a semantic error is a design mistake the compiler cannot see.
  • Testing can reveal the presence of bugs but never prove their absence.
  • A declaration has the form Type VariableName; and an assignment stores the value of the right side into the variable on the left.
  • Source files end in .java, bytecode files in .class, and the file name must match the public class name.
  • Java is compiled to bytecode first and then interpreted by the JVM, which is what makes programs portable.
  • Dot notation such as System.out.print("hello") invokes a method of an object.

Practice Tip: Write a program that prints a few lines of a song with several println() calls, save it under the class name, then compile with javac and run with java. Seeing the .class file appear makes the compile step real.

Common Mistake: Saving the file under a different name from the public class. The compiler reports an error even though the code itself is fine.

Important Questions:

  • What is stepwise refinement? Starting from a general algorithm in pseudocode and rewriting each step in more detail until it can be written as Java statements.
  • What is the difference between a Java application and an applet? An application runs in stand-alone mode, while an applet runs inside a Java-enabled browser and is referenced from an HTML page.

Chapter 2: Objects: Using, Creating, and Defining

Part I · Difficulty: Easy · Key topics: String objects, Graphics, class definition, instance variables, public and private, constructors, new, null, Scanner, UML

This chapter moves from using objects to defining them. You first use predefined classes, creating String objects and drawing shapes with a Graphics object. Then the Riddle class from Chapter 1 is walked through line by line: its instance variables, constructor and methods, and how another class creates riddle objects and calls them. A full case study designs and implements a model of a two-person stick-taking game, with the design drawn in UML. A final section introduces the Java 5.0 Scanner class for reading keyboard input.

Key Points:

  • An object’s state is held in its instance variables, which are usually declared private.
  • Public methods form the object’s interface; private methods are for the class’s internal work.
  • A class header gives the name, accessibility and superclass, and every class extends Object by default.
  • Objects are created with new and a constructor; declaring a variable alone creates only a name.
  • static elements such as main() belong to the class, not to its instances.
  • A Scanner on System.in reads values with methods such as nextInt() and nextDouble().

Practice Tip: Define a small class with two private instance variables, a constructor and getter methods. Create two objects in main() and print both. You will see that each object keeps its own state.

Common Mistake: Declaring a variable of a class type and calling a method on it without new. The variable holds null, so the call fails at run time.

Important Questions:

  • Why are instance variables usually private? So other objects cannot change an object’s state directly; they have to go through its public methods.
  • What does the new operator do? Together with a constructor it creates an object, allocating memory for it and initializing its state.

Chapter 3: Methods: Communicating with Objects

Part I · Difficulty: Medium · Key topics: parameters, accessor and mutator methods, constructors, return values, pass by value, if-else, while, java.lang.Object, polymorphism

Chapter 3 takes the stick-taking game from Chapter 2 and makes it more realistic by studying methods and parameters. You learn to pass information in through parameters, to initialize an object with constructor methods and to get information back with return values. It explains what happens when a primitive value or an object reference is passed, then adds the if, if-else and while structures so methods can make decisions and repeat work. A test program checks the improved game, and the chapter closes with toString() from Object, a first look at inheritance and polymorphism and optional line drawing.

Key Points:

  • A formal parameter is the variable in the method declaration; an argument is the value passed in when the method is called.
  • A method’s signature is its name plus the number, types and order of its parameters, and a class cannot repeat a signature.
  • A primitive argument cannot be changed by the method, but the object behind a reference argument can.
  • If you write no constructor, the compiler supplies a default constructor.
  • Accessor methods (getX()) read state and mutator methods (setX()) change it.
  • while repeats a block as long as its boolean condition is true.

Practice Tip: Add a getter, a setter and a constructor that takes a starting value to a class of your own, then print the object after each change. Watching the state change shows exactly where information flows. The book’s own listings that call Scanner.create(System.in) will not compile; write new Scanner(System.in), as Section 2.6 does.

Common Mistake: Putting a semicolon straight after else or after an if condition, which ends the statement early so the next line always runs.

Important Questions:

  • What is the difference between passing a primitive and passing an object reference? A primitive is passed as a copy and cannot be changed by the method; a reference lets the method modify the object it refers to.
  • Why can a constructor not have a return type such as void? A constructor is not an ordinary method; it is invoked when the object is created and has no result type at all.

Chapter 4: Input/Output: Designing the User Interface

Part I · Difficulty: Medium · Key topics: user interface, command-line I/O, buffer, wrapper class, GUI, Swing, JFrame, event-driven programming, ActionListener, file input

Chapter 4 separates the computation from the user interface so that one game or program can work with different interfaces. It builds a command-line interface around a keyboard reader that uses buffered input, wrapper classes for converting text to numbers and well-designed prompts. Then it introduces graphical interfaces with Java’s AWT and Swing packages, top-level containers, buttons, text fields, listeners and the event-driven model. Both interfaces are applied to the one-row Nim game as a case study, and an optional section reads a file with File and Scanner.

Key Points:

  • The user interface handles input and output only, and should be designed independently of the computation.
  • A buffer holds typed characters until the program needs them, which is why Backspace works.
  • A wrapper class converts between primitive data and objects, for example turning a string into an int.
  • GUI programs are event-driven: they react to events generated by the user.
  • Swing (javax.swing) is the newer package; every GUI must live in a top-level container such as a JFrame.
  • Events are handled by listener objects, and an interface is a class with only method signatures and constants.

Practice Tip: Build a tiny Swing window with a text field, a button and a text area that echoes what you type. Then move the echo logic to its own class so you can reuse it from a command-line version.

Common Mistake: Mixing game logic into the interface class. When the rules live in the GUI code, you cannot reuse them with a command-line interface.

Important Questions:

  • What is event-driven programming? A style in which the program waits for events, mostly from the user, and each event is passed to a listener object that handles it.
  • What is a top-level container? A GUI container that cannot be added to another container, such as JFrame; all GUI programs must be placed in one.

Chapter 5: Java Data and Operators

Part II · Difficulty: Medium · Key topics: boolean operators, short-circuit evaluation, int and double, type conversion, cast, Math, NumberFormat, char and Unicode, precedence

Part II begins with the data and operators that every program needs. Chapter 5 covers boolean data with its operators and short-circuit evaluation, then numeric data: the integer types byte, short, int and long, the floating-point types float and double, promotion, casting and round-off error. It tours the Math and NumberFormat library classes, works through numeric processing examples and explains character data in Unicode. The closing section, Problem Solving = Representation + Action, argues that choosing a good representation is often the key to solving a problem.

Key Points:

  • Integer literals default to int and floating-point literals default to double.
  • A type with n bits can represent 2 to the power n different values, and Java fixes the bit sizes to help portability.
  • 7 / 2 is 3 but 7.0 / 2 is 3.0, because integer and floating-point division differ.
  • Characters use Unicode, whose first 128 codes match ASCII.
  • Operator precedence and associativity decide evaluation order, and parentheses can always override them.
  • When you revise a class used by others, keep its public interface as stable as you can.

Practice Tip: Print 7 / 2, 7.0 / 2 and (double) 7 / 2 side by side, then try adding 0.1 to itself ten times. You will see both integer division and round-off error with your own eyes.

Common Mistake: Expecting integer division to keep the fraction. Dividing two int values always gives an int result.

Important Questions:

  • What is short-circuit evaluation? With && and || Java stops evaluating as soon as the result is known, so the right operand may never be evaluated.
  • What is a cast? An explicit conversion of a value from one type to another, such as (int) 3.7, which may lose information.

Chapter 6: Control Structures

Part II · Difficulty: Medium · Key topics: for, while, do-while, loop bound, infinite loop, nested loops, switch, preconditions, postconditions, structured programming

Chapter 6 extends repetition and selection. It starts with counting loops and the for statement, showing initializer, loop entry condition and updater, then loop bounds, infinite loops and indentation. Conditional loops follow, using while and do-while for sentinel-controlled input, averages and data validation. Worked examples include a car loan, a checkerboard drawing and a running average. The chapter closes with principles of loop design, the switch multiway selection and structured programming, including preconditions and postconditions.

Key Points:

  • Every loop has an initializer, a loop entry condition (or boundary condition) and an updater.
  • The book lists four kinds of bound: counting, sentinel, flag and limit.
  • Counting loops usually start at 0 (zero indexing), while countdowns can use unit indexing.
  • An infinite loop appears when the updater never moves the counter toward the bound.
  • Structured programming builds programs from sequence, selection, repetition and method-call structures, each with one entry and one exit.
  • A precondition must be true before a code segment runs and a postcondition must be true when it finishes.

Practice Tip: Write the same countdown with for, while and do-while. Then change the bound so one version loops forever and press Ctrl-C to stop it; it teaches loop bounds quickly.

Common Mistake: Leaving out braces around a multi-statement loop body. Only the first statement after the loop heading repeats, however you indent the rest.

Important Questions:

  • What is the difference between a counting loop and a conditional loop? A counting loop is used when you know in advance how many repetitions are needed; a conditional loop repeats until some condition, such as a sentinel input, changes.
  • What is a priming read? The first input read before a sentinel-controlled loop starts, so that the loop condition has a value to test.

Chapter 7: Strings and String Processing

Part II · Difficulty: Medium · Key topics: String literals, immutability, indexOf, charAt, substring, equals versus ==, StringBuffer, StringTokenizer, FontMetrics

Chapter 7 treats strings as objects and as data to be processed. It covers string literals, the concatenation operator and zero-based indexing, then methods for finding things within a string, such as indexOf(), and for extracting parts with substring(). Programs include a keyword search and a routine that processes names and passwords. It shows how to walk through a string one character at a time, compare strings correctly, use StringBuffer for modifiable text and StringTokenizer for splitting. An optional section draws and centers text with fonts.

Key Points:

  • A String object is immutable; a StringBuffer can be changed with insert() and append().
  • Every occurrence of the same string literal refers to one shared object.
  • equals() compares contents, while == only tests whether two references point to the same object.
  • Strings are zero indexed, and length(), charAt(), indexOf() and lastIndexOf() are the core tools.
  • A StringTokenizer splits a string into tokens at delimiters, using whitespace by default.
  • FontMetrics gives text dimensions, which helps when centering text in a window.

Practice Tip: Write a method that counts how many times a given letter appears in a sentence using charAt() in a loop. Test it with an empty string and a one-letter string to check the loop bounds.

Common Mistake: Comparing two strings with ==. It may print true or false depending on how the objects were created; use equals() for content.

Important Questions:

  • What does it mean that strings are immutable? Once created, the characters of a String object cannot be changed; operations such as concatenation create new objects.
  • What is the difference between equals() and == on strings? equals() is true when both hold the same sequence of characters; == is true only when both variables refer to the same object.

Chapter 8: Inheritance and Polymorphism

Part II · Difficulty: Hard · Key topics: inheritance, dynamic binding, polymorphism, abstract classes, interfaces, static and dynamic type, cipher hierarchy, game hierarchy

Chapter 8 collects the ideas that earlier chapters only touched and makes inheritance and polymorphism the main subject. It explains Java’s inheritance mechanism, then abstract classes and interfaces and how dynamic binding resolves a method call at run time. The examples grow from a toggle button to a hierarchy of ciphers, with substitution and transposition methods for encoding text. A larger case study builds a hierarchy of two-player games that can share one user interface. It ends with a set of principles of object-oriented design.

Key Points:

  • A subclass inherits the public and protected instance variables and methods of its superclass.
  • Dynamic (late) binding picks the method implementation at run time, and all calls except final or private methods use it.
  • Polymorphism means one method call can lead to different actions depending on the object it is invoked on.
  • A variable has a static (declared) type and a dynamic (actual) type, which may be a subclass.
  • An abstract class has at least one method with no implementation, so it can be subclassed but not instantiated.
  • A class implements an interface by giving implementations for all of its abstract methods.

Practice Tip: Make an abstract Shape with an abstract area() method and two subclasses. Fill an array of Shape variables with both kinds and loop over it calling area(); the right version runs each time.

Common Mistake: Thinking the declared type decides which method runs. For overridden methods the object’s actual type decides at run time.

Important Questions:

  • What is dynamic binding? The mechanism that links a method call to the correct implementation while the program runs, rather than at compile time.
  • What is the difference between an abstract class and an interface? An abstract class may contain some implemented methods and variables; an interface contains only method signatures and constants.

Chapter 9: Arrays and Array Processing

Part II · Difficulty: Medium · Key topics: one-dimensional arrays, array length, insertion sort, selection sort, sequential and binary search, two-dimensional arrays, Vector, polymorphic sorting, N-player game

Chapter 9 introduces arrays as named collections of items of one type, with the argument that one loop over an array replaces dozens of separate variables. It covers declaring, instantiating and initializing arrays, simple array programs and a letter-frequency counter. Then come the array algorithms: insertion sort and selection sort, sequential and binary search. Two-dimensional and multidimensional arrays follow, then the Vector class, a polymorphic sort and a case study of an N-player computer game that includes a sliding tile puzzle with a GUI version.

Key Points:

  • An array of N elements has indexes 0 to N-1, and its length variable is the natural loop bound.
  • An array is declared with a type and then created with new, which allocates the memory.
  • Passing an array to a method passes a reference, not a copy of all the elements.
  • Swapping two elements needs a temporary variable.
  • Binary search needs a sorted array; sequential search does not.
  • Each dimension of a multidimensional array has its own length.

Practice Tip: Fill an int array with ten random numbers, sort it with selection sort and print the array after every pass. The output shows exactly how each pass fixes one more element.

Common Mistake: Looping until k <= arr.length. The last valid index is length - 1, so the extra pass throws an out-of-bounds exception.

Important Questions:

  • What is the difference between insertion sort and selection sort? Both make several passes over the array; selection sort finds the smallest remaining element and moves it into place, while insertion sort inserts each element into the sorted part.
  • Why must an array be sorted before a binary search? Binary search repeatedly discards half of the range by comparing with the middle element, which only works when the elements are in order.

Chapter 10: Exceptions: When Things Go Wrong

Part III · Difficulty: Medium · Key topics: try, catch, finally, throw, checked and unchecked exceptions, exception hierarchy, stack trace, custom exceptions, JOptionPane

Part III begins with the fact that mistakes are the norm rather than the exception. Chapter 10 explains how Java signals errors by throwing exceptions, how the exception hierarchy is organized and how a try/catch/finally statement handles them. It separates checked from unchecked exceptions, shows how Java searches static and dynamic scope for a handler, and explains the method stack trace. The design section covers four ways to respond to an error and robust program design, and the chapter ends with user-defined exceptions and error dialogs built with JOptionPane.

Key Points:

  • Checked exceptions must be caught or declared with throws; unchecked ones are subclasses of RuntimeException.
  • A catch block handles any exception that matches its parameter class, including subclasses, and there may be several per try block.
  • The finally block runs whether or not an exception is thrown.
  • printStackTrace() shows the chain of method calls that led to the statement that threw.
  • Exceptions are for truly exceptional conditions, not for normal program control.
  • You define your own exception by extending Exception or one of its subclasses.

Practice Tip: Write a method that divides two integers read from the user. Run it with zero as the divisor first without a handler, read the stack trace, then add a try/catch and compare.

Common Mistake: Catching an exception and doing nothing. The program carries on in a broken state and the real cause is hidden.

Important Questions:

  • What is the difference between checked and unchecked exceptions? Checked exceptions must be handled by the method or declared in its throws clause; unchecked exceptions (RuntimeException subclasses) need not be, and uncaught ones go to Java’s default handler.
  • What is the purpose of a finally block? To hold statements, such as clean-up code, that must run whether or not an exception was raised.

Chapter 11: Files and Streams: Input/Output Techniques

Part III · Difficulty: Medium · Key topics: streams, text and binary files, buffering, File class, serialization, JFileChooser, IOException, EOFException

Chapter 11 shows how programs store and retrieve data outside memory. It defines files and streams, and the data hierarchy from bit up to database. A case study reads and writes text files, and later sections cover the File class for paths and attributes and the reading and writing of binary files. Object serialization saves whole objects to a stream, and JFileChooser lets the user pick a file in a dialog. The last section uses file data inside programs. A standard algorithm recurs: open a stream, do the I/O, close the stream.

Key Points:

  • A stream delivers data between a program and a source or destination; System.in and System.out are streams.
  • Text I/O uses Reader and Writer classes, while binary I/O uses InputStream and OutputStream.
  • Text input signals the end with null or -1, but binary reads throw EOFException.
  • Streams can be chained, for example a DataOutputStream on top of a FileOutputStream.
  • Object serialization writes an object to an ObjectOutputStream and deserialization reads it back.
  • Close streams when finished so an abnormal exit does not damage the file.

Practice Tip: Write a program that saves five lines of text to a file and a second one that reads them back and numbers them. Open the file in a text editor in between to confirm what was stored.

Common Mistake: Placing close() inside the same try block as the read loop. When an exception is thrown the close is skipped and the stream stays open.

Important Questions:

  • What are the three steps for file I/O? Open a stream to the file, perform the input or output, and close the stream.
  • What is object serialization? The process of writing an object to an output stream so it can be saved or sent and later rebuilt by deserialization.

Chapter 12: Recursive Problem Solving

Part III · Difficulty: Hard · Key topics: recursive definition, base case, recursive case, recursion parameter, tail recursion, recursion versus iteration, fractals, JComboBox

Chapter 12 opens with the Sierpinski gasket, a pattern that is painful to draw with nested loops but natural with recursion. It introduces recursion as both a problem-solving technique and an alternative to loops, starting from recursive definitions in mathematics and moving to recursive methods. You apply it to string methods and to array processing with a head-and-tail style of algorithm, and then to drawing recursive fractals. The design sections explain tail recursion and compare recursion with iteration, and an optional section adds the JComboBox component.

Key Points:

  • A recursive definition defines the nth case in terms of the (n-1)st case plus a limiting condition.
  • A recursive method has a base case that stops the process and a recursive case that works on a smaller, self-similar problem.
  • A recursion parameter controls the recursion and must make progress toward the base case.
  • Anything done iteratively can be done recursively, and the other way round.
  • Method calls cost memory and CPU time, so a recursive version is generally less efficient than an iterative one.
  • A method is tail recursive only if every recursive call is the last action it performs.

Practice Tip: Write a recursive method that prints a string backwards, then add a print statement at the start and end of each call. The indented trace shows calls stacking up and unwinding.

Common Mistake: Forgetting the base case, or writing a recursive call that does not move toward it, which ends in a stack overflow.

Important Questions:

  • What are the two parts of a recursive method? A base (limiting) case that stops the recursion, and a recursive case that calls the method on a smaller version of the problem.
  • When is a method tail recursive? When each recursive call is the very last action the method executes, so no work remains after the call returns.

Chapter 13: Graphical User Interfaces

Part III · Difficulty: Hard · Key topics: AWT versus Swing, model-view-controller, event model, listeners, containers, layout managers, check boxes, radio buttons, menus, scroll panes

Chapter 13 gives a history of Java’s GUI libraries, from the platform-dependent AWT to the pure-Java Swing component set. It explains why Swing is built on the model-view-controller architecture and how Java’s event model uses listeners. A case study designs a basic GUI, and later sections cover containers, layout managers, check boxes, radio buttons, borders, menus and scroll panes. Throughout, it draws out design principles for usable interfaces, such as limiting the number of input devices a user must handle and making errors easy to recover from.

Key Points:

  • AWT components use native peers; Swing components are written entirely in Java and so look the same across platforms.
  • Swing components split into model (state), view (looks) and controller (behavior).
  • Components register with event listeners, and the listener handles the component’s events.
  • Components form a containment hierarchy rooted at a top-level window, and content goes in its content pane.
  • A layout manager controls the size and arrangement of components, with flow, border, grid and box layouts built in.
  • Radio buttons belong to a group where only one can be selected, while a check box always shows its own state.

Practice Tip: Build one window with a BorderLayout, a text area in the center and a panel of buttons at the bottom. Resize the window to see how each layout region behaves.

Common Mistake: Placing components without a layout manager in mind. They then overlap or shrink to nothing when the window is resized.

Important Questions:

  • Why is Swing called lightweight and AWT heavyweight? Swing components are written entirely in Java and do not need a native window-system peer, while each AWT component has one, making it more platform dependent.
  • What is the model-view-controller architecture? A design that divides a component into the model (its state), the view (how it looks) and the controller (what it does).

Chapter 14: Threads and Concurrent Programming

Part III · Difficulty: Hard · Key topics: thread, Runnable, scheduling, time slicing, thread life cycle, synchronized, monitor, wait and notify, producer/consumer, Pong

Chapter 14 is about doing more than one thing at a time. It defines a thread as a single sequence of statements, explains time slicing and scheduling, and shows the two ways to create a thread: subclass Thread or pass a Runnable object. You study the thread life cycle and use threads to keep an interface responsive. A cooperating-threads case study, built around a take-a-number bakery, introduces the producer/consumer model, synchronized methods and wait() and notify(). A game of Pong closes the chapter.

Key Points:

  • Threads are asynchronous, so never base an algorithm on assumptions about their timing.
  • A thread is created by subclassing Thread and writing run(), or by giving a Thread a Runnable.
  • Round-robin scheduling gives equal time slices; priority scheduling runs higher priorities first.
  • A thread moves through ready, running, waiting, sleeping and blocked states.
  • An object with synchronized methods is a monitor and lets one thread at a time into a critical section.
  • Coordinate cooperating threads with wait() and notify(), never by chance.

Practice Tip: Start two threads that each print a letter and sleep a random time. Run it several times; the changing output is the most direct demonstration that thread timing is unpredictable.

Common Mistake: Sharing a variable between threads without synchronization and assuming it will be updated in a sensible order.

Important Questions:

  • What are the two ways to create a thread in Java? Subclass Thread and override run(), or create a Thread and pass it an object that implements Runnable.
  • What is a critical section? A section of code, marked synchronized, that must not be interrupted by other cooperating threads so that shared data stay consistent.

Chapter 15: Sockets and Networking

Part III · Difficulty: Hard · Key topics: networks, protocols, URL, Socket, ServerSocket, client/server, sandbox security, servlets, Java Server Pages

Chapter 15 moves from files on one computer to resources on a network. It gives an overview of LANs, WANs, topologies and protocols such as HTTP, SMTP and FTP, then uses java.net.URL to download images and text into a graphical slide show program. Next come sockets: client/server communication, generic client and server classes, and the one-row Nim game played across a network. It also explains Java’s sandbox security restrictions for downloaded code, and ends with a short introduction to servlets and Java Server Pages.

Key Points:

  • An internet joins two or more networks with routers, and the Internet uses the Internet Protocol (IP).
  • A URL has the form method://host:port/path/file and is represented by java.net.URL.
  • Network resources can be read with the same input streams used for disk files.
  • A socket is a two-way channel between two programs; the server listens and the client requests.
  • Once connected, ordinary input and output streams carry the data over the socket.
  • The sandbox model limits what downloaded, untrusted code may do.

Practice Tip: Write a tiny echo server and client on your own computer using localhost and a port number above 1024. Start the server first, then the client, and watch each line come back.

Common Mistake: Starting the client before the server is listening, or using a wrong host or port; the result is a connection-refused exception.

Important Questions:

  • What is the client/server model? An application split into a client, which requests a service, and a server, which provides it.
  • What is a socket? A two-way communication channel between two running programs on a network, created in Java with the Socket and ServerSocket classes.

Chapter 16: Data Structures: Lists, Stacks, and Queues

Part III · Difficulty: Hard · Key topics: linked list, Node, self-referential class, abstract data type, stack, queue, Java Collections Framework, generics, Set, Map, binary search tree

The final chapter moves from static arrays to dynamic structures that grow and shrink. You build a singly linked list from self-referential Node objects and learn to traverse, insert and remove. The list becomes an abstract data type with a hidden implementation, and inheritance extends it into a stack with push and pop and a queue with enqueue and dequeue. Then it shows the Java Collections Framework and the generic types added in Java 5.0, uses the Set and Map interfaces and ends with the binary search tree.

Key Points:

  • An array is a static structure; a vector or linked list is dynamic and can change size while the program runs.
  • A node holds data plus a link to another node, so the node class refers to itself.
  • An abstract data type combines data with the operations on it, and hides the implementation behind a public interface.
  • A stack is last-in-first-out with push and pop, and a queue is first-in-first-out with enqueue and dequeue.
  • Generic types, new in Java 5.0, let collections such as Vector<E> declare what they hold.
  • In a binary search tree, smaller values go in the left subtree and larger values in the right.

Practice Tip: Draw a three-node list on paper, then run your insert-at-head and delete-from-middle code line by line, redrawing the links after each assignment. Most list bugs show up on the page first.

Common Mistake: Changing a node’s link before saving the reference to the next node, which cuts the rest of the list off.

Important Questions:

  • What is an abstract data type? A concept that combines a collection of data with the operations that can be performed on it, while keeping the implementation hidden.
  • What is the difference between a stack and a queue? A stack inserts and removes at the same end (last in, first out), while a queue inserts at the rear and removes from the front (first in, first out).

Appendices A-H

Appendix · Difficulty: Easy · Key topics: coding conventions, javadoc, JDK tools, ASCII and Unicode, keywords, operator precedence, inner classes, autoboxing, enumerations, UML resources

The eight appendices are short reference material. Appendix A sets out coding conventions based on the Java language specification and adapted for a course, with comment styles and javadoc. Appendix B describes the JDK command-line tools such as javac, java, javadoc, jar, jdb and javap. Appendices C, D and E give the ASCII and Unicode tables, the Java keywords and the operator precedence table. Appendix F explains inner classes, Appendix G covers autoboxing and enumerations from Java 5.0, and Appendix H lists Java and UML resources.

Key Points:

  • Implementation comments use // and /* */, while documentation comments use /** */ and feed the javadoc tool.
  • javac compiles source to bytecode and java runs it; appletviewer is listed for applets.
  • Java has four kinds of inner class: nested top-level, member, local and anonymous.
  • Autoboxing wraps primitive values in wrapper objects automatically, and unboxing reverses it.
  • Java 5.0 enumerations make it easier to represent a fixed set of named constants.
  • Dated: Appendix B and the references point to Sun Microsystems web pages and an applet example from 2005, so use current JDK documentation for installation.

Practice Tip: Keep Appendices D and E open while you do Chapters 5 and 6. Checking the precedence table before running an expression is faster than debugging a wrong result.

Common Mistake: Following the Appendix B download and PATH instructions literally. The links belong to the Sun Microsystems era, so install a current JDK from its vendor instead.

Important Questions:

  • What is autoboxing? A Java 5.0 feature that automatically creates a wrapper-class object from a primitive value and unwraps it again when needed.
  • What is an anonymous inner class? A local class whose definition and use are combined in a single expression, intended for one-time use and without a constructor.

How to Study This Book

The Preface declares three parts. Part I (Chapters 0 to 4) introduces objects, classes, methods, parameters and user interfaces. Part II (Chapters 5 to 9) completes the language with data types, control structures, strings, inheritance and arrays. Part III (Chapters 10 to 16) holds advanced topics that the authors call self-contained, so you can pick them as your course needs. The authors say Parts I and II are the topics found in a typical CS1 course.

The Preface gives a 13-week syllabus you can copy. Week 1 covers Chapters 0 and 1, weeks 2 and 3 cover Chapters 2 and 3, week 4 covers Chapter 4, week 5 covers Chapter 5, weeks 6 and 7 cover Chapter 6, week 8 covers Chapter 7, week 9 covers Chapter 8, week 10 covers Chapter 9 and week 11 covers recursion in Chapter 12. The last two weeks are for chosen advanced topics such as exceptions, GUIs and threads. Note that the table lists chapter numbers for some of the advanced topics that do not match the Table of Contents, so follow the chapter titles.

Start with Chapters 0 to 3 in order and type every example. The book teaches objects first, so the same stick-taking game appears in Chapters 2, 3, 4 and later, and each chapter adds a layer to it. Chapter 4 can be read for either interface: the authors say the command-line interface and the GUI interface can be used interchangeably in most later chapters, so if you find Swing hard at first, use the command-line side and return to it before Chapter 13.

Chapters 8 and 9 are where most students slow down. Give Chapter 8 two sittings, one for inheritance, abstract classes and interfaces and one for the cipher and game hierarchies. In Chapter 9, make sure you can trace both sorting algorithms by hand before you read the case studies. Chapter 12 on recursion builds on strings and arrays, and the authors’ sample syllabus reads it right after Chapter 9, before the exceptions chapter. Chapter 16 assumes arrays and inheritance.

Two gaps in the PDF are worth knowing about. Chapter 5 ends with an Exercises heading and a short note, but no end-of-chapter exercises or solutions follow it, so make up practice problems from the chapter text. Also, a few listings in Chapters 2 and 3 call Scanner.create(System.in), which is not in the released Java API; write new Scanner(System.in) instead, exactly as Section 2.6 does. Self-study exercises with worked solutions appear inside most chapters, and the authors’ page offers source code archives. A solutions manual for the end-of-chapter exercises is available to instructors on request.

The book was written for Java 5.0 in 2005, so it does not cover later language features such as lambda expressions or the newer file API, and it does not use JavaFX, JUnit or Maven. Treat applets, Vector, StringBuffer and StringTokenizer as historical: learn the ideas, then use ArrayList, StringBuilder and current GUI practice in real projects. The object-oriented design lessons, the UML diagrams and the data-structure material are still sound.


Used In These Programs

This book is used for the Object-Oriented Programming (Java) course in: BS Computer Science and BS Software Engineering. Browse all object-oriented programming books, all Java books or all Computer Science books.

Who Should Read This

This book is written for a first course in programming: the authors say it suits a typical Introduction to Computer Science (CS1) course or a slightly more advanced Java as a Second Language course. That makes it a good fit for BSCS and BSSE students in the first two semesters who need object-oriented programming in Java, and for anyone who wants an objects-first route rather than a syntax-first one. If you want a shorter, lighter Java text to read alongside it, try Think Java, and when you reach Chapter 16 continue with Open Data Structures. It is not a book for modern Java features, Android or web development, and it is large, so you will not read all of it in one semester.


Applicable Universities

This book is useful for students at Pakistani universities offering BS Computer Science and BS Software Engineering, including Punjab University, Virtual University, COMSATS, FAST, UET, NUST, and other HEC-recognized institutions.

Official Copy of Java, Java, Java

This book is free from the authors’ official page at Trinity College. Click the button below to open that page, where you can download the PDF and the Java source code archives. We link to the official page and do not host the file.

→ Visit Official Page

FAQs

Is Java, Java, Java free to download?

Yes. The PDF’s own title page says the work is licensed under the Creative Commons Attribution 4.0 International License (CC BY 4.0), which allows you to use, share and modify the book as long as you give credit. The Preface explains that Pearson Education reassigned the copyright to the authors in 2010 so they could release it openly. This page links to the authors’ official page and does not host the file.

Which edition is this, and which Java version does it use?

This is the Third Edition by Ralph Morelli and Ralph Walde. The PDF is the open-source edition, dated 25 June 2017 on its title page, and the book was first published by Pearson Education in 2006. It was written for Java 5.0, so it predates lambda expressions, the newer file API and the other changes of later Java releases.

How many chapters and exercises does it have?

There are 17 chapters, numbered 0 to 16, plus eight appendices (A to H), in about 850 pages. Most chapters have Self-Study Exercises with worked solutions, about 180 in the PDF, and end-of-chapter exercises. In this PDF Chapter 5 has an Exercises heading but no list under it. Solutions to the end-of-chapter exercises are given only to instructors who ask the authors.

Is it good for complete beginners?

Yes, it is designed for a first programming course (CS1) or a Java as a Second Language course, and it assumes no earlier programming. It is objects-first, so you meet classes and objects in Chapter 2 and use them constantly. Because of its size and its slow, detailed style, many students find it easier to follow the examples by typing them in.

Does it cover object-oriented programming?

Yes, that is its main subject. It covers classes, objects, constructors, encapsulation and information hiding, inheritance, abstract classes, interfaces, dynamic binding and polymorphism, with UML class diagrams for the designs. Chapter 8 is devoted to inheritance and polymorphism, and a closing section lists principles of object-oriented design.

Is it still worth reading in 2026?

Yes for the ideas, with care for the details. The object-oriented design lessons, control structures, strings, arrays, recursion, exceptions and data structures still apply, and the core language examples generally still compile. Applets, Vector, StringBuffer and StringTokenizer are legacy, a few early listings use a Scanner.create method that is not in the released API, and the JDK appendix points to old Sun Microsystems pages. Check anything you plan to use against current Java documentation.

Related Books

Java, Java, Java is a long, patient, objects-first introduction to Java, and its design lessons outlast its 2005 library choices. Use it for the concepts, check details against current Java and browse more Computer Science books for the rest of your semester.

Java, Java, Java: Object-Oriented Problem Solving, Third Edition by Ralph Morelli and Ralph Walde, Trinity College. Previously published by Pearson Education, Inc.; copyright reassigned to the authors in 2010. Open-source edition PDF dated 25 June 2017, licensed under the Creative Commons Attribution 4.0 International License (CC BY 4.0). Official source: https://www.cs.trincoll.edu/~ram/jjj/. This page links to the official site and does not host or copy the book.

Leave a Comment