Table of Contents

List of Programs
List of Figures
List of Tables
Preface to second version
PART 1Structured Programming
1Getting started
1.1Programming
1.2Editing source code
Source code file naming rules
1.3Development tools for Java
1.4Compiling Java programs
1.5Running Java programs
1.6The components of a program
Operations
Programming with objects
Object-based programming
1.7The Java programming language
Classes and methods
Comments and indentation
Program entry point
Method calls
Variables
1.8The Java Virtual Machine
1.9Review questions
1.10Programming exercises
2Basic programming elements
2.1Printing to the terminal window
The print() and println() methods
Creating program output using strings
2.2Local variables
Declaring variables
Assigning variables
Logical errors
Literals and constants
Choosing names
2.3Numerical data types
Primitive data type int
Primitive data type double
2.4Arithmetic expressions and operators
Arithmetic expression evaluation rules
Conversion between primitive data types
Precedence and associativity rules
Integer and floating-point division
2.5Formatted output
Format string
Sample format specifications
Printing with fixed field widths
2.6Reading numbers from the keyboard
The Scanner class
Reading integers
Reading floating-point numbers
Error handling
Reading multiple values per line
Skipping the rest of the line when reading values from the keyboard
2.7Review questions
2.8Programming exercises
3Program control flow
3.1Boolean expressions
Boolean primitive data type
Relational operators
Understanding relational operators
Logical operators
Short-circuit evaluation
De Morgan's laws
Using Boolean expressions to control flow of execution
3.2Control flow: selection statements
Simple selection statement: if
Blocks of statements: { ... }
Local variables in a block
Selection statement with two choices: if-else
Nested selection statement
3.3Control flow: loops
Loop test before loop body: while
Loop test after loop body: do-while
Infinite loops
Using loops to implement user dialogue
Choosing the right loop
Nested loops
3.4Assertions
Making assertions
Assertions as a testing technique
3.5Review questions
3.6Programming exercises
PART 2Object-based Programming
4Using objects
4.1Introduction to the object model
Abstractions, classes and objects
Objects, reference values and reference variables
The new operator
Using objects
Object state
4.2Strings
Characters and strings
String concatenation
Creating string objects
String comparison
Converting primitive values to strings
Other useful methods for strings
4.3Manipulating references
Reference types and variables
Assignment to reference variables
Aliases: one object, several references
The null literal
Comparing objects
4.4Primitive values as objects
Auto-boxing
Auto-unboxing
Explicit boxing and unboxing
Useful methods in the wrapper classes
4.5Review questions
4.6Programming exercises
5More on control structures
5.1The extended assignment operators
5.2The increment and decrement operators
5.3Counter-controlled loops
Local variables in the for(;;) loop
Other increments in for(;;) loops
Counting backwards with for(;;) loops
Nested for(;;) loops
5.4Changing control flow in loops
The break statement
The continue statement
5.5Common pitfalls in loops
Infinite loop: for(;;)
One-off errors
Errors in initialization
Errors in the loop condition
Optimizing loops
5.6Multiple-selection statements
The default label
The case label values
Falling through case labels
5.7Review questions
5.8Programming exercises
6Arrays
6.1Arrays as data structures
6.2Creating and using arrays
Declaring array reference variables
Creating arrays
Default initialization
Arrays of objects
The length field
Accessing an array element
Array bounds
Array aliases
Alternate notation for array declaration
6.3Initializing arrays
6.4Iterating over an array
Comparing all values in an array with a given value
Finding the lowest value in an array
Finding the highest value in an array
Adding the values in an array
Iterating over an array of objects
6.5Multidimensional arrays
Creation and initialization of multidimensional arrays
Printing a two-dimensional array in tabular form
Iterating over a specific row in a two-dimensional array
Iterating over a specific column in a two-dimensional array
Iterating over all the columns in a two-dimensional array
Ragged arrays
Arrays with more than two dimensions
6.6More on iteration: enhanced for loop
6.7More miscellaneous operations on arrays
Copying arrays
Comparing arrays
Working with partially-filled arrays
6.8Pseudo-random number generator
The Random class
Determining the range
Simulating a dice roll
Generating the same sequence of pseudo-random numbers
6.9Review questions
6.10Programming exercises
7Defining classes
7.1Class members
7.2Defining object properties using field variables
Field declarations
Initializing fields
7.3Defining behaviour using instance methods
Method declaration and formal parameters
Method calls and actual parameter expressions
Parameter passing: call-by-value
The current object: this
Method execution and the return statement
Passing information using arrays
Automatic garbage collection
7.4Static members of a class
Accessing static members
Initializing static variables
The main() method and program arguments
7.5Initializing object state
Default constructors: implicit or explicit
Constructors with parameters
Overloading constructors
7.6Enumerated types
Simple form of enumerated types
Selected methods for enumerated types
General form of enumerated types
Declaring enumerated types inside a class
7.7Review questions
7.8Programming exercises
8Object communication
8.1Responsibilities and roles
A naive solution to a given problem
Combining properties and behaviour in classes
Using references as parameters
Advantages of good abstractions
Rethinking responsibility
8.2Communication and cooperation
Dividing and assigning responsibility
Clarifying the responsibilities of classes in the program
Communication between objects at runtime
Assigning the responsibility for calculating salaries
8.3Relationships between objects
Fields with reference values
Objects that communicate
Object ownership
One-to-one and one-to-many associations
Suggestions for further development
8.4Method overloading
8.5Documenting source code
Multi-line comments
Documenting classes and members
Hiding internal methods and fields
A fully-documented Java class
How to document programs
8.6Review questions
8.7Programming exercises
PART 3Useful Techniques for Building Programs
9Sorting and searching arrays
9.1Natural order
Relational operators for primitive data types
Understanding relational operators
9.2Selection sort
Sorting an array of integers
Pseudocode for the selection sort
Coding the selection sort
Analysing the amount of work required by a selection sort
9.3Insertion sort
Sorting an array of integers using an insertion sort
Pseudocode for the insertion sort
Coding the insertion sort
Analysing the amount of work required by an insertion sort
9.4Sorting arrays of objects
Comparing objects: the Comparable interface
Implementing the natural order for time objects
Sorting arrays of comparable objects
9.5Linear search
9.6Binary search
9.7Sorting and searching a CD collection
9.8Sorting and searching using the Java standard library
9.9Review questions
9.10Programming exercises
10Exception handling
10.1What is an exception?
10.2Method execution and exception propagation
Method execution
Stack trace
Exception propagation
10.3Exception handling
try-catch scenario 1: no exception
try-catch scenario 2: exception handling
try-catch scenario 3: exception propagation
10.4Checked exceptions
Dealing with checked exceptions using the throws clause
Programming with checked exceptions
10.5Unchecked exceptions
10.6Review questions
10.7Programming exercises
11Text file I/O and simple GUI dialogs
11.1File handling
Data records
11.2Text files
Writing to text files
Reading from text files
11.3Simple GUI dialogue design
Overview of the JOptionPane class
Message dialogs - presenting information to the user
Input dialogs - reading data from the user
Confirmation dialogs - getting confirmation from the user
11.4Review questions
11.5Programming exercises
PART 4Object-Oriented Programming (OOP)
12Inheritance
12.1Main concepts
Superclasses and subclasses
Specialization and generalization
Inheritance in Java
12.2Extending properties and behaviour
Initializing object state
Extending behaviour
12.3Using inherited members
Accessing inherited members in the subclass
Accessing inherited members using subclass references
Using superclass references to refer to subclass objects
Conversion between reference types
Using superclass and subclass references
12.4Extending behaviour in the subclass
Overriding instance methods in the subclass
Using an overridden method from the superclass
Using a shadowed field
12.5Final classes and methods
Final classes
Final methods
Overloading methods
12.6Review questions
12.7Programming exercises
13Polymorphism and interfaces
13.1Programming with inheritance
A superclass with multiple subclasses
Polymorphism and polymorphic references
Arrays of polymorphic references
Consequences of polymorphism
Inheritance is transitive
13.2Abstract classes
Abstract and concrete classes
Implementing abstract methods in subclasses
Abstract classes in the Java standard library
13.3Aggregation
13.4Interfaces in Java
The concept of contracts in programs
Declaring an interface
Implementing an interface
Implementing multiple interfaces
Inheritance between interfaces
Polymorphic use of interface references
13.5Review questions
13.6Programming exercises
PART 5Applying OOP
14Test-driven program development
14.1Developing large programs
14.2Simple testing with assert
The game board
Game board state
The state of several cells
Stacking pieces
Better error messages when tests fail
14.3Testing framework
JUnit framework
Writing test methods
Running tests with JUnit
Fixing test failures with JUnit
Full columns
14.4Printing the game board
Simulated game play
Method for printing game board
14.5Refactoring program code
14.6Interactive Four-in-a-Row game
Functional decomposition
Dropping the next piece (steps 3a and 3b)
A simplified end of game test (step 2)
14.7Ending a game
No winners
Four pieces in a row
14.8Machine-controlled player
The interface IPlayer and implementations
A game between arbitrary players
14.9Class libraries
Packages and the import statement
Static import
Declaring packages
Desigining frameworks
14.10Encapsulating implementation detail
Access modifiers for package members
Access modifiers for class members
Application programming interface (API)
Limiting access to fields
Tell - don't ask
14.11Base classes
Base classes in the game package
The package game.terminal
14.12Compiling and running code in packages
The package game.test
14.13Review questions
14.14Programming exercises
15Using dynamic data structures
15.1Overview
Abstract data types
Organizing and manipulating data
15.2Character sequences
Creating a character sequence
Modifying the contents of a StringBuilder
Other classes for handling character sequences
15.3Introduction to generic types
Declaring generic classes
Using generic classes
Generic interfaces
Handling of generic types at compile time
15.4Collections
Superinterface
Traversing a collection using an iterator
Traversing a collection using a for(:) loop
Default string representation of a collection
15.5Lists: ArrayList<E>
Subinterface List<E>
Using lists
15.6Sets: HashSet<E>
Interface Set<E>
Using sets
15.7Maps. HashMap<K,v>
Hashing
The Map<K,V> interface
Map views
Using maps
15.8More on generic types
Specifying subtypes: <? extends T>
Specifying supertypes: <? super T>
Specifying any type: <?>
Generic methods
15.9Sorting and searching methods from the Java API
15.10Review questions
15.11Programming exercises
16Implementing dynamic data structures
16.1Simple linked lists
Manipulating references in a linked list
Operations on linked lists
Inserting at the head of a linked list
Inserting at the tail of a linked list
Removing from the head of a linked list
Removing from the tail of a linked list
Removing a node from inside a linked list
Iterator for a linked list
Converting to an array
Remarks on linked lists
16.2Stacks and queues
Implementing a stack
Using stacks
Queues
Using queues
16.3Review questions
16.4Programming exercises
17Recursion
17.1Recursion and iteration
Factorials: an example from mathematics
Using recursive method calls
17.2Designing recursive algorithms
17.3Infinite recursion
17.4Recursive binary search
17.5Towers of Hanoi
Recursive solution
Iterative solution
17.6Quicksort: a recursive sorting algorithm
17.7Fibonacci series: an example of iterative solution
17.8Review questions
17.9Programming exercises
18More on exception handling
18.1Exception classes
The Exception class
The RuntimeException class
The Error class
18.2Throwing an exception programmatically
18.3Handling several types of exceptions
Typical programming errors in exception handling
18.4Defining new exceptions
18.5Using the finally block
18.6Review questions
18.7Programming exercises
19Files and streams
19.1Streams
Overview of byte streams
Overview of character streams
19.2Terminal window I/O
Writing to the terminal window
Reading from the keyboard
19.3Binary files
File path
Writing to binary files
Reading binary values
19.4Object serialization
Writing objects
Reading objects
Effective storing of objects
19.5Random access files
Overview of the class RandomAccessFile
Setting up random access
The file pointer
Reading and writing random access files
19.6Review questions
19.7Programming exercises
20Graphical user intefaces
20.1Building GUIs
Designing GUI-based dialogs
Delegating events
GUI building packages
Basics of GUI development
20.2Components and containers
Components
Containers
Windows and frames
Panels
Steps in developing a GUI
GUI and the main() method
20.3GUI control components
Text fields
Buttons
GUI design with panels
Using different types of buttons
20.4Designing layout
FlowLayout
BorderLayout
GridLayout
20.5Event-driven programming
Events
Event delegation model
Classes ActionEvent and WindowEvent
Programming paradigms for event handling
20.6Dialog boxes
Application using dialog boxes
Implementing a dialog box
20.7Anonymous classes as listeners
Creating and registering anonymous listener objects
Using anonymous listener objects
Some remarks on anonymous classes
20.8Programming model for GUI-based applications
20.9GUI for the Four-in-a-Row game
20.10Review questions
20.11Programming exercises
PART 6Appendices
AAnswers to review questions
A.1Getting started
A.2Basic programming elements
A.3Program control flow
A.4Using objects
A.5More on control structures
A.6Arrays
A.7Defining classes
A.8Object communication
A.9Sorting and searching arrays
A.10Exception handling
A.11Text file I/O and simple GUI dialogs
A.12Inheritance
A.13Polymorphism and interfaces
A.14Test-driven program development
A.15Using dynamic data structures
A.16Implementing dynamic data structures
A.17Recursion
A.18More on exception handling
A.19Files and streams
A.20Graphical user interfaces
BLanguage reference
B.1Reserved words
B.2Operators
B.3Primitive data types
B.4Java modifiers
CFormatted values
C.1Syntax for format strings
C.2Conversion codes and types
C.3Examples
DThe Unicode character set
D.1Excerpt from the Unicode character set
D.2Lexicographical order and alphabetical order
EConsole I/O and simple GUI dialog boxes
E.1Support for console I/O
E.2Support for simple GUI dialog boxes
FNumeral systems and representation
F.1Numeral systems
Decimal numeral system
Binary numeral system
Octal numeral system
Hexadecimal numeral system
F.2Conversions between numeral systems
F.3Conversions from decimal numeral system
F.4Integer representation
F.5String representation of integers
GProgramming tools in the JDK
G.1Programming tools
G.2Commands
Compiling source code: javac
Running the program: java
Generating documentation: javadoc
G.3Configuring the CLASSPATH
HIntroduction to UML
H.1Class diagram
H.2Object diagrams
H.3Sequence diagrams
H.4Activity diagrams
Index

Khalid A. Mughal
Torill Hamre
Rolf W. Rasmussen