Intro_Java_brief_Liang2011


Чтобы посмотреть этот PDF файл с форматированием и разметкой, скачайте его и откройте на своем компьютере.
INTRODUCTION TO
JAVA
PROGRAMMING
INTRODUCTION TO
JAVA
PROGRAMMING
Y.Daniel Liang
Armstrong Atlantic State University
Boston Columbus Indianapolis New York San Francisco Upper Saddle River
Amsterdam Cape Town Dubai London Madrid Milan Munich ParisMontreal Toronto
Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
Prentice Hall
Vice President and Editorial Director, ECS: Marcia J. Horton
Executive Editor: Tracy Dunkelberger
Vice President, Production: Vince OBrien
Production Editor: Irwin Zucker
Copyright 2011, 2009, 2007, 2004 by Pearson Higher Education. Upper Saddle River, New Jersey, 07458.
All right reserved. Manufactured in the United States of America. This publication is protected by Copyright and
This book is dedicated to Dr. S. K. Dhall and
Dr. S. Lakshmivarahan of the University of Oklahoma,
who inspired me in teaching and research. Thank you for being
my mentors and advisors.
To Samantha, Michael, and Michelle
PREFACE
This book is a brief version of
Introduction to Java Programming, Comprehensive Version,
. This version is designed for an introductory programming course, commonly known as
. This version contains the first twenty chapters in the comprehensive version.
This book uses the fundamentals-first approach and teaches programming concepts and
techniques in a problem-driven way.
The fundamentals-first approach introduces basic programming concepts and techniques
before objects and classes. My own experience, confirmed by the experiences of many col-
leagues, demonstrates that new programmers in order to succeed must learn basic logic and
fundamental programming techniques such as loops and stepwise refinement. The funda-
Preface
Exception handling is covered before abstract classes and interfaces. The instructor can
still choose to cover exception handling later.
Chapter 12, Object-Oriented Design and Patterns, in the previous edition has been
replaced by spreading the design guidelines and patterns into several chapters so that these
topics can be covered in appropriate context.
Learning Strategies
A programming course is quite different from other courses. In a programming course, you
learn from examples, from practice, and
from mistakes
. You need to devote a lot of time to
writing programs, testing them, and fixing errors.
For first-time programmers, learning Java is like learning any high-level programming lan-
guage. The fundamental point is to develop the critical skills of formulating programmatic
Preface
Provides additional information on the subject and reinforces important concepts.
Tip
Teaches good programming style and practice.
Helps students steer away from the pitfalls of programming errors.
Provides the guidelines for designing programs.
Flexible Chapter Orderings
The book is designed to provide flexible chapter orderings to enable GUI, exception handling,
and recursion to be covered earlier or later. The diagram shows the chapter dependencies.
Computers, Programs, and
Java
Programming
Polymorphism
Handling
and Interfaces
Arrays
Programming
Programming
User Interfaces
Organization of the Book
Preface
simple examples and exercises; subsequent chapters progressively present Java programming
Preface
The main features of the Automatic Grading System are as follows:
Preface
Video Notes
Web Chapters
To access the Video Notes and Web Chapters, students must log onto
www.pearsonhighered.com/liang
and use the access card located in the front of the book to register and access the material. If there is
no access card in the front of this textbook, students can purchase access by visiting
www.pearsonhighered.com/liang
purchase access to premium content
The text covers the essential subjects. The supplements extend the text to introduce addition-
al topics that might be of interest to readers. The supplements listed in this table are available
from the Companion Web site.
Supplements on the Companion Web site
Part I General Supplements
AGlossary
BInstalling and Configuring JDK
CCompiling and Running Java from the
Command Window
DJava Coding Style Guidelines
ECreating Desktop Shortcuts for Java
Applications on Windows
FUsing Packages to Organize the Classes
in the Text
Part II IDE Supplements
ATextPad Tutorial
Preface
Instructor Resource Materials
The instructor resources can be accessed through the Publishers Web site
www.pearsonhighered.com/liang
) and the Companion Web site (
www.cs.armstrong.edu/liang/intro8e
For username and password information to the Liang 8e site, please contact your Pearson
Representative.
PowerPoint lecture slides with source code and run program capacity
Sample exams using multiple choice and short answer questions, write and trace pro-
LiveLab
Video Notes
Web Chapters
To access the Video Notes and Web Chapters, instructors must log onto
www.pearsonhighered.com/liang
and register.
Acknowledgments
I would like to thank Armstrong Atlantic State University for enabling me to teach what I
write and for supporting me in writing what I teach. Teaching is the source of inspiration for
continuing to improve the book. I am grateful to the instructors and students who have offered
comments, suggestions, bug reports, and praise.
This book has been greatly enhanced thanks to outstanding reviews for this and previous
Preface
Y. Daniel Liang
y.daniel.liang@gmail.com
www.cs.armstrong.edu/liang
www.pearsonhighered.com/liang
Introduction to Computers,Programs,
and Java
Elementary Programming
Introduction to Computers,Programs,
and Java
1.1Introduction
1.2What Is a Computer?
1.3Programs
1.4Operating Systems
1.5Java, World Wide Web, and Beyond
1.6The Java Language Specification, API, JDK, and IDE
1.7A Simple Java Program
1.8Creating, Compiling, and Executing a Java Program
1.9(GUI) Displaying Text in a Message Dialog Box
Elementary Programming
2.1Introduction
2.2Writing Simple Programs
2.3Reading Input from the Console
2.4Identifiers
2.5Variables
2.6Assignment Statements and Assignment Expressions
2.7Named Constants
2.8Numeric Data Types and Operations
2.9Problem: Displaying the Current Time
2.10Shorthand Operators
2.11Numeric Type Conversions
2.12Problem: Computing Loan Payments
2.13Character Data Type and Operations
3.5Problem: Guessing Birthdays
3.6Two-Way
Statements
3.7Nested
Statements
3.8Common Errors in Selection Statements
3.9Problem: An Improved Math Learning Tool
3.10Problem: Computing Body Mass Index
3.11Problem: Computing Taxes
3.12Logical Operators
Single-Dimensional Arrays
6.1Introduction
6.2Array Basics
6.3Problem: Lotto Numbers
6.4Problem: Deck of Cards
6.5Copying Arrays
9.4The
9.5Command-Line Arguments
9.6The
9.7File Input and Output
9.8(GUI) File Dialogs
Thinking in Objects
10.1Introduction
10.2Immutable Objects and Classes
10.3The Scope of Variables
10.4The
Reference
10.5Class Abstraction and Encapsulation
10.6Object-Oriented Thinking
10.7Object Composition
10.8Designing the
10.9Designing a Class for Stacks
10.10Designing the
10.11Class Design Guidelines
Inheritance and Polymorphism
11.1Introduction
11.2Superclasses and Subclasses
11.3Using the
Keyword
12.6Using Panels as Subcontainers
12.7The
12.8The
12.9Common Features of Swing GUI Components
12.10Image Icons
13.1Introduction
13.2Exception-Handling Overview
13.3Exception-Handling Advantages
13.4Exception Types
13.5More on Exception Handling
13.6The
13.7When to Use Exceptions
15.7Drawing Polygons and Polylines
15.8Centering a String Using the
INTRODUCTION TO
JAVA
PROGRAMMING
NTRODUCTIONTO
ROGRAMS
AVA
Objectives
To review computer basics, programs, and operating systems (1.21.4).
Chapter 1Introduction to Computers, Programs, and Java
1.1Introduction
e.g., Disk, CD,
and Tape
e.g., Modem
and NIC
e.g., Keyboard,
Mouse
e.g., Monitor,
Printer
CPU
Bus
Devices
Devices
Devices
Devices
A computer consists of CPU, memory, storage devices, input devices, output
devices, and communication devices.
1.2What Is a Computer?
multiplication, division) and logical operations (comparisons).
Todays CPU is built on a small silicon semiconductor chip having millions of transistors.
Every computer has an internal clock, which emits electronic pulses at a constant rate. These
the more instructions are executed in a given period of time. The unit of measurement of clock
speedis the
puter is usually stated in megahertz(MHz) (1 MHz is 1 million Hz). CPU speed has been
improved continuously. Intels Pentium 3 Processor runs at about 500 megahertz and Pentium
4 Processor at about 3 gigahertz(GHz) (1 GHz is 1000 MHz).
1.2.2Memory
To store and process information, computers use
off
convention as
Memory addressMemory content
1.2
megabyte
Chapter 1Introduction to Computers, Programs, and Java
1.2.3Storage Devices
Memory is volatile, because information is lost when the power is turned off. Programs and
data are permanently stored on storage devicesand are moved, when the computer actually
uses them, to memory, which is much faster than storage devices.
There are four main types of storage devices:
Disk drives
CD drives (CD-R, CD-RW, and DVD)
Tape drives
USB flash drives
are devices for operating a medium, such as disks, CDs, and tapes.
Disks
Each computer has at least one hard drive.
Hard disks
programs. The hard disks of the latest PCs store from 80 to 250 gigabytes. Often disk drives
are encased inside the computer. Removable hard disks are also available.
CDs and DVDs
CD stands for compact disk. There are two types of CD drives: CD-R and CD-RW. A
for read-only permanent storage; the user cannot modify its contents once they are recorded.
CD-RW
can be used like a hard disk and can be both read and rewritten. A single CD can
hold up to 700 MB. Most software is distributed through CD-ROMs. Most new PCs are
equipped with a CD-RW drive that can work with both CD-R and CD-RW.
DVD stands for digital versatile disc or digital video disk. DVDs and CDs look alike, and
you can use either to store data. A DVD can hold more information than a CD. A standard
DVDs storage capacity is 4.7 GB.
Tapes
Tapes
are mainly used for backup of data and programs. Unlike disks and CDs, tapes store
1.3Programs
numeric keypad,
Chapter 1Introduction to Computers, Programs, and Java
Assembly languages were developed to make programming easy. However, since the com-
is used to convert
assembly-language programs into machine code, as shown in Figure 1.3.
be executed only on a particular kind of machine. The high-level languages were developed in
order to transcend platform specificity and make programming easier.
high-level languages
are English-like and easy to learn and program. Here, for exam-
ple, is a high-level language statement that computes the area of a circle with radius 5:
Among the more than one hundred high-level languages, the following are well known:
FORTRAN (FORmula TRANslation)
BASIC (Beginners All-purpose Symbolic Instruction Code)
Pascal (named for Blaise Pascal)
Ada (named for Ada Lovelace)
C (developed by the designer of B)
Visual Basic (Basic-like visual language developed by Microsoft)
Delphi (Pascal-like visual language developed by Borland)
C# (a Java-like language developed by Microsoft)
Each of these languages was designed for a specific purpose. COBOL was designed for busi-
ness applications and is used primarily for business data processing. FORTRAN was
BASIC was designed to be learned and used easily. Ada was developed for the Department
of Defense and is used mainly in defense projects. C combines the power of an assembly lan-
guage with the ease of use and portability of a high-level language. Visual Basic and Delphi
are used in developing graphical user interfaces and in rapid application development. C++
is popular for system software projects such as writing compilers and operating systems. The
Microsoft Windows operating system was coded using C++. C# (pronounced C sharp) is a
new language developed by Microsoft for developing applications based on the Microsoft
Java
high-level language
..
ADDF3 R1, R2, R3
..
Machine-Code File
..
1101101010011010
..
1.3
1.4Operating Systems
A program written in a high-level language is called a
source program
source code
translate it into a machine-language program. The machine-language program is then linked
with other supporting library code to form an executable file, which can be run on the
machine, as shown in Figure 1.4. On Windows, executable files have extension .exe.
1.4Operating Systems
operating system
) is the most important program that runs on a computer, which
manages and controls a computers activities. The popular operating systems are Microsoft
Windows, Mac OS, and Linux. Application programs, such as a Web browser or a word
processor, cannot run without an operating system. The interrelationship of hardware, operat-
ing system, application software, and the user is shown in Figure 1.5.
Controlling and monitoring system activities
1.4.1Controlling and Monitoring System Activities
Operating systems perform basic tasks, such as recognizing input from the keyboard, sending
output to the monitor, keeping track of files and directories on the disk, and controlling
peripheral devices, such as disk drives and printers. They also make sure that different pro-
grams and users running at the same time do not interfere with each other, and they are
responsible for security, ensuring that unauthorized users do not access the system.
File
File
1.4
A source program is compiled into a machine-language file, which is then
linked with the system library to form an executable file.
1.5
The operating system is the software that controls and manages the system.
Chapter 1Introduction to Computers, Programs, and Java
1.4.2Allocating and Assigning System Resources
same time. For example, a word-processing program allows users to simultaneously edit text
and save it to a file. In this example, editing and saving are two tasks within the same applica-
tion. These two tasks may run on separate threads concurrently.
Multiprocessing
1.5Java, World Wide Web, and Beyond
text fields, text areas, radio buttons, and so on, to interact with users on the Web and process
1.6
1.7
Java was used to develop an automatic grading system to accompany this book.
Chapter 1Introduction to Computers, Programs, and Java
Java is a versatile programming language. You can use it to develop applications on
your desktop and on the server. You can also use it to develop applications for small hand-
held devices. Figure 1.8shows a Java-programmed calendar displayed on a BlackBerry
1.6The Java Language Specification, API, JDK, and IDE
Computer languages have strict rules of usage. If you do not follow the rules when writing a
program, the computer will be unable to understand it. The Java language specification and
Java API define the Java standard.
Java language specification
is a technical definition of the language that includes the
1.8
Java can be used to develop applications for hand-held and wireless devices,
such as a BlackBerry(left) and a cell phone (right).
Java IDE
1.7A Simple Java Program
online help are integrated in one graphical user interface. Just enter source code in one window
or open an existing file in a window, then click a button, menu item, or function key to compile
1.7A Simple Java Program
line numbers
are displayed for reference purposes but are not part of the program. So,
dont type line numbers in your program.
Line 1 defines a class. Every Java program must have at least one class. Each class has a
Video Note
First Java program
Chapter 1Introduction to Computers, Programs, and Java
block
syntax rules
Welcome {
public static void
main(String[] args) {
System.out.println(
"Welcome to Java!"
);
}
Further, you can perform mathematical computations and display the result to the console.
Listing 1.3 gives an example of evaluating
case sensitive
1.8Creating, Compiling, and Executing a Java Program
The multiplication operator in Java is
. As you see, it is a straightforward process to trans-
Result
Compile Source Code
e.g.,
javac Welcome.java
Saved on the disk
If compilation errors
If runtime errors or incorrect result
Source code (developed by the programmer)
Bytecode (generated by the compiler for JVM
Welcome to Java!
1.9
The Java program-development process consists of repeatedly creating/modifying source code, compiling,
and executing programs.
1.3
Chapter 1Introduction to Computers, Programs, and Java
You can use any text
or IDE to create and edit a Java source-code file. This section
demonstrates how to create, compile, and run Java programs from a command window. If you
file name
.class bytecode file
1.10
You can create the Java source file using Windows NotePad.
Computer
(Java source
code file)
(Java bytecode
executable file)
Compiler
compiled
by
by
(a)(b)
1.11
(a) Java source code is translated into bytecode. (b) Java bytecode can be executed on any computer with a
Java Virtual Machine.
Video Note
Brief Eclipse Tutorial
1.8Creating, Compiling, and Executing a Java Program
To execute a Java program is to run the programs bytecode. You can execute the bytecode
1.12
The output of Listing 1.1 displays the message Welcome to Java!
Video Note
Compile and run a Java program
Chapter 1Introduction to Computers, Programs, and Java
Pedagogical Note
Instructors may require students to use packages for organizing programs. For example, you may
place all programs in this chapter in a package named
chapter1
. For instructions on how to use
packages, please see Supplement I.F, Using Packagesto Organize the Classes in the Text.
1.9(GUI) Displaying Text in a Message Dialog Box
The program in Listing 1.1 displays the text on the console, as shown in Figure 1.12. You can
rewrite the program to display the text in a message dialog box. To do so, you need to use the
1.4
)8// Display Welcome to Java! in a message dialog box910 }11 }This program uses a Java class
(line 9). Javas predefined classes are grouped
If you replace
, you dont need to
import it in line 4.
is the full name for the
javax.swing.JOptionPane;
1.13
Welcome to Java! is displayed in a message box.
null
,
"Welcome to Java!"
);
Key Terms
The first argument can always be
is a Java keyword that will be fully intro-
duced in Chapter 8, Objects and Classes. The second argument is a string for text to be
There are several ways to use the
two versions of
specific import
no performance difference
.class file14
.java file14
assembly language5
bit3
block12
block comment11
bus2
byte3
bytecode14
bytecode verifier15
cable modem5
central processing unit (CPU)2
class loader15
comment11
null
,
"Welcome to Java!"
,
"Display Message"
,
JOptionPane.INFORMATION_MESSAGE);
There are two types of
statements:
specific import
wildcard import
specific
import
specifies a single class in the import statement. For example, the following statement
imports
from package
wildcard import
imports all the classes in a package. For example, the following statement
imports all classes from package
The information for the classes in an imported package is not read in at compile time or runtime
unless the class is used in the program. The import statement simply tells the compiler where to
locate the classes. There is no performance differencebetween a specific import and a wildcard
import declaration.
Recall that you have used the
class in the statement
in Listing 1.1. The
class is not imported because it is in the
package. All the classes in the
package are
imported in every Java program.
Chapter 1Introduction to Computers, Programs, and Java
compiler7
console11
dot pitch5
DSL (digital subscriber line)5
hardware2
high-level language6
Integrated Development Environment
(IDE)10
java
command15
javac
command15
Java Development Toolkit (JDK)10
Java Virtual Machine (JVM)14
keyword (or reserved word)11
line comment11
machine language5
UMMARY
A computer is an electronic device that stores and processes data.
hardware
software
Hardware is the physical aspect of the computer that can be seen.
programs
, known as
software
, are the invisible instructions that control the
hardware and make it perform tasks.
Chapter Summary
Programs and data are permanently stored on storage devices and are moved to mem-
Chapter 1Introduction to Computers, Programs, and Java
UESTIONS
Answers to review questions are on the Companion Website.
Sections 1.21.4
Define hardware and software.
1.2
List the main components of the computer.
1.3
Define machine language, assembly language, and high-level programming
1.4
1.5
1.6
Sections 1.51.6
1.7
Describe the history of Java. Can Java run on any machine? What is needed to run
Java on a computer?
1.8
What are the input and output of a Java compiler?
1.9
Programming Exercises
1.18
What is the command to compile a Java program? What is the command to run a
Java program?
1.19
1.20
ROGRAMMING
Solutions to even-numbered exercises are on the Companion Website. Solutions to all exer-
cises are on the Instructor Resource Website. The level of difficultyis rated easy (no star),
moderate (*), hard (**), or challenging (***).
Displaying three messages
1.2
Displaying five messages
five
1.3*
) Write a program that displays the following pattern:
1.4
) Write a program that displays the following table:
1.5
Computing expressions
level of difficulty
Chapter 1Introduction to Computers, Programs, and Java
1.6
1.7
Approximating
) can be computed using the following formula:
-
1
+
1
b
.
4
*
a
1
-
1
+
1
-
1
+
=
4
*
a
1
-
1
+
1
-
1
+
1
-
1
+
1
+

b
p
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
LEMENTARY
ROGRAMMING
Objectives
To write Java programs to perform simple calculations (2.2).
To obtain input from the console using the
dialog boxes (2.18).
Chapter 2Elementary Programming
2.1Introduction
In Chapter 1 you learned how to create, compile, and run a Java program. Now you will learn
how to solve practical problems programmatically. Through these problems, you will learn ele-
mentary programming using primitive data types, variables, constants, operators, expressions,
2.2Writing Simple Programs
2.2Writing Simple Programs
as variable names, choose descriptive names: in this case,
2.1
Chapter 2Elementary Programming
Variables such as
correspond to memory locations. Every variable has a
name, a type, a size, and a value. Line 3 declares that
value. The
value is not defined until you assign a value. Line 7 assigns
. Similarly, line 4
declares variable
, and line 10 assigns a value into
. The following table shows the
value in the memory for
as the program is executed. Each row in the table
shows the values of variables after the statement in the corresponding line in the program is
executed. Hand trace is helpful to understand how a program works, and it is also a useful tool
for finding errors in the program.
) has two meanings: one for addition and the other for concatenating
string concatenation operator
two strings if two operands are strings. If one of the operands is a nonstring (e.g., a number),
the nonstring value is converted into a string and concatenated with the other string. So the
Type.
A string constant cannot cross lines in the source code. Thus the following statement would
result in a compile error:
To fix the error, break the string into separate substrings, and use the concatenation operator (
Tip
This example consists of three steps. It is a good approach to develop and test these steps
incrementallyby adding them one at a time.
2.3Reading Input from the Console
In Listing 2.1, the radius is fixed in the source code. To use a different radius, you have to
modify the source code and recompile it. Obviously, this is not convenient. You can use the
Java uses
to refer to the standard output device and
dard input device. By default the output device is the display monitor, and the input device is
declaring variable
assign value
incremental development and
line#radiusarea
3no value
4no value
720
101256.636
Video Note
Obtain input
2.3Reading Input from the Console
the keyboard. To perform console output, you simply use the
2.1
reads an integer of the
reads an integer of the
reads an integer of the
reads an integer of the
reads a string that ends before a whitespace character.
reads a line of text (i.e., a string ending with the
key pressed).
For now, we will see how to read a number that includes a decimal point by invoking the
java.util.Scanner;
Chapter 2Elementary Programming
System.out.(
Listing 2.3 gives another example of reading input from the keyboard. The example reads
three numbers and displays their average.
)5// Create a Scanner object678// Prompt the user to enter three numbers9 System.out.print("Enter three numbers: ");10doublenumber1 =;
number2 = ;
number3 = ;
java.util.Scanner;
one line
enter input in
multiple lines
2.5Variables
the same as in the preceding example as well as in all new programs you will write.
Line 9 prompts the user to enter three numbers. The numbers are read in lines 1012. You
key,or enter each number
followed by a press of the
key, as shown in the sample runs of this program.
2.4Identifiers
identifiers
. All identifiers must obey the following rules:
identifier naming rules
case sensitive
descriptive names
why called variables?
Chapter 2Elementary Programming
Variables are for representing data of a certain type. To use a variable, you declare it by telling
variable declaration
the compiler to allocate appropriate memory space for the variable based on its data type. The
syntax for declaring a variable is
Here are some examples of variable declarations:
The examples use the data types
declaring variables
naming variables
initializing variables
2.7Named Constants
expression
represents a computation involving values, variables, and operators that,
expression
assignment expression
Chapter 2Elementary Programming
Numeric Data Types
Range
Storage Size
2
1
-
2
1
-
2
1
-
(i.e.,
-
2
Negative range:to
Positive range:1.4E45 to
45
Negative range:to
Positive range:to
A constant must be declared and initialized in the same statement. The word
Java keyword for declaring a constant. For example, you can declare as a constant and
rewrite Listing 2.1 as follows:
)// Declare a constant// Assign a radiusdoubleradius = 20;// Compute areadoublearea = radius * radius * ;
By convention, constants are named in uppercase:
, not
There are three benefits of using constants: (1) you dont have to repeatedly type the same value;
(2) if you have to change the constant value (e.g., from
for
), you need to
change it only in a single location in the source code; (3) a descriptive name for a constant makes
the program easy to read.
2.8Numeric Data Types and Operations
Every data type has a range of values. The compiler allocates memory space for each variable
or constant according to its data type. Java provides eight primitive data types for numeric val-
ues, characters, and Boolean values. This section introduces numeric data types.
Table 2.2lists the six numeric data types, their ranges, and their storage sizes.
benefits of constants
2.8Numeric Data Types and Operations
is a standard approved by the Institute of Electrical and Electronics Engineers for represent-
ing floating-point numbers on computers. The standard has been widely adopted. Java has adopted
for the
for the
standard also defines special values as given in Appendix E, Special Floating-Point Values.
Java uses four types for integers:
appropriate for your variable. For example, if you know an integer stored in a variable is
within a range of byte, declare the variable as a
. For simplicity and consistency, we will
for integers most of the time in this book.
Java uses two types for floating-point numbers:
is known as
double precision
single precision
When a variable is assigned a value that is too large (
) to be stored, it causes
overflow
. For
example, executing the following statement causes
overflow
, because the largest value that can
be stored in a variable of the
typeis
is too large.
Likewise, executing the following statement causes
overflow
be stored in a variable of the
is too large in size to
be stored in an
Java does not report warnings or errors on overflow. So be careful when working with numbers
close to the maximum or minimum range of a given type.
When a floating-point number is too small (i.e., too close to zero) to be stored, it causes
underflow
. Java approximates it to zero. So normally you should not be concerned with underflow.
2.8.1Numeric Operators
), division (
), as shown in Table 2.3.
When both operands of a division are integers, the result of the division is an integer. The
fractional part is truncated. For example,
5/ 2
. To perform regular mathematical division, one of the operands must be a floating-point
number. For example,
operator yields the remainder after division. The left-hand operand is the dividend
and the right-hand operand the divisor. Therefore,
what is overflow?
what is underflow?
integer types
Numeric Operators
+
1
34.00.1
*
30
Division
integer division
Chapter 2Elementary Programming
line#secondsminutesremainingSeconds
8500
108
1120
read an integer
divide
away the minutes.
Divisor
2
412
826
1320
operator is often used for positive integers but can be used also with negative integers
and floating-point values. The remainder is negative only if the dividend is negative. For example,
Remainder is very useful in programming. For example, an even number
is always
is always
After 10 days
Day 2 in a week is Tuesday
A week has 7 days
Day 6 in a week is Saturday
Listing 2.4 gives a program that obtains minutes and remaining seconds from an amount of
time in seconds. For example,
)56// Prompt the user for input7 System.out.print("Enter an integer for seconds: ");8intseconds = ;
minutes = ;
remainingSeconds = ;
java.util.Scanner;
2.8Numeric Data Types and Operations
octal and hex literals
suffix d or D
suffix f or F
operators can be both unary and binary. A
operator has two. For example, the
to negate number
Calculations involving floating-point numbers are approximated because these numbers are not
stored with complete accuracy. For example,
displays
, not
displays
, not
. Integers are stored precisely. Therefore, calcula-
tions with integers yield a precise integer result.
2.8.2Numeric Literals
literal
is a constant value that appears directly in a program. For example,
are literals in the following statements:
Integer Literals
An integer literal can be assigned to an integer variable as long as it can fit into the variable.
A compile error will occur if the literal is too large for the variable to hold. The statement
, for example, will cause a compile error, because 128 cannot be stored in a
variable of the
type. (Note that the range for a byte value is from to 127.)
An integer literal is assumed to be of the
1
1
.
-
2
1
-
-
Chapter 2Elementary Programming
displays
displays
Scientific Notation
Floating-point literals can also be specified in scientific notation; for example,
, is equivalent to and
equivalent to
) represents an exponent and can be in
either lowercase or uppercase.
types are used to represent numbers with a decimal point. Why are
they called
floating-point numbers
? These numbers are stored in scientific notation. When a
number such as
is converted into scientific notation, such as
point is moved (i.e., floated) to a new position.
2.8.3Evaluating Java Expressions
last. If an expression contains several addition and subtraction operators, they are applied
from left to right. Here is an example of how an expression is evaluated:
-
10
1
y
-
5
+
b
+
c
2
+
9
a
4
+
9
+
x
b
evaluating an expression
+
4
*
4
+
5
* (
4
+
3
) -
1
3
+
4
*
4
+
5
*
7

1
3
+
16
+
5
*
7

1
3
+
16
+
35

1
19
+
35

1
54 1
(1) inside parentheses first
2.9Problem: Displaying the Current Time
divide
Listing 2.5 gives a program that converts a Fahrenheit degree to Celsius using the formula
)5 Scanner input = newScanner(System.in);67 System.out.print("Enter a degree in Fahrenheit: ");8doublefahrenheit = input.nextDouble(); 910// Convert Fahrenheit to Celsius11doublecelsius = * (fahrenheit -
9
)
32
2
.
line#fahrenheit
8100
1137.77777777777778
Be careful when applying division. Division of two integers yields an integer in Java. is trans-
5.0/9
in Java.
2.9Problem: Displaying the Current Time
The problem is to develop a program that displays the current time in GMT (Greenwich Mean
Time) in the format hour:minute:second, such as 13:19:8.
currentTimeMillis
Video Note
Use operators / and %
01-01-1970
00:00:00 GMT
Elapsed
time
Current Time
System.currentTimeMillis()
Time
minute, and hour as follows.
Chapter 2Elementary Programming
1.Obtain the total milliseconds since midnight, Jan 1, 1970, in
invoking
2.Obtain the total seconds
by dividing
10001203183086
3.Compute the current second from
6026
4.Obtain the total minutes
by dividing
6020053051
5.Compute the current minute from
6031
6.Obtain the total hours
by dividing
60334217
7.Compute the current hour from
2417
8
10
);
11
// Obtain the total minutes
13
// Compute the current minute in the hour
16
// Obtain the total hours
19
// Compute the current hour
22
// Display results
25 System.out.println(
"Current time is "
+ currentHour +
" GMT"
=
=
=
=
=
2.10Shorthand Operators
variables
471013161922
totalMilliseconds1203183086328
totalSeconds1203183086
currentSecond26
totalMinutes20053051
currentMinute31
totalHours334217
currentHour
Shorthand Operators
Operator
Division assignment
Chapter 2Elementary Programming
Increment and Decrement Operators
Operator
use the new
value
// j is 2,
// i is 2
, but
value
// j is 1,
// i is 2
use the new
value
// j is 0,
// i is 0
value
// j is 1,
// i is 0
There are no spaces in the shorthand operators. For example,
Like the assignment operator (
), the operators (
) can be used to form an
assignment statement as well as an expression. For example, in the following code,
statement in the first line and an expression in the second line.
System.out.println();
There are two more shorthand operators for incrementing and decrementing a variable by
These are handy, because thats often how much the value needs to be changed. The two opera-
. For example, the following code increments
operators can be used in prefix or suffix mode, as shown in Table 2.5.
before
(prefixed to) the variable, the variable is incremented or decremented
new
int
i =
10
;
int
newNum =
10
* (
++i
);
1
;
int
newNum =
10
* i;
int
i =
10
;
int
newNum =
10
*
i++
;
newNum =
10
* i;
i = i +
1
;
value of
2.11Numeric Type Conversions
, and the new value of
narrowing a type
Chapter 2Elementary Programming
line#purchaseAmounttaxoutput
8197.55
1011.853
1111.85
Casting does not change the variable being cast. For example,
is not changed after casting in
the following code:
Toassign a variable of the
type, explicit casting
must be used. For example, the following statements have a compile error:
However, so long as the integer literal is within the permissible range of the target variable,
explicit casting is not needed to assign an integer literal to a variable of the
Please refer to 2.8.2, Numeric Literals.
Listing 2.7 gives a program that displays the sales tax with two digits after the decimal point.
) /
100.0
Variable
is evaluated as
with two digits after the decimal point.
2.12Problem: Computing Loan Payments
3.Compute the monthly payment using the preceding formula.
4.Compute the total payment, which is the monthly payment multiplied by
5.Display the monthly payment and total payment.
13
double
monthlyInterestRate = annualInterestRate /
// Enter number of years
16 System.out.print(
"Enter number of years as an integer, for example 5: "
// Enter loan amount
21 System.out.print(
"Enter loan amount, for example 120000.95: "
annualInterestRate = input.nextDouble();
java.util.Scanner;
1
+
12
1
1
+
12

-
1
1
+
12
Video Note
Program computations
Chapter 2Elementary Programming
Line 10 reads the yearly interest rate, which is converted into monthly interest rate in line
13. If you entered an input other than a numeric value, a runtime error would occur.
Choose the most appropriate data type for the variable. For example,
. For simplicity, however,
the examples in this book will use
for integer and
for floating-point values.
The formula for computing the monthly payment is translated into Java code in lines 2527.
Casting is used in lines 31 and 33 to obtain a new
with two digits after the decimal point.
why isnt it imported? The
package are implicitly imported. So, there is no need to explicitly import the
2.13Character Data Type and Operations
, is used to represent a single character. A character literal is
enclosed in single quotation marks. Consider the following code:
loanAmount = input.nextDouble();
variables
101318222527
annualInterestRate5.75
monthlyInterestRate0.0047916666666
numberOfYears15
loanAmount250000
monthlyPayment2076.0252175
totalPayment373684.539
2.13Character Data Type and Operations
The first statement assigns character
variable
import
javax.swing.JOptionPane;
2
public class
DisplayUnicode {
4
public static void
main(String[] args) {
5 JOptionPane.showMessageDialog(
null
,
6
"\u6B22\u8FCE \u03b1 \u03b2 \u03b3"
,
7
"\u6B22\u8FCE Welcome"
Chapter 2Elementary Programming
Java Escape Sequences
Character Escape Sequence
Tab
Formfeed
The increment and decrement operators can also be used on
variables to get the next or
preceding Unicode character. For example, the following statements display character
2.13.2Escape Sequences for Special Characters
Suppose you want to print a message with quotation marks in the output. Can you write a
statement like this?
No, this statement has a syntax error. The compiler thinks the second quotation character is
the end of the string and does not know what to do with the rest of characters.
Toovercome this problem, Java defines escape sequences to represent special characters,
as shown in Table 2.6. An escape sequence begins with the backslashcharacter (
) followed
by a character that has a special meaning to the compiler.
So, now you can print the quoted message using the following statement:
2.14Problem: Counting Monetary Units
is cast into a numeric type, the characters Unicode is cast into the specified
Chapter 2Elementary Programming
Here are the steps in developing the program:
1.Prompt the user to enter the amount as a decimal number, such as
2.Convert the amount (e.g.,
3.Divide the cents by
to find the number of dollars. Obtain the remaining cents using
4.Divide the remaining cents by
to find the number of quarters. Obtain the remaining
5.Divide the remaining cents by
to find the number of dimes. Obtain the remaining
6.Divide the remaining cents by
to find the number of nickels. Obtain the remaining
7.The remaining cents are the pennies.
8.Display the result.
;
nickels
2.14Problem: Counting Monetary Units
variables
1113161720212425282932
Amount11.56
remainingAmount115656661
numberOfOneDollars11
numberOfQuarters2
numberOfDimes0
numberOfNickles1
numberOfPennies
" dollars\n"
" quarters\n"
" dimes\n"
" nickels\n"
" pennies"
11 dollars
The variable
stores the amount entered from the console (line 11). This variable is
results. The program introduces the variable
The variable
decimal representing dollars and cents. It is converted to
variable
, which represents all the cents. For instance, if
. The division operator yields the inte-
ger part of the division. So
1156/100
of the division. So
1156%100
The program extracts the maximum number of singles from the total amount and obtains the
remaining amount in the variable
(lines 1617). It then extracts the maxi-
and obtains a new
(lines 2021). Continuing the same process, the program finds the maximum number of dimes,
nickels, and pennies in the remaining amount.
One serious problem with this example is the possible loss of precision when casting a
intremainingAmount
. You will find
pennies. To fix the problem, enter the amount as an
integer value representing cents (see Exercise 2.9).
Chapter 2Elementary Programming
As shown in the sample run,
nickels, and
numbers
reading strings
2.16Programming Style and Documentation
"s1 is "
+ s1);
System.out.println(
"s2 is "
+ s2);
System.out.println(
"s3 is "
+ s3);
To
avoid input errors
, do not use
. The reasons will be explained in
9.7.3, How Does
Work?
2.16Programming Style and Documentation
Programming style
deals with what programs look like. A program can compile and run prop-
erly even if written on only one line, but writing it all on one line would be bad programming
style because it would be hard to read.
is the body of explanatory remarks and
and make programs easy to read. So far you have learned some good programming styles.
avoiding input errors
javadoc comment
Chapter 2Elementary Programming
Use javadoc comments (
/**...*/
naming variables and
i=
3
+
4
*
4
;
i =
3
+
4
*
4
;
A single space line should be used to separate segments of the code to make the program
2.16.4Block Styles
A block is a group of statements surrounded by braces. There are two popular styles,
next-line
style, as shown below.
2.17Programming Errors
The next-line style aligns braces vertically and makes programs easy to read, whereas the
end-of-line style saves space and may help avoid some subtle programming errors. Both are
acceptable block styles. The choice depends on personal or organizational preference. You
should use a block style consistently. Mixing styles is not recommended. This book uses the
style to be consistent with the Java API source code.
2.17Programming Errors
Programming errors are unavoidable, even for experienced programmers. Errors can be cate-
2.17.1Syntax Errors
syntax errors
compile errors
result from errors in code construction, such as mistyping a keyword, omitting some necessary
30
Test
{
public static void
main(String[] args)
{
"Block Styles"
);
}
public class
Test {
public static void
main(String[] args) {
System.out.println(
"Block Styles"
);
}
Next-line style
End-of-line style
Chapter 2Elementary Programming
The runtime error causes the program to terminate abnormally.
2.17.2Runtime Errors
Runtime errors
are errors that cause a program to terminate abnormally. They occur while a
/
0
2.18(GUI) Getting Input from Input Dialogs
Cancel
to dismiss the
dialog without input
String input =
JOptionPane.showInputDialog(
);
Click
OK
to accept
input and dismiss the
bugs
. The process of finding and correcting errors is called
debugging
box by invoking the
null
,
"Enter an input"
,
"Input Dialog Demo"
,
JOptionPane.QUESTION_MESSAGE);
Chapter 2Elementary Programming
(c)
(b)
2.18.1Converting Strings to Numbers
Toconvert a string into an
value, use the
Key Terms
, whichever is convenient. For con-
sistency most examples in this book use
for getting input. You can easily revise the
examples using
for getting input.
+ totalPayment;
"The monthly payment is "
+ monthlyPayment +
) /
100
0
;
) /
100
0
;
totalPayment = monthlyPayment * numberOfYears *
1
));
algorithm24
)30
assignment statement30
)46
type27
casting41
type44
constant31
data type25
debugger55
debugging55
declaration30
)41
type33
encoding45
Chapter 2Elementary Programming
type35
floating-point number33
expression31
identifier29
)41
incremental development and testing26
indentation52
type34
literal35
logic error54
type35
narrowing (of types)41
operator33
overflow33
pseudocode30
primitive data type25
runtime error54
type27
syntax error53
supplementary Unicode45
underflow33
Unicode45
Unix epoch43
variable24
widening (of types)41
whitespace51
UMMARY
Identifiers are names for things in a program.
Chapter Summary
Java provides two floating-point types (
numbers of two different precisions.
17.
Java provides operators that perform numeric operations:
(division), and
(division assignment), and
21.
a variable by
When evaluating an expression with values of mixed types, Java automatically con-
verts the operands to appropriate types.
You can explicitly convert a value from one type to another using the
Casting a variable of a type with a small range to a variable of a type with a larger
range is known as
Casting a variable of a type with a large range to a variable of a type with a smaller
range is known as
narrowing a type
Widening a type can be performed automatically without explicit casting. Narrowing
a type must be performed explicitly.
27.
) represents a single character.
is called the escape character.
Java allows you to use escape sequences to represent special characters such as
are known as the whitespace char-
31.
In computer science, midnight of January 1, 1970, is known as the
Unix epoch.
Programming errors can be categorized into three types: syntax errors, runtime
syntax errors
compile errors.
Runtime errors
are errors that cause a program to terminate abnormally.
Logic errors
occur when a program does not perform the way it was intended to.
Chapter 2Elementary Programming
UESTIONS
2.1
Which of the following identifiers are valid? Which are Java keywords?
1
r
+
-
9
1
a
+
+
3
+
d
1
2
+
a
2
+
Review Questions
2.11
are integers. Write a Java expression for
2.12
(a)Any expression can be used as a statement.
(b)The expression
(c)The statement
is also an expression.
(d)The statement
is illegal.
2.13
Which of the following are correct literals for floating-point numbers?
2.14
Identify and fix the errors in the following code:
)3int i;4intk = 100.0;5intj = i + 1;67 System.out.println("j is "+ j + " and8k is "+ k);9 }10 }2.15
How do you obtain the current minute using the
Chapter 2Elementary Programming
Can the following conversions involving casting be allowed? If so, find the con-
verted result.
Show the output of the following program:
)charx = 'a';chary = 'c';System.out.println(++x);System.out.println(y++);System.out.println(x - y);}}Section 2.15
Show the output of the following statements (write a program to verify your result):
Evaluate the following expressions (write a program to verify your result):
Sections 2.162.17
Programming Exercises
Section 2.18
Why do you have to import
but not the
How do you prompt the user to enter an input using a dialog box?
How do you convert a string to an integer? How do you convert a string to a double?
ROGRAMMING
Students can run all exercises by downloading
from
to run Exercise
. For example, to run Exer-
cise2_1, use
This will give you an idea how the program runs.
Debugging TIP
The compiler usually gives a reason for a syntax error. If you dont know how to correct it,
compare your program closely, character by character, with similar examples in the text.
2.1
Converting Celsius to Fahrenheit
) Write a program that reads a Celsius degree in
double from the console, then converts it to Fahrenheit and displays the result. The
formula for the conversion is as follows:
: In Java,
, but
9.0/5
learn from examples
length of a cylinder and computes volume using the following formulas:
Chapter 2Elementary Programming
Converting pounds into kilograms
) Write a program that converts pounds into
kilograms. The program prompts the user to enter a number in pounds, converts it
Financial application: calculating tips
and the gratuity rate, then computes the gratuity and total. For example, if the user
Summing the digits in an integer
Finding the number of years
)Write a program that prompts the user to enter the
For simplicity, assume a year has
Programming Exercises
and output is shown below:
Federal Withholding (20.0%): $13.5
2.12*
Financial application: calculating interest
) If you know the balance and the
annual percentage interest rate, you can compute the interest on the next monthly
payment using the following formula:
Section 2.13
Finding the character of an ASCII code
) Write a program that receives an ASCII
Chapter 2Elementary Programming
2.13*
Financial application: calculating the future investment value
that reads in investment amount, annual interest rate, and number of years, and
displays the future investment value using the following formula:
For example, if you enter amount
, the future investment value is
Math.pow(a,b)
2.14*
) Body Mass Index (BMI) is a measure of
2.15**
Financial application: compound value
) Suppose you save
each
into a savings account with the annual interest rate 5%. So, the monthly interest
rate is After the first month, the value in the account
After the second month, the value in the account becomes
Video Note
Compute BMI
displays the interest for the next month in two versions: (a) Use dialog boxes to
Programming Exercises
After the third month, the value in the account becomes
Write a program to display the account value after the sixth month. (In Exercise
4.30, you will use a loop to simplify the code and display the account value for
any month.)
2.16
Science: calculating energy
) Write a program that calculates the energy needed
to heat water from an initial temperature to a final temperature. Your program
should prompt the user to enter the amount of water in kilograms and the initial
and final temperatures of the water. The formula to compute the energy is
is the weight of water in kilograms, temperatures are in degrees Celsius,
and energy
2.17*
Science: wind-chill temperature
) How cold is it outside? The temperature alone
is not enough to provide the answer. Other factors including wind speed, relative
2.18
) Write a program that displays the following table:
Chapter 2Elementary Programming
=
1
s
Physics: acceleration
)Average acceleration is defined as the change of velocity
divided by the time taken to make the change, as shown in the following formula:
Write a program that prompts the user to enter the starting velocity in
2.19
Random character
2
1
x
x
1
y
y
Programming Exercises
Physics: finding runway length
)Given an airplanes acceleration
and take-off
, you can compute the minimum runway length needed for an airplane to
take off using the following formula:
Current time
)Listing 2.6, ShowCurrentTime.java, gives a program that displays
the current time in GMT. Revise the program so that it prompts the user to enter
Objectives
To declare
type and write Boolean expressions using comparison operators (3.2).
To program
using Boolean expressions (3.3).
To implement selection control using one-way
To program the
game using one-way
To implement selection control using two-way
To implement selection control using nested
To avoid common errors in
Chapter 3Selections
3.1Introduction
If you enter a negative value for
in Listing 2.2, ComputeAreaWithConsoleInput.java,
the program prints an invalid result. If the radius is negative, you dont want the program to
compute the area. How can you deal with this situation?
3.1
Comparison Operators
Operator
You can also compare characters. Comparing characters is the same as comparing their Unicodes.
For example,
is larger than
because the Unicode of
is larger than the Unicode of
. See Appendix B, The ASCII Character Sets, to find the order of characters.
The equality comparison operator is two equal signs (
), not a single equal sign (
symbol is for assignment.
The result of the comparison is a Boolean value:
. For example, the following
A variable that holds a Boolean value is known as a
Booleanvariable
is used to declare Boolean variables. A
variable can hold one of the two values:
3.3Problem: A Simple Math Learning Tool
. For example, the following statement assigns
to the variable
are literals, just like a number such as
. They are reserved words and can-
not be used as identifiers in your program.
3.3Problem: A Simple Math Learning Tool
Boolean expression
number1+number2 == answer
3.1
)5678// Create a Scanner9 Scanner input = newScanner(System.in);1011 System.out.print(12"What is "+ number1 + " + "+ number2 + "? ");13141516 System.out.println(17 number1 + " + "+ number2 + " = "+ answer + " is "+18 ());
%
);
show question
line#number1number2answeroutput
149
164 + 8 = 9 is false
Video Note
Program addition quiz
Chapter 3Selections
Statements
The preceding program displays a message such as is false. If you wish the message
to be is incorrect, you have to use a selection statement to carry out this minor change.
This section introduces selection statements. Java has several types of selection statements:
one-way
statements, two-way
and conditional expressions.
3.4.1One-Way
Statements
A one-way
statement executes an action if and only if the condition is
for a one-way
statement is shown below:
The execution flow chart is shown in Figure 3.1(a).
evaluates to
, the statements in the block are executed.
As an example, see the following code:
The flow chart of the preceding statement is shown in Figure 3.1(b). If the value of
the two statements in the block will not be executed.
is enclosed in parentheses. For example, the code in (a)
below is wrong. It should be corrected, as shown in (b).
3.1
statement executes statements if the
evaluates to
expression
true
false
true
false
(b)
�i
{
"i is positive"
�i
{
"i is positive"
(a) Wrong(b) Correct
3.5Problem: Guessing Birthdays
The block braces can be omitted if they enclose a single statement. For example, the follow-
ing statements are equivalent.
check even
The program prompts the user to enter an integer (line 7) and displays
if it is divisi-
if it is divisible by
3.5Problem: Guessing Birthdays
You can find out the date of the month when your friend was born by asking five questions.
)
"i is positive"
Equivalent
Listing 3.2 gives a program that prompts the user to enter an integer. If the number is a multi-
. If the number is divisible by
)
)
16171819
20212223
24252627
28293031
91011
12131415
24252627
28293031
12131415
20212223
28293031
10111415
182223
26273031
9111315
1719
2123
25272931
4
1
Chapter 3Selections
)
;
3.5Problem: Guessing Birthdays
)
)
)
)
Chapter 3Selections
line#dayansweroutput
350
441
471
531
563
620
710
801
8319
Your birthday is 19
DecimalBinary
100001
200010
1910011
3111111
1931
(a)(b)
The game is easy to program. You may wonder how the game was created. The mathematics
3.6Two-Way
Statements
expression
true
false
3.6Two-Way
Statements
A one-way
statement takes an action if the specified condition is
, nothing is done. But what if you want to take alternative actions when the condition is
? You can use a two-way
statement. The actions that a two-way
Chapter 3Selections
(a)(b)
� (score =
A preferred format for multiple alternative
statements is shown in (b).
Here is another example of using the
if...else
statement. The example checks
3.8Common Errors in Selection Statements
(number %
2
==
0
)
even =
true
;
else
false
;
(a)(b)
The code can be simplified by assigning the test value directly to the variable, as shown in (b).
3.8Common Errors in Selection Statements
The following errors are common among new programmers.
(even ==
true
)
System.out.println(
"It is even."
);
(even)
System.out.println(
"It is even."
);
)
"The area "
+ area);
)
"The area "
+ area);
Common Error 2: Wrong Semicolon at the
line, as shown in (a) below, is a common mistake.
� (radius =
0
);
{
"The area "
+
" is "
+ area);
}
if
� (radius =
0
) { }
;
{
"The area "
+
" is "
+ area);
}
Equivalent
(a)(b)
This mistake is hard to find, because it is neither a compilation error nor a runtime error; it
is a logic error. The code in (a) is equivalent to that in (b) with an empty block.
This error often occurs when you use the next-line block style. Using the end-of-line block
style can help prevent the error.
Common Error 3: Redundant Testing of Boolean Values
Chapter 3Selections
System.out.println(
System.out.println(
System.out.println(
System.out.println(
(a)(b)
randomly generates two single-digit integers,
number1�=
and displays to the student a question such as What is After the student
Video Note
Program subtraction quiz
3.9Problem: An Improved Math Learning Tool
)5// 1. Generate two random single-digit integers6intnumber1 = (int)(Math.random() * 10);7intnumber2 = (int)(Math.random() * 10);89// 2. If number1 number2, swap number1 with number210 {
line#number1number2tempansweroutput
112
129
132
205
26Your answer is wrong
Chapter 3Selections
below 16
overweight
seriously overweight
above 35
gravely overweight
To swap two variables
, a temporary variable
to first hold the value in
. The value in
and the value in
3.10Problem: Computing Body Mass Index
Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your
3.11Problem: Computing Taxes
Two constants
2009 U.S. Federal Personal Tax Rates
Marginal
Tax Rate
Married Filing Jointly
or Qualified Widow(er)
Married Filing Separately
0
-
$
8,350
0
-
$
0
-
$
0
-
$
8,351
-
$
$
$
$
$
$
$
$
$
$
$
$
$
$
$
$
Video Note
Use multiple alternative
if statements
Chapter 3Selections
You are to write a program to compute personal income tax. Your program should prompt
the user to enter the filing status and taxable income and compute the tax. Enter
filers,
for married filing jointly,
for married filing separately, and
Your program computes the tax for the taxable income based on the filing status. The filing
1
1
171,550
-
82,250
2
1
1
33,950
-
8,350
2
3.11Problem: Computing Taxes
(status ==
(status ==
exit program
line#statusincometaxoutput
130
17400000
200
38117683.5
57Tax is 117683.5
The program receives the filing status and taxable income. The multiple alternative
statements (lines 22, 42, 45, 48, 51) check the filing status and compute the tax based on the
filing status.
(line 53) is defined in the
Chapter 3Selections
Boolean Operators
Operator
logical negation
exclusive or
logical exclusion
Truth Table for Operator
Example (assume )
, because is
!(gender=='M')
(gender=='M')
Truth Table for Operator
Example (assume )
(age�18) && (gender=='F')
(age�18)
(gender=='F')
(age�18)&&(gender!='F')
(gender!='F')
statement. The compiler thinks that these statements may not be executed and therefore
reports a syntax error.
To test a program, you should provide the input that covers all cases. For this program,
your input should cover all statuses (
). For each status, test the tax for each of the six
incremental development and
3.12Logical Operators
Truth Table for Operator
Example (assume )
(age�34)||(gender=='F')
(gender=='F')
(age�34)||(gender=='M')
(age�34)
(gender=='M')
Truth Table for Operator
Example (assume )
(age�34)^(gender=='F')
(age�34)
but
(gender=='F')
(age�34)||(gender=='M')
(age�34)
(gender=='M')
exclusive or
divisible by 2 and 3? true
Chapter 3Selections
(number%2==0&&number%3==0)
De Morgans law
3.14Problem: Lottery
!=
==
)
leap year?
display result
3.14Problem: Lottery
Suppose you want to develop a program to play lottery. The program randomly generates a
(int)
(Math.random() *
);
Chapter 3Selections
variable
6111415181933
lottery34
guess23
lotteryDigit13
lotteryDigit24
guessDigit12
guessDigit23
outputMatch one digit:
you win $1,000
(guessDigit1 == lotteryDigit1
(guessDigit2 == lotteryDigit1
exact match?
obtains the first digit from
is a two-digit number (lines 1819).
3.15
Statements
Compute tax for head of household
status is 0
statement checks all cases and executes the statements in the
Chapter 3Selections
statement observes the following rules:
must yield a value of
and must always be enclosed in parentheses.
must have the same data type as the value of the
are constant expres-
sions, meaning that they cannot contain variables, such as
When the value in a
statement matches the value of the
starting from this case
are executed until either a
The keyword
the specified cases matches the
statements are checked in sequential order, but the order of the cases
(including the default case) does not matter. However, it is good programming
style to follow the logical sequence of the cases and place the default case at the
Do not forget to use a
statementwhen one is needed. Once a case is matched, the state-
ments starting from the matched case are executed until a
statement or the end of the
statement is reached. This is referred to as
fall-through
behavior. For example, the fol-
lowing code prints character
three times if
fall-through behavior
ch is 'c'
true
false
true
(ch) {
case
'a'
: System.out.println(ch);
case
'b'
: System.out.println(ch);
case
'c'
: System.out.println(ch);
}
Tip
To avoid programming errors and improve code maintainability, it is a good idea to put a com-
is purposely omitted.
3.17Formatting Console Output
3.16Conditional Expressions
You might want to assign a value to a variable that is restricted by certain conditions. For
example, the following statement assigns
Alternatively, as in this example, you can use a conditional expression to achieve the same
1-1
conditional expression
Chapter 3Selections
Frequently Used Specifiers
Specifier
a Boolean value
true or false
a decimal integer
a number in standard scientific notation
Java is cool
Examples of Specifying Width and Precision
Output the Boolean value and add one space before the false value and two spaces before
the true value.
Output the integer item with width at least 5. If the number of digits in the item is
add spaces before the number. If the number of digits in the item is the width is
Output the floating-point item with width at least 10 including a decimal point and two
number of digits before the decimal point in the item is add spaces before the
number. If the number of digits before the decimal point in the item is the width is
Output the floating-point item with width at least 10 including a decimal point, two digits
after the point and the exponent part. If the displayed number in scientific notation has
width less than 10, add spaces before the number.
specifier
A format specifier specifies how an item should be displayed. An item may be a numeric
value, a character, a Boolean value, or a string. A simple specifier consists of a percent sign
) followed by a conversion code. Table 3.8lists some frequently used simple specifiers:
displaycount is 5 and amount is 45.560000
Here is an example:
Items must match the specifiers in order, in number, and in exact type. For example, the
specifier for
. By default, a floating-point value is displayed
with six digits after the decimal point. You can specify the width and precision in a specifier,
as shown in the examples in Table 3.9.
3.18Operator Precedence and Associativity
The items must match the specifiers in exact type. The item for the specifier
floating-point type value such as 40.0, not 40. Thus an
variable cannot match
Tip
sign denotes a specifier. To output a literal
in the format string, use
3.18Operator Precedence and Associativity
associativity
The code presented in the beginning of this section for displaying only two digits after the
decimal point in a floating-point value can be revised using the
display x is 0.67
conversion code
By default, the output is right justified. You can put the minus sign (
) in the specifier to
specify that the item is left justified in the output within the specified field. For example, the
following statements
12
J v a
Chapter 3Selections
3.10
Operator Precedence Chart
Precedence
Operator
(Postfix)
(Prefix)
(Multiplication, division, and remainder)
(Exclusive OR)
. Therefore, the expression
equivalent
are 1 before the assignment; after the whole expression is evaluated,
becomes 5. Note that left associativity for the assignment
operator would not make sense.
Java has its own way to evaluate an expression internally. The result of a Java evaluation is the
same as that of its corresponding arithmetic evaluation. Interested readers may refer to Supple-
ment III.B for more discussions on how an expression is evaluated in Java
3.19(GUI) Confirmation Dialogs
You have used
tion with a confirmation dialog box. A confirmation dialog can be created using the following
option =
JOptionPane.showConfirmDialog
(
null
,
"Continue"
);
3.19(GUI) Confirmation Dialogs
option =
JOptionPane.showConfirmDialog
(
null
,
"Continue"
);
(a)(b)(c)
Click Yes in (a), Yes in (b), No in (c), No in (d), and Yes in (e).
3.10
Chapter 3Selections
;
// Prompt the user to answer questions
38
;
"Is your birthday in these numbers?\n"
UMMARY
variable stores a
value.
) work with numbers and characters, and
yield a Boolean value.
confirmation dialog
Review Questions
operate with Boolean values and variables.
When evaluating
p1&&p2
, Java first evaluates
and then evaluates
, it does not evaluate
. When evaluating
p1p2
, Java first evaluates
and then evaluates
, it does not evaluate
is referred to as the conditional or short-circuit AND operator, and is
referred to as the conditional or short-circuit OR operator.
Selection statements are used for programming with alternative courses. There are
several types of selection statements:
if...else
statements, and conditional expressions.
The various
statements all make control decisions based on a Boolean expression.
evaluation of the expression, these statements take one
of two possible courses.
statement makes control decisions based on a switch expression of type
The keyword
is optional in a switch statement, but it is normally used at the
statement is not present, the next
statement will be executed.
UESTIONS
3.1
Can the following conversions involving casting be allowed? If so, find the con-
verted result.
Sections 3.33.11
tively?
(a)(b)
; show the output, if any, of the following code. What is
? Draw a flow
Chapter 3Selections
Which of the following statements are equivalent? Which ones are correctly
(a)(b)
� (i
0
) {
if
� (j
0
)
x =
0
;
else
� if (k
0
)
y =
0
;
}
0
;
elseif
(c)(d)
� (i
0
)
if
� (j
0
)
x =
0
;
else if
� (k
0
)
y =
0
;
else
z =
0
;
. Show the output, if any, of the following code. What is
: Indent the statement correctly first.)
Are the following two statements equivalent?
(income =
10000
)
tax = income *
0.1
;
else if
(income =
20000
)
tax =
1000
+
(income
10000
) *
0.15
;
(income =
10000
)
tax = income *
0.1
;
else if
�(income
10000
&&
income =
20000
)
tax =
1000
+
(income
10000
) *
0.15
;
Which of the following is a possible output from invoking
How do you generate a random integer
such that How
do you generate a random integer
such that How do
you generate a random integer
3.10
3.11
Review Questions
3.12
What is wrong in the following code?
3.13
Rewrite the following statement using a Boolean expression:
Sections 3.123.14
3.14
, show the result of the following Boolean expressions.
3.15
Write a Boolean expression that evaluates to
if a number stored in variable
Chapter 3Selections
Write a Boolean expression that evaluates
Write a Boolean expression that evaluates
Write a Boolean expression that evaluates
Write a Boolean expression that evaluates
, but not both.
Section 3.15
variable? If the keyword
used after a case is processed, what is the next statement to be executed? Can you
convert a
statement to an equivalent
statement, or vice versa? What are
the advantages of using a
after the following
statement is executed?
x=
statement to rewrite the following
statement and draw the flow
variable
with Sunday,
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, if
, accordingly.
Section 3.16
Rewrite the following
Programming Exercises
Rewrite the following statement using a conditional expression:
Section 3.17
What are the specifiers for outputting a Boolean value, a character, a decimal inte-
ger, a floating-point number, and a string?
What is wrong in the following statements?
Show the output of the following statements.
How do you create a formatted string?
Section 3.18
List the precedence order of the Boolean operators. Evaluate the following expres-
True or false? All the binary operators except
are left associative.
Evaluate the following expressions:
(x�0 &&x10)
((x�0) && (x10))
(x�0 ||x10)
((x�0)||(x10))
(x�0||x10&&y0)
�(x 0||(x10 &&y0))
Section 3.19
ROGRAMMING
Pedagogical Note
For each exercise, students should carefully analyze the problem requirements and design
strategies for solving the problem before coding.
Chapter 3Selections
Pedagogical Note
Instructors may ask students to document analysis and design for selected exercises. Students
should use their own words to analyze the problem, including the input, output, and what
needs to be computed, and describe how to solve the problem in pseudocode.
Debugging Tip
Before you ask for help, read and explain the program to yourself, and trace it using several
representative inputs by hand or using an IDE debugger. You learn how to program by debug-
ging your own mistakes.
3.1*
Algebra: solving quadratic equations
) The two roots of a quadratic equation
can be obtained using the following formula:
is called the discriminant of the quadratic equation. If it is positive, the
equation has two real roots. If it is zero, the equation has one root. If it is negative,
Write a program that prompts the user to enter values for
the result based on the discriminant. If the discriminant is positive, display two
Math.pow(x,0.5)
to compute Here are some sample
b
-
b
+
2
b
-
b
-
2
b
ax
c
=
0
learn from mistakes
Programming Exercises
Algebra: solving linear equations
) You can use Cramers rule to solve the
following system of linear equation:
result. If is
=
*
2
2
*
2
) Write a program that generates two integers under 100 and
prompts the user to enter the sum of these two integers. The program then reports true
if the answer is correct, false otherwise. The program is similar to Listing 3.1.
Game: addition for three numbers
) The program in Listing 3.1 generates two
integers and prompts the user to enter the sum of these two integers. Revise the
program to generate three single-digit integers and prompt the user to enter the
sum of these three integers.
subtraction question. Revise the program to randomly generate an addition ques-
tion with two integers less than
Video Note
Sort three integers
Chapter 3Selections
Sections 3.93.19
3.11*
Finding the number of days in a month
to enter the month and year and displays the number of days in the month. For
example, if the user entered month
3.12
Checking a number
) Write a program that prompts the user to enter an integer
3.18*
Using the input dialog box
) Rewrite Listing 3.8, LeapYear.java, using the input
3.19
Validating triangles
Programming Exercises
: for a positive
in the formula. So you need to convert the user input
the month and change the year to the previous year.)
Science: wind-chill temperature
) Exercise 2.17 gives a formula to compute the
,
h
=
a
q
+
m
+
1
2
k
+

%
7
-
Chapter 3Selections
3.24**
Game: picking a card
cards. Your program should display the rank (
(a)(b)
-axis
y
-axis
(0, 0)
rectangle.
Programming Exercises
3.27**
3.28**
1
(
x
1,
y
1)
(
x
2,
y
2)
w
2
h
2
h
1
1
(
x
1,
y
1)
(
x
2,
y
2)
w
2
h
2
h
1
(a) A rectangle is inside another one. (b) A rectangle overlaps another one.
(0, 0)(200, 0)
2
p
1
Chapter 3Selections
3.29**
(a)(b)
x
1,
y
1)
r
1
x
2,
y
2)
r
2
(a) A circle is inside another circle. (b) A circle overlaps another circle.
Programming Exercises
Objectives
To write programs for executing statements repeatedly using a
To develop a program for
To follow the loop design strategy to develop loops (4.2.2).
To develop a program for
To control a loop with a sentinel value (4.2.4).
To obtain large input from a file using input redirection
rather than typing from the keyboard (4.2.4).
To write loops using
To write loops using
To discover the similarities and differences of three
To write nested loops (4.6).
To learn the techniques for minimizing numerical errors (4.7).
Chapter 4Loops
4.1Introduction
"WelcometoJava!"
would be tedious to have to write the following statement a hundred times:
So, how do you solve this problem?
Java provides a powerful construct called a
that controls how many times an operation
tell the computer to print a string a hundred times without having to code the print statement
a hundred times, as follows:
The variable
4.2The
counter-controlled loop
infinite loop
off-by-one error
continuation
condition?
true
false
true
false
(loop body)
4.1
loop repeatedly executes the statements in the loop body when the
evaluates to
In this example, you know exactly how many times the loop body needs to be executed. So a
control variable
is used to count the number of executions. This type of loop is known
counter-controlled loop
must always appear inside the parentheses. The
braces enclosing the loop body can be omitted only if the loop body contains one or no
statement.
Here is another example to help understand how a loop works.
i10
. Variable
Chapter 4Loops
4.2.1Problem: Guessing Numbers
The problem is to guess what a number a computer has in mind. You will write a program that
Video Note
4.2The
(guess != number) {
(guess != number) {
) {
�(guess number)
too low?
Chapter 4Loops
line#numberguessoutput
11-1
1550
20Your guess is too high
1525
20Your guess is too high
1512
20Your guess is too high
156
22Your guess is too low
159
20Yes, the number is 9
4.2The
4.2.3Problem: An Advanced Math Learning Tool
The Math subtraction learning tool program in Listing 3.4, SubtractionQuiz.java, generates
just one question for each run. You can use a loop to generate questions repeatedly. How do
you write the code to generate five questions? Follow the loop design strategy. First identify
the statements that need to be repeated. These are the statements for obtaining two random
wrap the statements in a loop. Third, add a loop control variable and the loop-continuation-
condition to execute the loop five times.
Listing 4.3 gives a program that generates five questions and, after a student answers all
five, reports the number of correct answers. The program also displays the time spent on the
(count NUMBER_OF_QUESTIONS) {
Video Note
Multiple subtraction quiz
Chapter 4Loops
increase control variable
The program uses the control variable
to control the execution of the loop.
test time is in milliseconds and is converted to seconds in line 49.
4.2.4Controlling a Loop with a Sentinel Value
Another common technique for controlling a loop is to designate a special value when read-
4.2The
(data !=
(line 17) and the next item of input data is read (lines
, the loop body is no longer executed and the
input value
is the sentinel value for this loop. Note that if the first input read is
body never executes, and the resulting sum is
line#datasumoutput
122
150
172
223
175
224
179
220
25The sum is 9
Chapter 4Loops
Dont use floating-point values for equality checking in a loop control. Since floating-point values
are approximations for some values, using them could result in imprecise counter values and inac-
curate results.
Consider the following code for computing
Variable
starts with
and is reduced by
every time the loop body is executed. The
loop should terminate when
. However, there is no guarantee that item will be
exactly
, because the floating-point arithmetic is approximated. This loop seems OK on the sur-
face, but it is actually an infinite loop.
4.2.5Input and Output Redirections
In the preceding example, if you have a large number of data to enter, it would be cumber-
some to type from the keyboard. You may store the data separated by whitespaces in a text
file, say input.txt, and run the program using the following command:
input redirection
. The program takes the input from the file
input.txt rather than having the user to type the data from the keyboard at runtime. Suppose
the contents of the file are
4.3The
The loop body is executed first. Then the
is evalu-
ated. If the evaluation is
, the loop body is executed again; if it is
(data !=
false
continuation
condition?
(loop body)
loop executes the loop body first, then checks the
Chapter 4Loops
Tip
loop if you have statements inside the loop that must be executed
loop in the preceding
program. These
statements must appear before the loop as well as inside it if you use a
4.4The
Often you write a loop in the following common form:
loop is as shown below:
The flow chart of the
loop is shown in Figure 4.3(a).
(loop body)
(a)
true
false
continuation
condition?
(b)
true
false
loop performs an initial action once, then repeatedly executes the
statements in the loop body, and performs an action after an iteration when the
evaluates to
4.4The
loop statement starts with the keyword
, followed by a pair of parentheses
structure is followed by the loop body enclosed inside braces. The
loop generally uses a variable to control how many times the loop body is executed
and when the loop terminates. This variable is referred to as a
control variable
often initializes a control variable, the
increments or decrements the control variable, and the
i =
control variable
declare control variable
for loop variations
Chapter 4Loops
This example is correct, but it is a bad example, because it makes the code difficult to read. Nor-
mally, you declare and initialize a control variable as an initial action and increment or decrement
the control variable as an action after each iteration.
loop is omitted, it is implicitly
the statement given below in (a), which is an infinite loop, is the same as in (b). To avoid confu-
sion, though, it is better to use the equivalent loop in (c):
(
;
true
;
) {
(
while
(
true
) {
4.5Which Loop to Use?
Equivalent
loop in (a) in the next figure can generally be converted into the
(b) except in certain special cases (see Review Question 4.17 for such a case):
Equivalent
Use the loop statement that is most intuitive and comfortable for you. In general, a
i =
; i++) { }
(a)
i =
4.6Nested Loops
i =
0
;
do
{
System.out.println(
"i is "
+ i);
i++;
while
(i
10
);
4.6Nested Loops
Nested loopsconsist of an outer loop and one or more inner loops. Each time the outer loop is
repeated, the inner loops are reentered, and started anew.
j =
Similarly, the loop in (c) is also wrong. (c) is equivalent to (d).
i =
0
;
while
(i
10
) { };
{
"i is "
+ i);
i++;
(d)
i =
0
;
while
(i
10
);
{
"i is "
+ i);
i++;
Error
(c)
These errors often occur when you use the next-line block style. Using the end-of-line block style
can avoid errors of this type.
Chapter 4Loops
1 2 3 4 5 6 7 8 9
-
The program displays a title (line 5) on the first line in the output. The first
The next loop (lines 1522) is a nested
loop with the control variable
in the inner loop. For each
4.7Minimizing Numeric Errors
Numeric errors involving floating-point numbers are inevitable. This section discusses how to
minimize such errors through an example.
Listing 4.7 presents an example summing a series that starts with
, as follows:
0.01f
,
loop (lines 78) repeatedly adds the control variable
. This variable, which
begins with
exceeds
loop initial action can be any statement, but it is often used to initialize a control
variable. From this example, you can see that a control variable can be a
type. In fact,
it can be any data type.
Video Note
Minimize numeric errors
4.8Case Studies
The exact
, but the answer is
because computers use a fixed number of bits to represent floating-point numbers, and thus
they cannot represent some floating-point numbers exactly. If you change
, as follows, you should see a slight improvement in precision, because a
variable takes 64 bits, whereas a
variable takes 32.
(i =
However, you will be stunned to see that the result is actually
slightly larger than
(not exactly
damental problem is that the floating-point numbers are represented by approximation. To fix
the problem, use an integer count to ensure that all the numbers are added to
new loop:
in this order) as follows:
way to minimize error.
4.8Case Studies
Loops are fundamental in programming. The ability to write loops is essential in learning Java
If you can write programs using loops, you know how to program!
For this rea-
son, this section presents three additional examples of solving problems using loops.
4.8.1Problem: Finding the Greatest Common Divisor
The greatest common divisor of two integers
. The greatest common divisor of
two integers
,
avoiding numeric error
Chapter 4Loops
)
;
check divisor
How did you write this program? Did you immediately begin to write the code? No. It is
think before you type
problem without concern about how to write the code. Once you have a logical solution, type
4.8Case Studies
the code to translate the solution into a Java program. The translation is not unique. For exam-
loop to rewrite the code as follows:
A problem often has multiple solutions. The gcd problem can be solved in many ways. Exer-
cise 4.15 suggests another solution. A more efficient solution is to use the classic Euclidean
algorithm. See http://www.cut-the-knot.org/blue/Euclid.shtml for more information.
You might think that a divisor for a number
n1/2
would attempt to improve the program using the following loop:
; k = && k = ; k++) {
This revision is wrong. Can you find the reason? See Review Question 4.14 for the answer.
4.8.2Problem: Predicating the Future Tuition
Suppose that the tuition for a university is
every
year. In how many years will the tuition be doubled?
Before you can write a program to solve this problem, first consider how to solve it by
hand. The tuition for the second year is the tuition for the first year *
computed as follows:
Keep computing tuition for a new year until it is at least
. By then you will know how
many years it will take for the tuition to be doubled. You can now translate the logic into the
following loop:
(tuition
20000
Chapter 4Loops
next years tuition
loop (lines 58) is used to repeatedly compute the tuition for a new year. The loop
4.8.3Problem: Problem: Monte Carlo Simulation
Monte Carlo simulation uses random numbers and probability to solve problems. This
1
1
1
x
y
. So, the circle area is and the square area is
domly generate a point in the square. The probability for the point to fall in the circle is
circleArea/squareArea=
pi =
x = Math.random() *
1
;
p
4.9Keywords
If the point is inside the circle and
.is
4*numberOfHits/NUMBER_OF_TRIALS
4.9Keywords
Pedagogical Note
Two keywords,
, can be used in loop statements to provide additional
controls. Using
can simplify programming in some cases. Overusing or
improperly using them, however, can make programs difficult to read and debug. (
Note to instruc-
tors
: You may skip this section without affecting the rest of the book.)
You have used the keyword
statement. You can also use
to immediately terminate the loop. Listing 4.11 presents a program to demonstrate the effect
4.11
x
y
1,
The program in Listing 4.11 adds integers from
. Without the
. Without the
statement, the output would be:
"PI is "
+ pi);
15 }
Chapter 4Loops
You can also use the
keyword in a loop. When it is encountered, it ends the current
iteration. Program control goes to the end of the loop body. In other words,
keyword breaks out of a loop. Listing 4.12 presents a pro-
gram to demonstrate the effect of using
4.12
The program in Listing 4.12 adds integers from
except
. With the
statement is executed when
statement in the loop body is not executed; therefore,
. Without the
statement in the program, the output would be as follows:
, even when
more than it was with the
statement is always inside a loop. In the
is evaluated immediately after the
state-
is performed, then the
is evaluated, immediately after the
statement.
You can always write a program without using
in a loop. See Review
is appropriate only if it simplifies cod-
ing and makes programs easier to read.
Listing 4.2 gives a program for guessing a number. You can rewrite it using a
ment, as shown in Listing 4.13.
4.9Keywords
4.13
) {
Chapter 4Loops
(count NUMBER_OF_PRIMES) {
exit loop
4.10(GUI) Controlling a Loop with a Confirmation Dialog
// Print the number and advance to the new line
29 System.out.println(number);
);
// Check if the next number is prime
36 number++;
This is a complex program for novice programmers. The key to developing a programmatic
solution to this problem, and to many other problems, is to break it into subproblems and
confirmation dialog
Chapter 4Loops
1
1
1
x
y
(a)(b)
(c)(d)(e)
The user enters 3 in (a), clicks Yes in (b), enters 5 in (c), clicks No in (d), and the result is
shown in (e).
Listing 4.15 rewrites Listing 4.4, SentinelValue.java, using a confirmation dialog box. A sam-
ple run is shown in Figure 4.4.
4.15
)5intsum = 0;67// Keep reading data until the user answers No8intoption = JOptionPane.YES_OPTION; 9while(option == JOptionPane.YES_OPTION) {10// Read the next data11 String dataString = JOptionPane.showInputDialog(12"Enter an int value: ");13intdata = Integer.parseInt(dataString);1415 sum += data;1617 option = JOptionPane.showConfirmDialog(null,"Continue?");18 }1920 JOptionPane.showMessageDialog(null,"The sum is "+ sum); 21 }22 }A program displays an input dialog to prompt the user to enter an integer (line 11) and adds it
confirmation option
confirmation dialog
statement136
statement136
loop124
loop126
loop control structure127
infinite loop117
Chapter Summary
input redirection124
iteration116
labeled continue statement136
loop116
loop body116
nested loop 129
off-by-one error124
output redirection124
sentinel value122
loop116
UMMARY
Chapter 4Loops
keyword immediately ends the innermost loop, which contains the break.
keyword only ends the current iteration.
UESTIONS
4.1
Analyze the following code. Is
count100
always
, always
int
(b)(c)
; ) {
(a)(b)
. What is the output of the following code?
)Scanner input = newScanner(System.in);intnumber, max;number = input.nextInt();max = number;while(number != 0) {number = input.nextInt();if�(number max)max = number;}System.out.println("max is "+ max);System.out.println("number "+ number);}}4.8Suppose the input is 23450. What is the output of the following code?
)Scanner input = newScanner(System.in);intnumber, sum = 0, count;for(count = 0; count 5; count++) {number = input.nextInt();sum += number;}System.out.println("sum is "+ sum);System.out.println("count is "+ count);}}4.9Suppose the input is 2 3 4 5 0. What is the output of the following code?
)Scanner input = newScanner(System.in);intnumber, max;number = input.nextInt();max = number;do{number = input.nextInt();if�(number max)max = number;}while(number != 0);System.out.println("max is "+ max);System.out.println("number "+ number);}}Review Questions
Chapter 4Loops
4.10
What does the following statement do?
int
}
4.16
Can you always convert a
loop? Convert the following
4.17
loop on the left is converted into the
(
int
i =
0
; i
4
; i++) {
if
(i %
3
==
0
)
continue
;
sum += i;
i =
0
;
while
(i
4
) {
if
(i %
3
==
0
)
continue
;
sum += i;
Converted
Review Questions
4.18
Rewrite the programs
4.19
statement is executed in the following loop, which statement is
executed? Show the output.
statement is executed in the following loop, which statement
is executed? Show the output.
Comprehensive
Identify and fix the errors in the following code:
Chapter 4Loops
What is wrong with the following programs?
4 System.out.println(i +
Show the output of the following programs. (
Tip
: Draw a table and list the vari-
public class
System.out.print(num +
}
}
}
System.out.print(num +
}
}
What is the output of the following program? Explain the reason.
Count the number of iterations in the following loops.
Programming Exercises
) Listing 4.3, SubtractionQuizLoop.java, generates five ran-
dom subtraction questions. Revise the program to generate ten random addition
count++;
for
count++;
int
count = count +
}
ROGRAMMING
Pedagogical Note
For each problem, read it several times until you understand the problem. Think how to solve
the problem before coding. Translate your logic into a program.
A problem often can be solved in many different ways. Students are encouraged to explore
4.1*
Counting positive and negative numbers and computing the average of numbers
explore solutions
Chapter 4Loops
Programming Exercises
4.15*
Computing the greatest common divisor
) Another solution for Listing 4.8 to find
the greatest common divisor of two integers
is as follows: First find
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
4.18*
) Use nested loops that print the following pat-
Pattern IPattern IIPattern IIIPattern IV
11 2 3 4 5 611 2 3 4 5 6
1 21 2 3 4 5 2 11 2 3 4 5
1 2 31 2 3 43 2 11 2 3 4
1 2 3 41 2 3 4 3 2 11 2 3
1 2 3 4 51 2 5 4 3 2 11 2
1 2 3 4 5 61 6 5 4 3 2 11
4.19**
Printing numbers in a pyramid pattern
following output:
1 2 4 8 16 32 6412864 32 168 4 2 1
Chapter 4Loops
The balance after the last payment may not be zero. If so, the last payment should be the normal
monthly payment plus the final balance.
loan amount. For each iteration in the loop, compute the interest and principal,
and update the balance. The loop may look like this:
Payment#InterestPrincipalBalance
158.33806.939193.07
253.62811.648381.43
1110.0855.26860.27
125.01860.250.01
Interest RateMonthly PaymentTotal Payment
5%188.7111322.74
5.125%189.2811357.13
5.25%189.8511391.59
7.875%202.1712129.97
8.0%202.7612165.83
For the formula to compute monthly payment, see Listing 2.8, ComputeLoan.java.
Financial application: loan amortization schedule
given loan pays the principal and the interest. The monthly interest is computed
Video Note
Display loan schedule
Programming Exercises
Obtaining more accurate results
) In computing the following series, you will obtain
n50000
) Write a program to sum the following series:
) You can approximate by using the following series:
Write a program that displays the value for
i10000
) You can approximate
using the following series:
value for
i10000
: Since thenis
and keep adding a new
. The new item is
the previous item divided by
Displaying leap years
line, in the twenty-first century (from 2001 to 2100).
Displaying the first days of each month
enter the year and first day of the year, and displays the first day of each month in
the year on the console. For example, if the user entered the year
Saturday, January 1, 2005, your program should display the following output
Displaying calendars
first day of the year and displays the calendar table for the year on the console. For
example, if the user entered the year
for Saturday, January 1, 2005,
your program should display the calendar for each month in the year, as follows:
1)
!
1
!
i
!
=
i
*
1)
*
1,

,
=
e
=
1
+
1
!
+
1
!
+
1
!
+
1
!
!

,
=
p
p
=
4
a
1
-
1
+
1
-
1
+
1
-
1
1
-
1
1
b
p
p
1
+
3
+
5
+
7
+
9
+
11
1
+
1
+
1
January 2005
Sun Mon Tue Wed Thu Fri Sat
2345678
9101112131415
16171819202122
23242526272829
3031
Chapter 4Loops
SunMonTueWedThuFriSat
123
45678910
11121314151617
18192021222324
2526272829 3031
Financial application: compound value
) Suppose you save
each
a savings account with the annual interest rate
0.05/12=0.00417
. After the first month, the value in the account becomes
After the second month, the value in the account becomes
After the third month, the value in the account becomes
in the savings account after the given month.
Financial application: computing CD value
with an annual percentage yield of 5.75%. After one month, the CD is worth
After two months, the CD is worth
After three months, the CD is worth
table as shown in the sample run.
MonthCD Value
110047.91
210096.06
1710846.56
1810898.54
Programming Exercises
) Revise Listing 3.9, Lottery.java, to generate a lottery of a two-
digit number. The two digits in the number are distinct.
: Generate the first digit. Use a loop to continuously generate the second
digit until it is different from the first digit.)
Perfect number
) A positive integer is called a
sum of all of its positive divisors, excluding itself. For example,
is the first perfect
. The next is
28=14+7+4+2+1
. There are four
. Write a program to find all these four numbers.
Game: scissor, rock, paper
) Exercise 3.17 gives a program that plays the
+
2
2
1
2
2
3
1
3
2
4
2
Sales AmountCommission Rate
$0.01$5,0008 percent
$5,000.01$10,00010 percent
$10,000.01 and above12 percent
Your goal is to earn $30,000 a year. Write a program that finds out the minimum
amount of sales you have to generate in order to make $30,000.
Occurrence of max numbers
) Write a program that reads integers, finds the
largest of them, and counts its occurrences. Assume that the input ends with
352555 0
; the program finds that the
largest is
: Maintain two variables,
ber, and
stores its occurrences. Initially, assign the first number to
Chapter 4Loops
Financial application: finding the sales amount
) Rewrite Exercise 4.39 as follows:
) A square is divided into four smaller regions as shown
below in (a). If you throw a dart into the square 1000000 times, what is the prob-
ability for a dart to fall into an odd-numbered region? Write a program to simulate
shown in (b). Randomly generate a point in the square and count the number of
times a point falls into an odd-numbered region.)
4
3
2
(a)
4
3
2
(b)
picking two numbers from integers
.Also display the total number of all
Computer architecture: bit-level operations
value is stored in
Write a program that prompts the user to enter a short integer and displays the
bits for the integer. Here are sample runs:
: You need to use the bitwise right shift operator (
), which are covered in Supplement III.D on the Companion Website.)
Chapter 5Methods
5.1Introduction
Suppose that you need to find the sum of integers from
, respectively. You may write the code as follows:
You may have observed that computing sum from
are very similar except that the starting and ending integers are different. Wouldnt it be nice
if we could write the common code once and reuse it without rewriting it? We can do so by
5.2Defining a Method
z = max(x, y);
max(
int
num1,
int
num2) {
int
result;
if
� (num1 num2)
result = num1;
else
result = num2;
5.1
definition defines what the defined item is, but a declaration usually involves allocating memory
to store data for the declared item.
Chapter 5Methods
int
Video Note
Define/invoke max method
5.3Calling a Method
line#ijknum1num2 result
1252
13undefined
165
main(String[] args) {
int
i =
5
;
int
j =
2
;
int
k = max(i, j);
System.out.println(
i
max(
int
num1,
int
num2) {
int
result;
if
� (num1 num2)
result = num1;
else
result = num2;
Chapter 5Methods
sign(
int
n) {
if
� (n
0
)
(a)(b)
main
main
max
main
num2: 2
(c) The
max
Video Note
Use void method
Method Example
"The grade is "
) {
else if
�(score =
) {
else if
�(score =
) {
else if
�(score =
) {
printGrade(
double
score) {
);
invoke
Chapter 5Methods
) {
5.5Passing Parameters by Values
three times. However, the statement
nPrintln(3,"Hello")
would be
pass-by-value
invoke increment
Listing 5.5 gives another program that demonstrates the effect of passing by value. The pro-
false swap
Chapter 5Methods
main
num1
and
num2
are
passed to
n1
and
n2
. Executing swap
does not affect
num1
and
num2
.
swap(
n1,
int
n2)
5.6Modularizing Code
For simplicity, Java programmers often say
passing an argument
int
n1,
int
invoke
Video Note
Chapter 5Methods
invoke
2.The errors on computing gcd are confined in the
isPrime(
5.7Problem: Converting Decimals to Hexadecimals
We divided a large problem into two subproblems. As a result, the new program is easier to
h
16123
167
Listing 5.8 gives a program that prompts the user to enter a decimal number and converts
it into a hex number as a string.
String decimalToHex(
Chapter 5Methods
line#decimalhexhexValuetoHe
xChar(hexValue)
191234
iteration 12322
2477
2213
iteration 223D2D
244
224
iteration 3234D24
240
'0')
public staticchar
5.8Overloading Methods
num1,
double
num2,
double
num3)
num1,
double
num2)
int
3.0
3.0
,
4
)
Chapter 5Methods
max(3,4)
num1,
int
double
num2)
,
2
)
ambiguous invocation
5.9The Scope of Variables
j
i
publicstaticvoid
A variable declared in the initial action part of a
5.9The Scope of Variables
is the part of the program where the variable can be referenced. A
i
in two
nonnested blocks
i
in two
nested blocks
publicstaticvoid
A variable can be declared multiple times in nonnested blocks but only once in nested blocks.
Do not declare a variable inside a block and then attempt to use it outside the block. Here is an
example of a common mistake:
Chapter 5Methods
The last statement would cause a syntax error, because variable
is not defined outside of the
5.10The
5.10The
Chapter 5Methods
You can view the documentation for Java API online.
5.11Case Study: Generating Random Characters
Tip
You can view the complete documentation for the
http://java.sun.com/
javase/6/docs/api/index.html
, as shown in Figure 5.7.
Not all classes need a
method. The
class do not have
methods. These classes contain methods for other classes to use.
5.11Case Study: Generating Random Characters
Computer programs process numerical data and characters. You have seen many examples
that involve numerical data. It is also important to understand characters and how to process
them. This section presents an example for generating random characters.
Chapter 5Methods
Line 9 invokes
5.12Method Abstraction and Stepwise Refinement
for input
You have already used the
Chapter 5Methods
(main)
(a)(b)
printMonth
The structure chart shows that the
problem is divided into two subproblems,
is divided into two smaller subproblems,
(a)
5.10
(a) To
5.11
(a) To
5.12Method Abstraction and Stepwise Refinement
(main)
5.12
The structure chart shows the hierarchical relationship of the subproblems in
Chapter 5Methods
isLeapYear(
public staticvoid
printMonthTitle(
printMonth(
5.12Method Abstraction and Stepwise Refinement
Use the following facts to implement
printMonthTitle(
printMonth(
Chapter 5Methods
printMonthBody(
Key Terms
public staticboolean
Chapter 5Methods
UMMARY
Making programs modular and reusable is one of the central goals in software engi-
neering. Java provides many powerful constructs that help to achieve this goal.
Review Questions
UESTIONS
5.1
Chapter 5Methods
Identify and correct the errors in the following program:
(a)(b)
Review Questions
5.12
For (a) in the preceding question, show the contents of the stack just before the
Chapter 5Methods
Section 5.10
5.16
ROGRAMMING
5.1
Math: pentagonal numbers
) A pentagonal number is defined as for
and so on. So, the first few numbers are Write the
Programming Exercises
Palindrome integer
Chapter 5Methods
Programming Exercises
Write a test program that displays the following table:
5.12
Displaying characters
+
1
-
1
+
1
-
1
1
-
1
1
b
m
1
i
2
=
1
+
2
+
1
Video Note
Compute
Chapter 5Methods
5.16*
Programming Exercises
Statistics: computing mean and standard deviation
) In business applications,
you are often asked to compute the mean and standard deviation of data. The
mean is simply the average of the numbers. The standard deviation is a statistic
that tells you how tightly all the various data are clustered around the mean in a
=
x
x
x
i
=
1
i
=
1
-
1
Math: approximating the square root
Chapter 5Methods
Comprehensive
Palindromic prime
palindromic prime
dromic. For example,
. Write a program that displays the first
numbers per line and align the numbers properly, as follows:
(prime spelled backward) is a nonpalindromic prime number
whose reversal is also a prime. For example,
are emirps. Write a program that displays the first
numbers per line and align the numbers properly, as follows:
Mersenne prime
Mersenne prime
ten in the form for some positive integer
. Write a program that finds all
Mersenne primes with and displays the output as follows:
Game: craps
to play a variation of the game, as follows:
Roll two dice. Each die has six faces representing values
tively. Check the sum of the two dice. If the sum is
craps
natural
), you win; if the sum is another value (i.e.,
or the same point value is rolled. If
Your program acts as a single player. Here are some sample runs.
Programming Exercises
Twin primes
) Twin primes are a pair of prime numbers that differ by
. For
example,
twin primes. Write a program to find all twin primes less than
output as follows:
Financial: credit card number validation
) Credit card numbers follow certain
Chapter 5Methods
) Exercise 3.21 uses Zellers congruence to calculate the day
of the week. Simplify Listing 5.12, PrintCalendar.java, using Zellers algorithm
*
p
b
.
5
*
s
*
p
b
INGLE
IMENSIONAL
RRAYS
Objectives
To describe why arrays are necessary in programming (6.1).
To declare array reference variables and create arrays (6.2.16.2.2).
To initialize the values in an array (6.2.3).
To access array elements using indexed variables (6.2.4).
To declare, create, and initialize an array using an array
To program common array operations (displaying arrays,
summing all elements, finding min and max elements,
random shuffling, shifting elements) (6.2.6).
To simplify programming using the for-each loops (6.2.7).
To apply arrays in the
To copy contents from one array to another (6.5).
Chapter 6Single-Dimensional Arrays
each number in the array with the average to count the number of values above the average
This chapter introduces single-dimensional arrays. The next chapter will introduce two-
6.2Array Basics
An array is used to store a collection of data, but often we find it more useful to think of an
array as a collection of variables of the same type. Instead of declaring individual variables,
, you declare one array variable such as
,numbers[1], and numbers[99]to represent individ-
ual variables. This section introduces how to declare array variables, create arrays, and
process arrays using indexed variables.
newdouble
6.2Array Basics
new operator
6.2.1Declaring Array Variables
Touse an array in a program, you must declare a variable to reference the array and specify
the arrays
. Here is the syntax for declaring an array variable:
TheelementTypecan be any data type, and all elements in the array will have the same data
type. For example, the following code declares a variable
NoteYou can also use
elementTypearrayRefVar[]
to declare an array variable. This style comes
from the C language and was adopted in Java to accommodate C programmers. The style
elementType[]arrayRefVar
is preferred.
6.2.2Creating Arrays
Unlike declarations for primitive data type variables, the declaration of an array variable does
not allocate any space in memory for the array. It creates only a storage location for the refer-
ence to an array. If a variable does not contain a reference to an array, the value of the variable
. You cannot assign elements to an array unless it has already been created. After an
array variable is declared, you can create an array by using the
operator with the follow-
This statement does two things: (1) it creates an array using
newelementType[array-
; (2) it assigns the reference of the newly created array to the variable
Declaring an array variable, creating an array, and assigning the reference of the array to
the variable can be combined in one statement, as shown below:
orelementType arrayRefVar[] = newelementType[arraySize];Here is an example of such a statement:
newdouble
10];This statement declares an array variable,
. To assign values to the elements, use the
For example, the following code initializes the array.
Chapter 6Single-Dimensional Arrays
array vs. array variable
default values
indexed variables
[] myList =
new double
[
10
];
myList
Array reference
variable
Array element at
index
5
13.2
4.0
34.33
34.0
45.45
99.993
11123
6.1
4] = 4.0;myList[5] = 34.33;myList[6] = 34.0;myList[7] = 45.45;myList[8] = 99.993;myList[9] = 11123;The array is pictured in Figure 6.1.NoteAn array variable that appears to hold an array actually contains a reference to that array. Strictly
speaking, an array variable and an array are different, but most of the time the distinction can be
ignored. Thus it is all right to say, for simplicity, that
is an array, instead of stating, at greater
is a variable that contains a reference to an array of ten double elements.
6.2.3Array Size and Default Values
When space for an array is allocated, the array size must be given, specifying the number of ele-
. For example,
When an array is created, its elements are assigned the default value of
primitive data types,
6.2.4Array Indexed Variables
The array elements are accessed through the index. Array indices are
based; that is, they
. In the example in Figure 6.1,
values, and the indices are from
Each element in the array is represented using the following syntax, known as an
indexed
For example,
represents the last element in the array myList.CautionSome languages use parentheses to reference an array element, as in
. But Java uses
brackets, as in
6.2Array Basics
After an array is created, an indexed variable can be used in the same way as a regular variable.
For example, the following code adds the values in
andmyList[1]tomyList[2].myList[2] = myList[0] + myList[1];The following loop assigns
,1tomyList[1], and 9tomyList[9]:for(inti = 0; i myList.length; i++) {myList[i] = i;}6.2.5Array Initializers
Java has a shorthand notation, known as the
array initializer
ment declaring an array, creating an array, and initializing, using the following syntax:
k};For example,
1.9,2.9,3.4,3.5};This statement declares, creates, and initializes the array myListwith four elements, which isequivalent to the statements shown below:
new double[4];myList[0] = 1.9;myList[1] = 2.9;myList[2] = 3.4;myList[3] = 3.5;CautionThenewoperator is not used in the array-initializer syntax. Using an array initializer, you have to
declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error.
Thus the next statement is wrong:
myList = {1.9,2.9,3.4,3.5};6.2.6Processing Arrays
loopfor two reasons:
All of the elements in an array are of the same type. They are evenly processed in the
same fashion repeatedly using a loop.
Since the size of the array is known, it is natural to use a
Assume the array is created as follows:
newdouble
10];Here are some examples of processing arrays:
1.(
Initializing arrays with input values
) The following loop initializes the array
with user input values.
,
Chapter 6Single-Dimensional Arrays
2.(
Initializing arrays with random values
) The following loop initializes the array
.
Video Note
Random shuffling
6.2Array Basics
off-by-one error
myList
i
[1]
(
int
i =
0
; i myList.length; i++) {
// Generate an index j randomly
index = (
int
) (Math.random()
* mylist.length);
// Swap myList[i] with myList[j]
temp = myList[i];
myList[i] = myList[index]
A random index
[index]
temp = myList[
0
];
8.(
Chapter 6Single-Dimensional Arrays
false
false
.
false
isCovered
[0]
(a)
[97]
false
false
.
false
isCovered
[0]
(b)
[97]
truetruetrue
false
.
false
isCovered
[0]
(d)
[97]
.
false
isCovered
[0]
(e)
[97]
Video Note
Lotto numbers
6.3Problem: Lotto Numbers
mark number covered
isCovered[3-1]
Chapter 6Single-Dimensional Arrays
lineRepresentative elements in array isCovered numberallCovered
[1][2][3][4][5][22][42]
6falsefalsefalsefalsefalsefalsefalse
11true
125
11true
126
11true
125
11true
124
11true
123
11true
1223
11true
1243
11true
122
11true
120
16true
18(i=0)false
6.4Problem: Deck of Cards
.
12
.
25
.
38
.
51
0
.
12
.
25
.
38
.
51
deck
.
[12]
.
[25]
.
[38]
.
[51]
Random shuffle
6
48
.
deck
[1]
[4]
.
[25]
.
[38]
.
[51]
Card number 6 is
Card number 48 is
Card number 24 is
shuffle deck
DeckOfCards {
main(String[] args) {
new int
];
"Spades"
"Ace"
6
i =
10 deck[i] = i;
// Shuffle the cards
13
i =
14
// Generate an index randomly
15
16
17 deck[i] = deck[index];
// Display the first four cards
22
i =
23 String suit = suits[deck[i] /
];
];
"Card number "
+ deck[i] +
+ suit);
27 }
Chapter 6Single-Dimensional Arrays
copy reference
of
list1
of
list1
of
list2
of
list2
list1
the assignment
list2 = list1;
list1
After
the assignment
list2 = list1;
The program defines an array
is initialized with values
in lines 910. A deck value
Lines 1319 randomly shuffle the deck. After a deck is shuffled,
contains anarbitrary value.
deck[i]/13
6.6Passing Arrays to Methods
Chapter 6Single-Dimensional Arrays
Space required for the
int
values is
Arrays are
The primitive type value in
and the reference value in
You will see that after
is invoked,
, but
is5555. This is because yandnumbers, although they are independent variables, reference to the same array, as illustrated
m(x,y)
is invoked, the values of
contains the reference value to the array,
now contains the same
reference value to the same array.
The JVM stores the array in an area of memory called the
, which is used for dynamic mem-
ory allocation where blocks of memory are allocated and freed in an arbitrary order.
6.6.1Passing Array Arguments
Take the following code, for example:
)intx = 1;// x represents an int valueint[] y = newint
int
6.6Passing Arrays to Methods
false swap
swap array elements
n1,
int
n2)
,
2
As shown in Figure 6.6, the two elements are not swapped using the
Chapter 6Single-Dimensional Arrays
swap(int n1, int n2)
.
The primitive type values in
and
a[1]
are passed to the
swap
StackHeap
: 1
a[1]
: 2
public static int
[] reverse(
int
[] list) {
2
int
[] result =
new int
[list.length];
3
for
(
int
i =
0
, j = result.length -
1
;
5 i list.length; i++, j--) {
result
Line 2 creates a new array
. Lines 47 copy elements from array
6.7Returning an Array from a Method
chars[0]


chars[98]
counts[1]counts[24]counts[25](a)(b)
The
Chapter 6Single-Dimensional Arrays
);
6.8Variable-Length Argument Lists
pass variable-length arg list
(a) Executing
createArray
in line 5
(b) After exiting
createArray
in line 5
Heap
Space required for the
StackHeap
(a) An array of 100 characters is created when executing
Chapter 6Single-Dimensional Arrays
printMax() {
... numbers
new double
,
2
,
3
for i = 0, 1, [0][1][2]
public class
LinearSearch {
2
for
(
int
i =
0
; i list.length; i++) {
5
if
(key == list[i])
6
pass an array arg
a variable-length arg
6.9Searching Arrays
array before finding the key, if it exists. Since the execution time of a linear search increases
linearly as the number of array elements increases, linear search is inefficient for a large array.
6.9.2The Binary Search Approach
Binary search is the other common search approach for a list of values. For binary search to
work, the elements in the array must already be ordered. Assume that the array is in ascend-
ing order. The binary search first compares the key with the element in the middle of the array.
Consider the following three cases:
If the key is less than the middle element, you need to continue to search for the key
only in the first half of the array.
If the key is equal to the middle element, the search ends with a match.
If the key is greater than the middle element, you need to continue to search for the
key only in the second half of the array.
[0][1][2][3][4][5][7][8][9][10][11]
47101145
596066697079
[6]
[12]
[0][1][2][3][4][5]
list4
101145
[3][4][5]
lowmid
comparison.
Chapter 6Single-Dimensional Arrays
6.10
keylist[mid]
;
first half
binarySearch(
;
;
;
high = mid -
;
(key == list[mid])
(a) Version 1(b) Version 2
6.10Sorting Arrays
Low
6
1
1
2
binary search benefits
Video Note
Selection sort
Chapter 6Single-Dimensional Arrays
The solution can be described as follows:
i =
swap
6.10Sorting Arrays
9
5
swap
5
4
8
1
6
Select 2 (the smallest) and swap it
swap
6.11
Selection sort repeatedly selects the smallest number and swaps it with the first number in the list.
9
5
4
8
1
6
6.12
Insertion sort repeatedly inserts a new element into a sorted sublist.
Chapter 6Single-Dimensional Arrays
[0][1][2][3][4][5][6]
[0][1][2][3][4][5][6]
259
tolist[3][0][1][2][3][4][5][6]
259
tolist[2][0][1][2][3][4][5][6]
6.13
A new element is inserted into a sorted sublist.
Toinsert
intolist[0..i-1], save
into a temporary variable, say
. Move
tolist[i]iflist[i-1]�currentElement
move
tolist[i-1]iflist[i-2]�currentElement
list[i-k]=currentElement
(we pass the first element of the sorted list).
. For example, to insert
in Figure 6.13, move
(9) to list[3]since�94, move
(5) to list[2]since�54. Finally, move
.The algorithm can be expanded and implemented as in Listing 6.9.
tolist[i]. The inner loop (with the loop control variable
6.11The
6.11The
,
3
,
8
)
)
));
,
3
Chapter 6Single-Dimensional Arrays
anonymous array209
array198
array initializer201
binary search216
garbage collection208
index198
indexed variable200
insertion sort219
linear search216
selection sort219
UMMARY
A variable is declared as an array type using the syntax
elementType[]arrayRef-
. The style elementType[]arrayRefVar
elementTypearrayRefVar[]
is legal.
Unlike declarations for primitive data type variables, the declaration of an array vari-
able does not allocate any space in memory for the array. An array variable is not a
primitive data type variable. An array variable contains a reference to an array.
You cannot assign elements to an array unless it has already been created. You can
operator with the following syntax:
newelement-
.4.Each element in the array is represented using the syntax arrayRefVar[index]. Anindex must be an integer or an integer expression.
. Since the index of an array always begins with
index is always
arrayRefVar.length-1
attempt to reference elements beyond the bounds of an array.
Programmers often mistakenly reference the first element in an array with index
, but
index off-by-one error
When an array is created, its elements are assigned the default value of
numeric primitive data types,
Java has a shorthand notation, known as the
array initializer
statement declaring an array, creating an array, and initializing, using the syntax:
elementType[]arrayRefVar={value0,value1,...,value
UESTIONS
6.1
How do you declare and create an array?
How do you access elements of an array?
Review Questions
cated for an array? What is the printout of the following code?
new int[x];x = 60;System.out.println("x is "+ x);System.out.println("The size of numbers is "+ numbers.length);6.4Indicate true or false for the following statements:
Every element in an array has the same type.
The array size is fixed after it is declared.
The array size is fixed after it is created.
The elements in an array must be of primitive data type.
Which of the following statements are valid array declarations?
new double[30];char[] r = new char(1..30);inti[] = (3,4,3,2);floatf[] = {2.3,4.5,6.6};char[] c = new char();6.6What is the array index type? What is the lowest index? What is the representation
Write statements to do the following:
a.Create an array to hold
double values.
b.Assign value
to the last element in the array.
c.Display the sum of the first two elements.
d.Write a loop that computes the sum of all elements in the array.
e.Write a loop that finds the minimum element in the array.
f.Randomly generate an index and display the element of this index in the array.
g.Use an array initializer to create another array with initial values
invalid index?
Identify and fix the errors in the following code:
)3double[100] r;45for(inti = 0; i r.length(); i++);6 r(i) = Math.random * 100;7 }8 }Section 6.36.10
Chapter 6Single-Dimensional Arrays
6.11
Once an array is created, its size cannot be changed. Does the following code
myList = new int[10];// Some time later you want to assign a new array to myListmyList = new int[20];Sections 6.46.76.12
System.out.print(list[i] +
newList[i] = list[list.length -
}
6.14
Where are the arrays stored during execution? Show the contents of the stack and
heap during and after executing
Programming Exercises
6.18
Use Figure 6.11as an example to show how to apply the selection-sort approach to
6.19
Use Figure 6.12as an example to show how to apply the insertion-sort approach to
How do you modify the
ROGRAMMING
6.1*
Assigning grades
Reversing the numbers entered
) Write a program that reads ten integers and dis-
plays them in the reverse of the order in which they were read.
Counting occurrence of numbers
) Write a program that reads the integers
Chapter 6Single-Dimensional Arrays
Revising Listing 4.14, PrimeNumber.java
Note that if a number occurs more than one time, the plural word times is used
Analyzing scores
) Write a program that reads an unspecified number of scores
Programming Exercises
Write a test program that prompts the user to enter ten numbers, invokes this
6.12*
Reversing an array
=
x
x
Q
a
i
=
1
x
-
1
Chapter 6Single-Dimensional Arrays
6.16
integers and a key. Estimate the execution time of invoking the
6.17*
Revising selection sort
) In 6.10.1, you used selection sort to sort an array.
Programming Exercises
(a)(b)(c)
6.14
Each ball takes a random path and falls into a slot.
of balls in a slot. Each ball falls into a slot via a path. The number of Rs in a
path is the position of the slot where the ball falls. For example, for the path
output is shown below:
Game: bean machine
) The bean machine, also known as a quincunx or the Gal-
ton box, is a device for statistic experiments named after English scientist Sir
Francis Galton. It consists of an upright board with evenly spaced nails (or pegs)
in a triangular form, as shown in Figure 6.14.
Balls are dropped from the opening of the board. Every time a ball hits a nail, it
has a 50% chance of falling to the left or to the right. The piles of balls are accu-
Write a program that simulates the bean machine. Your program should
the machine. Simulate the falling of each ball by printing its path. For example,
the path for the ball in Figure 6.14(b)is LLRRLLR and the path for the ball in
Figure 6.14(c)is RLRRLRR. Display the final buildup of the balls in the slots in
Chapter 6Single-Dimensional Arrays
LRLRLRR, the ball falls into
, and for the path is RRLLLLL, the ballfalls into
.)6.22***(Game: multiple Eight Queens solutions)Exercise 6.20 finds one solution for
Game: locker puzzle
) A school has 100 lockers and 100 students. All lockers
are closed on the first day of school. As the students enter, the first student,
denoted S1, opens every locker. Then the second student, S2, begins with the
second locker, denoted L2, and closes every other locker. Student S3 begins
with the third locker and changes every third locker (closes it if it was open, and
opens it if it was closed). Student S4 begins with locker L4 and changes every
fourth locker. Student S5 starts with L5 and changes every fifth locker, and so
After all the students have passed through the building and changed the lock-
ers, which lockers are open? Write a program to find your answer.
100boolean
Video Note
Coupon collectors
problem
Programming Exercises
Identical arrays
) Two arrays
if they have the
integers
and displays all combinations of picking two numbers from the
Game: picking four cards
, respectively. Your program should display the number of picks that
Pattern recognition: consecutive four equal numbers
) Write the following
ULTIDIMENSIONAL
RRAYS
Objectives
To give examples of representing data using two-dimensional arrays (7.1).
To declare variables for two-dimensional arrays, create arrays, and access array elements
in a two-dimensional array using row and column indexes (7.2).
To program common operations for two-dimensional arrays
(displaying arrays, summing all elements, finding min and
max elements, and random shuffling) (7.3).
Chapter 7Multidimensional Arrays
7.1Introduction
The preceding chapter introduced how to use one-dimensional arrays to store linear collec-
tions of elements. You can use a two-dimensional array to store a matrix or a table. For exam-
Distance Table (in miles)
New York
Atlanta
New York
7.2Two-Dimensional Array Basics
It is a common mistake to use
to access the element at row
Java, each subscript must be enclosed in a pair of square brackets.
You can also use an array initializer to declare, create, and initialize a two-dimensional
array. For example, the following code in (a) creates an array with the specified initial values,
as shown in Figure 7.1(c). This is equivalent to the code in (b).
[3]
[2]
[1]
[0]
[4]
[3]
[2]
[1]
[0]
[2]
[1]
[0]
[2][1][0]1
matrix = new int[5][5];matrix[2][1] = 7;
101112
{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};(a)(b)(c)
7.1
The index of each subscript of a two-dimensional array is an
value, starting
new int
4
;
;
;
10
11
12
7.2.2Obtaining the Lengths of Two-Dimensional Arrays
A two-dimensional array is actually an array in which each element is a one-dimensional
array. The length of an array
is the number of elements in the array, which can be obtained
,x[1], and x[x.length-1]are arrays. Their lengths can beobtained using x[0].length,x[1].length, and x[x.length-1].length.For example, suppose
,x[0],x[1], and x[2]are one-dimensionalarrays and each contains four elements, as shown in Figure 7.2.
x[0][0]x[0][1]x[0][3]
x[1][0]x[1][1]x[1][2]x[1][3]
x[2][0]x[2][1]x[2][2]x[2][3]
is 4x[1].length is
7.2
A two-dimensional array is a one-dimensional array in which each element is
another one-dimensional array.
Chapter 7Multidimensional Arrays
is 5, triangleArray[1].lengthis4,triangleArray[2].lengthis 3, triangleArray[3].lengthis 2, andtriangleArray[4].lengthis 1.If you dont know the values in a ragged array in advance, but know the sizes, say the same
as before, you can create a ragged array using the syntax that follows:
;triangleArray[0] = new int[5];triangleArray[1] = new int[4];triangleArray[2] = new int[3];triangleArray[3] = new int[2];triangleArray[4] = new int[1];You can now assign values to the array. For example,
0][3] = 50;triangleArray[4][0] = 45;NoteThe syntax
for creating an array requires the first index to be specified. The syn-
tax
would be wrong.
7.3Processing Two-Dimensional Arrays
is created as follows:
new int[10][10];Here are some examples of processing two-dimensional arrays:
1.(
Initializing arrays with input values
) The following loop initializes the array with user
input values:
)for(introw = 0; row ; row++) {
; column ; column++) {
()}}2.(
Initializing arrays with random values
) The following loop initializes the array with
5
,
2
,
3
,
4
,
5
},
,
3
,
4
,
5
},
,
4
,
5
},
,
5
},
}
};
7.2.3Ragged Arrays
Each row in a two-dimensional array is itself an array. Thus the rows can have different lengths.
An array of this kind is known as a
ragged array
. Here is an example of creating a ragged array:
7.3Processing Two-Dimensional Arrays
(int)(Math.random() * 100);}}3.(
Printing arrays
) To print a two-dimensional array, you have to print each element in
the array using a loop like the following:
; row ; row++) {
; column ; column++) {
" ");}System.out.println();}4.(
) Use a variable named
using a loop like this:
)total += matrix[row][column];}}5.(
) For each column, use a variable named
using a loop like this:
0].length; column++) {inttotal = 0;for(introw = 0; row matrix.length; row++)total += matrix[row][column];System.out.println("Sum for column "+ column + " is "+total);}6.(
Which row has the largest sum?
) Use variables
the largest sum and index of the row. For each row, compute its sum and update
if the new sum is greater.
Video Note
find the row with the
largest sum
Chapter 7Multidimensional Arrays
7.(
Random shuffling
) Shuffling the elements in a one-dimensional array was introduced in
6.2.6. How do you shuffle all the elements in a two-dimensional array? To accomplish
, randomly generate indices i1andj1and swap
withmatrix[i1][j1], as follows:
7.5Problem: Grading a Multiple-Choice Test
of rows using
(line 22) and the number of columns in a specified row using
(line 23). 7.5Problem: Grading a Multiple-Choice Test
students and ten questions, and the answers are stored in a two-dimensional array. Each row
records a students answers to the questions, as shown in the following array.
Student 0A B A C C D E E A D
Student 1D B A B C A E E A D
Student 2E D D A C B E E A D
Student 3C B A E D C E E A D
Student 4A B D C C D E E A D
Student 5B B E C C D E E A D
Student 6B B A C C D E E A D
Student 7E B E C C D E E A D
The key is stored in a one-dimensional array:
Key to the Questions:
Your program grades the test and displays the result. It compares each students answers with
the key, counts the number of correct answers, and displays it. Listing 7.2 gives the program.
7.2
}};
},
},
},
},
},
},
},
Video Note
Grade multiple-choice test
Chapter 7Multidimensional Arrays
; ; i++) {
; ; j++) {
'D','B','D','C','C','D','A','E','A','D'};1-D arraycompare with key
The statement in lines 513 declares, creates, and initializes a two-dimensional array of char-
type.The statement in line 16 declares, creates, and initializes an array of charvalues and
type.Each row in the array
stores a students answer, which is graded by comparing it with
the key in the array
. The result is displayed immediately after a students answer is graded.
7.6Problem: Finding a Closest Pair
The GPS navigation system is becoming increasingly popular. The system uses the graph and
13
11
20.5
21
70.5
7.3
Points can be represented in a two-dimensional array.
7.6Problem: Finding a Closest Pair
i =
shortestDistance = distance(points[p1][
;
new double[numberOfPoints][2];number of points2-D arrayread pointstrack two points
Chapter 7Multidimensional Arrays
from the console and stored in a two-dimensional array named
program uses variable
1
x
x
1
y
y
input file
fixed cells
537
6195
986
483
6
1
7
8
4
5
3
7
9
6
9
7.4
The Sudoku puzzle in (a) is solved in (b).
Video Note
7.7Problem: Sudoku
For convenience, we use value
to indicate a free cell, as shown in Figure 7.5(a). The grid
can be naturally represented using a two-dimensional array, as shown in Figure 7.5(a).
To find a solution for the puzzle we must replace each
. For the solution in Figure 7.4(b), the grid should be as shown in Figure 7.6.
53000000
000
986
483
(a)(b)
{{
};
7.5
A grid can be represented using a two-dimensional array.
{{
};
7.6
A simplified version of the Sudoku problem is to check the validity of a solution. The pro-
[][] readASolution() {
()read inputsolution valid?
Chapter 7Multidimensional Arrays
new int[9];37for(inti = 0; i 9; i++) {38 column[i] = grid[i][j];39 }4041if()
i =
j =
i =
)check solutioncheck rows
check small boxes
all valid
copy of array
7.7Problem: Sudoku
)
The program invokes the
grid[6][3]
The location of the starting cell for
grid[0][0]
7.7
Chapter 7Multidimensional Arrays
With this observation, you can easily identify all the cells in the box. Suppose
is the starting cell of a box. The cells in the box can be traversed in a
nested loop as follows:
7.8Multidimensional Arrays
Note that the lines in the file are not necessary in order. For example, the file may appear
as shown in (b).
Your task is to write a program that calculates the average daily temperature and humidity
days. You can use the input redirection to read the file and store the data in a three-
dimensional array, named
. The first index of
days, the second index ranges from
hours, and the third index
and represents temperature and humidity, respectively. Note that the days
in the file. Since the array index starts from
stores the temperature in day 1at hour 1anddata[9][23][1]storesthe humidity in day 10at hour 24.The program is given in Listing 7.5.
7.5
[NUMBER_OF_DAYS][NUMBER_OF_HOURS][
[][][] data
Chapter 7Multidimensional Arrays
You can use the following command to run the program:
in lines 1219 reads the input to the array. You can enter the input from the keyboard, but doing
so will be awkward. For convenience, we store the data in a file and use the input redirection to
read the data from the file. The loop in lines 2427 adds all temperatures for each hour in a day
Review Questions
45 day += ;
UMMARY
A two-dimensional array can be used to store a table.
A variable for two-dimensional arrays can be declared using the syntax:
elementType[][]arrayVar
A two-dimensional array can be created using the syntax:
newelementType-
.4.Each element in a two-dimensional array is represented using the syntax:
5.You can create and initialize a two-dimensional array using an array initializer with the
elementType[][]arrayVar={{row values},...,{row values}}
You can use arrays of arrays to form multidimensional arrays. For example, a vari-
arrayVarand a three-dimensional array can be created using newelement-
UESTIONS
7.1
5int
7.2
Can the rows in a two-dimensional array have different lengths?
7.3
What is the output of the following code?
new int[5][6];int[] x = {1,2};array[0] = x;System.out.println("array[0][1] is "+ array[0][1]);7.4
Which of the following statements are valid array declarations?
]
Chapter 7Multidimensional Arrays
7.5
ROGRAMMING
7.1*
Summing all the numbers in a matrix
7.2*
Summing the major diagonal in a matrix
7.3*
Sorting students on grades
) Rewrite Listing 7.2, GradeExam.java, to display the
7.4**
Computing the weekly hours for each employee
employees are stored in a two-dimensional array. Each row records an employees
seven-day work hours with seven columns. For example, the array shown below
stores the work hours for eight employees. Write a program that displays employ-
Programming Exercises
1.0 2.0 3.0 0.0 2.0 4.0 1.0 4.0 7.0
7.0 8.0 9.0 1.1 4.3 5.2 8.1 12.3 14.2
7.6**
Algebra: multiplying two matrices
SuMTWHFSa
7.5
Algebra: adding two matrices
Video Note
Multiply two matrices
Chapter 7Multidimensional Arrays
1 2 3 0 2.0 4.0 5.3 23.9 24
7.7*
Points nearest to each other
) Listing 7.3 gives a program that finds two points in
a two-dimensional space nearest to each other. Revise the program so that it finds
two points in a three-dimensional space nearest to each other. Use a two-dimen-
sional array to represent the points. Test the program using the following points:
Programming Exercises
7.10*
Game: TicTacToe board
) Write a program that randomly fills in 0s and 1s into a
TicTacToe board, prints the board, and finds the rows, columns, or diagonals with
all 0s or 1s. Use a two-dimensional array to represent a TicTacToe board. Here is a
7.11**
) Nine coins are placed in a 3-by-3matrix with some
face up and some face down. You can represent the state of the coins using a 3-by-3
matrix with values
(tail). Here are some examples:
Each state can also be represented using a binary number. For example, the pre-
7.12**
Financial application: computing tax
Chapter 7Multidimensional Arrays
and (400,000 372,950) at 36%. The six rates are the same for all filing statuses,
which can be represented in the following array:
7.14**
matrix, randomly fills in
s into the matrix, prints the matrix, and finds the rows,
Programming Exercises
7.15*
100.5
125
85
40
75
175
125
125
125
320.5
181
25
75
7.8
Banks lend money to each other.
Chapter 7Multidimensional Arrays
0 1 0 3 1 6 1
7.20***
) Connect four is a two-player board game in which the
players alternately drop colored disks into a seven-column, six-row vertically-
suspended grid, as shown below.
Programming Exercises
7.21***
The objective of the game is to connect four same-colored disks in a row, a col-
umn, or a diagonal before your opponent can do likewise. The program prompts
two players to drop a RED or YELLOW disk alternately. Whenever a disk is
Chapter 7Multidimensional Arrays
7.23*
Algebra: matrix inverse
) The inverse of a square matrix
s on the diagonal
on all other cells. The inverse of matrix for example, is
The inverse of a matrix
121
231
20.50.5
10.5
1.50.5
100
001
20.50.5
10.5
1.50.5
121
231
The inverse of a matrix
can be obtained using the following formula:
[][] inverse(
double
[][] A)
-
b
-
*
2
Programming Exercises
can be obtained using the following formula if
Implement the following function to obtain an inverse of the matrix:
A

C
a
a
a
a
a
a
a
a
a
a

A

Z
0
:
BJECTSAND
LASSES
Objectives
To describe objects and classes, and use classes to model objects (8.2).
To use UML graphical notations to describe classes and objects (8.2).
To demonstrate defining classes and creating objects (8.3).
To create objects using constructors (8.4).
To access objects via object reference variables (8.5).
To define a reference variable using a reference type (8.5.1).
Chapter 8Objects and Classes
8.1Introduction
Having learned the material in earlier chapters, you are able to solve many programming prob-
ButtonLabelText FieldCheck BoxRadio Button
8.1
radius is _____
radius is
radius is
radius is
class
8.2Defining Classes for Objects
Circle {
/** The radius of this circle */
radius =
1.0
;
/** Construct a circle object */
Circle() {
/** Construct a circle object */
Circle(
double
newRadius) {
radius = newRadius;
A class is a construct that defines objects of the same type.
radius: double
radius = 25
circle3: Circle
radius = 125
circle1: Circle
radius = 10
Chapter 8Objects and Classes
8.3Example: Defining Classes and Creating Objects
This section gives two examples of defining classes and uses the classes to create objects.
Listing 8.1 is a program that defines the
class and uses it to create objects. To avoid a
naming conflict with several improved versions of the
class in this example is named
display its new radius and area.
8.1
double
newRadius)
radius
);
);
8.3Example: Defining Classes and Creating Objects
The program contains two classes. The first of these,
of the class. When you run the program, the Java runtime system
invokes the
main(String[] args) {
Circle1
client
Chapter 8Objects and Classes
28 {
33 {
double
newRadius)
TV() {
on =
false
;
;
data field
no-arg constructor
The current channel (1 to 120) of this TV.
8.3Example: Defining Classes and Creating Objects
Note that the channel and volume level are not changed if the TV is not on. Before either of
these is changed, its current value is checked to ensure that it is within the correct range.
Listing 8.4 gives a program that uses the
class to create two objects.
volumeDown() {
volumeUp() {
channelDown() {
channelUp() {
turnOff() {
turn off TV
Chapter 8Objects and Classes
"tv2's channel is "
+ tv2.channel
17 +
" and volume level is "
+ tv2.volumeLevel);
18 }
constructors name
8.5Accessing Objects via Reference Variables
8.5.1Reference Variables and Reference Types
reference variables
Such variables are declared using the following syntax:
A class is essentially a programmer-defined type. A class is a
reference type
that a variable of the class type can reference an instance of the class. The following statement
declares the variable
The variable
object. The next statement creates an object
Using the syntax shown below, you can write a single statement that combines the declaration
of an object reference variable, the creation of an object, and the assigning of an object refer-
ence to the variable.
Here is an example:
The variable
An object reference variable that appears to hold an object actually contains a reference to that
object. Strictly speaking, an object reference variable and an object are different, but most of the
time the distinction can be ignored. So it is fine, for simplicity, to say that
object rather than use the longer-winded description that
contains a reference to a
Arrays are treated as objects in Java. Arrays are created using the
operator. An array variable
is actually a variable that contains a reference to an array.
reference variable
variable
instance variable
Chapter 8Objects and Classes
Recall that you use
8.5Accessing Objects via Reference Variables
is a common runtime error. It occurs when you invoke a method on
a reference variable with
value. Make sure you assign an object reference to the variable
before invoking the method through the reference variable.
x;
int i
= 1
Circle c
i
Object type
c
reference
Created using new
Circle()
A variable of a primitive type holds a value of the primitive type, and a variable
of a reference type holds a reference to where an object is stored in memory.
Before:After:
i
i
Primitive variable
is copied to variable
Chapter 8Objects and Classes
As shown in Figure 8.8, after the assignment statement
referenced by
. The object previously referenced by
is no longer useful and therefore is now
known as
garbage
. Garbage occupies memory space. The Java runtime system detects garbage
and automatically reclaims the space it occupies. This process is called
garbage collection
Tip
If you know that an object is no longer needed, you can explicitly assign
to a reference vari-
able for the object. The JVM will automatically collect the space if the object is not referenced by
any reference variable.
8.6Using Classes from the Java Library
Listing 8.1 defined the
class and created objects from the class. You will frequently
use the classes in the Java library to develop programs. This section gives some examples of
the classes in the Java library.
8.6.1The
In Listing 2.8, ShowCurrentTime.java, you learned how to obtain the current time using
. You used the division and remainder operators to extract
current second, minute, and hour. Java provides a system-independent encapsulation of date
class, as shown in Figure 8.9.
c1 = c2
c1
After:
c2
Before:
c1
c2
Reference variable
is copied to variable
+Date()
object represents a specific date and time.
You can use the no-arg constructor in the
8.6Using Classes from the Java Library
java.util.Date date = ;
System.out.println();
displays the output like this:
class has another constructor,
8.10
object can be used to generate random values.
object, you have to specify a seed or use the default seed. The
no-arg constructor creates a
object using the current elapsed time as its seed. If two
objects have the same seed, they will generate identical sequences of numbers. For
example, the following code creates two
values:
The ability to generate the same sequence of random values is useful in software testing and
many other applications. In software testing, you can test your program using a fixed sequence of
numbers before using different sequences of random numbers.
Chapter 8Objects and Classes
8.6.3Displaying GUI Components
Pedagogical Note
Graphical user interface (GUI) components are good examples for teaching OOP. Simple GUI
examples are introduced for this purpose. The full introduction to GUI programming begins with
Chapter 12, GUI Basics.
When you develop programs to create graphical user interfaces, you will use Java
frames, buttons, radio buttons, combo boxes, lists, and so on. Listing 8.5 is an example
that creates two windows using the
class. The output of the program is shown in
8.11
The program creates two windows using the
8.6Using Classes from the Java Library
publicclass
publicstaticvoid
)5// Create a button with text OK 6 JButton jbtOK = newJButton("OK");78// Create a button with text Cancel 9 JButton jbtCancel = newJButton("Cancel");1011// Create a label with text "Enter your name: "12 JLabel jlblName = newJLabel("Enter your name: ");1314// Create a text field with text "Type Name Here"15 JTextField jtfName = newJTextField("Type Name Here");1617// Create a check box with text bold18 JCheckBox jchkBold = newJCheckBox("Bold");1920// Create a check box with text italic21 JCheckBox jchkItalic = newJCheckBox("Italic");2223// Create a radio button with text red24 JRadioButton jrbRed = newJRadioButton("Red");2526// Create a radio button with text yellow27 JRadioButton jrbYellow = newJRadioButton("Yellow");2829// Create a combo box with several choices30 JComboBox jcboColor = newJComboBox(newString[]{"Freshman",31"Sophomore","Junior","Senior"});3233// Create a panel to group components34 JPanel panel = newJPanel();35 panel.add(jbtOK); // Add the OK button to the panel36 panel.add(jbtCancel); // Add the Cancel button to the panel37 panel.add(jlblName); // Add the label to the panel38 panel.add(jtfName); // Add the text field to the panel39 panel.add(jchkBold); // Add the check box to the panel40 panel.add(jchkItalic); // Add the check box to the panel41 panel.add(jrbRed); // Add the radio button to the panel42 panel.add(jrbYellow); // Add the radio button to the panel43 panel.add(jcboColor); // Add the combo box to the panel4445 JFrameframe =
Video Note
Chapter 8Objects and Classes
Memory
instantiate
Circle
Circle
Objects were created,
8.12
Instance variables belong to the instances and have memory storage independent of one another. Static
variables are shared by all the instances of the same class.
radio button, and combo box (lines 3543). The program then creates a frame and adds the
instance variable
static variable
Video Note
static vs. instance
8.7Static Variables, Constants, and Methods
The new circle class, named
static variable
Chapter 8Objects and Classes
15 +
"c1: radius("
27 +
30 +
;
instance variable
static variable
static variable
static variable
, the Java compiler automatically compiles
8.7Static Variables, Constants, and Methods
result *= i;
;
result *= i;
(a) Wrong design (b) Correct design
Chapter 8Objects and Classes
8.8Visibility Modifiers
You can use the
int
y;
m1() {
m3() {
}
void
void
8.13
The private modifier restricts access to its defining class, the default modifier restricts access to a package,
and the public modifier enables unrestricted access.
If a class is not defined public, it can be accessed only within the same package. As shown
but not from
class C2 {
can access C1
8.14
8.9Data Field Encapsulation
class. As shown in Figure 8.15(b), an object
class cannot access its private
class. As shown in Figure 8.15(a), an object
class can access its private members, because
is defined inside its own class.
Foo {
private boolean
x;
public static void
main(String[] args) {
Foo foo =
new
Foo();
System.out.println(foo.x);
private int
convert() {
foo
is used inside the
Foo
class
x
and
convert
are private in
Foo
.
8.15
An object can access its private members if it is defined in its own class.
modifier applies only to the members of a class. The
modifier can apply
to a class or members of a class. Using modifiers
on local variables would
cause a compile error.
In most cases, the constructor should be public. However, if you want to prohibit the user from
creating an instance of a class, use a private constructor. For example, there is no reason to create
an instance from the
class, because all of its data fields and methods are static. To prevent
the user from creating objects from the
class, the constructor in
defined as follows:
8.9Data Field Encapsulation
The data fields
modified directly (e.g.,
myCircle.radius=5
Circle2.numberOfObjects=10
This is not a good practicefor two reasons:
First, data may be tampered with. For example,
private constructor
data field encapsulation
Video Note
Data field encapsulation
Chapter 8Objects and Classes
data field accessible, provide a
get
Circle
8.16
numberOfObjects =
;
radius =
;
8.9Data Field Encapsulation
Chapter 8Objects and Classes
To prevent data from being tampered with and to make the class easy to maintain, declare data
fields private.
pass-by-value
8.11Array of Objects
1.03.141592653589793
2.012.566370614359172
3.029.274333882308138
4.050.26548245743669
5.079.53981633974483
class is defined in Listing 8.9. The program passes a
and an integer value from
to invoke
, as shown in the sample output.
Circle
object
Pass-by-value
Pass-by-value (here
When passing an argument of a primitive data type, the value of the argument is passed. In
this case, the value of
Chapter 8Objects and Classes
array of reference variables
. So, invoking
circleArray[9]
reference
object 0
object 1
object 9
circleArray
8.18
When an array of objects is created using the
operator, each element in the array is a refer-
ence variable with a default value of
Listing 8.12 gives an example that demonstrates how to use an array of objects. The program
composed of five
objects; it then initializes circle radii with random values and dis-
plays the total area of the circles in the array.
8.12
Key Terms
38 );
70.577708 15648.941866
5.680718 101.380949
36.734246 4239.280350
The program invokes
(line 8) to create an array of five
objects. Several
classes were introduced in this chapter. This example uses the
class introduced in 8.9, Data Field Encapsulation.
Chapter 8Objects and Classes
UMMARY
A class is a template for objects. It defines the properties of objects and provides con-
UESTIONS
8.1
Review Questions
What is wrong in the following code?
)3 A a = newA();4 a.print();5 }6 }78classA {9 String s;1011 A(String s) {12this.s = s;13 }1415public void print() {16 System.out.print(s);17 }18 }8.6What is the printout of the following code?
)Foo foo = newFoo();System.out.println(foo.x);}}Section 8.68.7How do you create a
for the current time? How do you display the current
How do you create a
(a)(b)
8
Chapter 8Objects and Classes
8.10
8.11
keyword in the place of
publicvoid
)...}publicint
Review Questions
8.13
Count myCount =
increment(myCount, times);
System.out.println(
System.out.println(
c.count++;
}
public
Count(
Count() {
count =
}
}
8.17
Show the output of the following program:
Chapter 8Objects and Classes
8.18
Show the printout of the following code:
T t1 =
T t2 =
System.out.println(
System.out.println(
}
}
}
public class
+
n1 = n2;
}
+
a[
a[
}
Programming Exercises
8.19
What is the output of the following program?
Date date =
import
Date date =
date =
}
Date date =
Section 8.11
What is wrong in the following code?
ROGRAMMING
Pedagogical Note
The exercises in Chapters 814 achieve three objectives:
Design classes and draw UML class diagrams;
Implement classes from the UML;
Use classes to develop applications.
Solutions for the UML diagrams for the even-numbered exercises can be downloaded from the
Student Website and all others can be downloaded from the Instructor Website.
three objectives
Chapter 8Objects and Classes
8.1
)Following the example of the
Two
data fields named
and height of the rectangle. The default values are
A no-arg constructor that creates a default rectangle.
A constructor that creates a rectangle with the specified
Programming Exercises
Displaying calendars
) Rewrite the
play calendars in a message dialog box. Since the output is generated from several
Video Note
The Fan class
Chapter 8Objects and Classes
A private
data field named
that defines the number of sides in the poly-
gon with default value
A private
data field named
default value
A private
data field named
that defines the
of the polygon with default value
A private
data field named
that defines the
of the polygon with default value
A no-arg constructor that creates a regular polygon with default values.
A constructor that creates a regular polygon with the specified number of sides
A constructor that creates a regular polygon with the specified number of sides,
-
b
+
2
b
ax
x
=
n
*
s
*
p
b
.
Programming Exercises
8.11*
Algebra: linear equations
Private data fields
A constructor with the arguments for
=
*
2
2
*
2
8.13**
)Design a class named
value and its location in a two-dimensional array. The class contains public data
fields
that store the maximal value and its indices
in a two dimensional array with
TRINGSAND
Objectives
To use the
class to process fixed strings (9.2).
To use the
To use the
class to process flexible strings (9.4).
To distinguish among the
To learn how to pass arguments to the
Chapter 9Strings and Text I/O
9.1Introduction
Often you encounter problems that involve string processing and file input and output. Sup-
pose you need to write a program that replaces all occurrences of a word in a file with a new
word. How do you accomplish this? This chapter introduces strings and text files, which will
enable you to solve problems of this type. (Since no new concepts are introduced here,
instructors may assign this chapter for students to study on their own.)
9.2The
is a sequence of characters. In many languages, strings are treated as an array of char-
acters, but in Java a string is an object. The
string variable, string object,
string value
9.2The
instance for string literals with the same character sequence in order to improve efficiency and
save memory. Such an instance is called
. For example, the following statements:
This string object is
s
9.1
"Welcome to Java"
;
String s2 =
new
String(
"Welcome to Java"
);
"Welcome to Java"
;
System.out.println(
"s1 == s2 is "
+ (s1 == s2));
System.out.println(
"s1 == s3 is "
+ (s1 == s3));
s1
refer to the same interned string Welcome to Java,
s1==s3
. However,
s1==s2
are two differ-
ent string objects, even though they have the same contents.
9.2.3String Comparisons
Chapter 9Strings and Text I/O
How do you compare the contents of two strings? You might attempt to use the
tor, as follows:
However, the
9.2The
9.2.4String Length, Characters, and Combining Strings
When you use a string, you often know its literal value. For convenience, Java allows you to use
the string literal to refer directly to strings without creating new variables. Thus,
is correct and returns
A string value is represented using a private array variable internally. The array cannot be accessed
class provides many public methods, such as
, to retrieve the array information. This is a good example of
encapsulation: the data field of the class is hidden from the user through the private modifier, and
thus the user cannot directly manipulate it. If the array were not private, the user would be able to
change the string content by modifying the array. This would violate the tenet that the
class is immutable.
Attempting to access characters in a string
out of bounds is a common programming error. To
avoid it, make sure that you do not use an index beyond
s.length()1
. For example,
would cause a
string index range
message.charAt(0)message.charAt(14)
01234567891011121314
WelcometoJava
object is represented using an array internally.
Chapter 9Strings and Text I/O
You can use the
You can obtain a single character from a string using the
message.substring(0, 11)message.substring(11)
01234567891011121314
WelcometoJava
9.2The
9.2.6Converting, Replacing, and Splitting Strings
regular expression
newString: String): String
newString: String): String
Chapter 9Strings and Text I/O
9.2The
Chapter 9Strings and Text I/O
For example, to convert a
value
Video Note
Check palindrome
9.2The
)6// Create a Scanner7 Scanner input = newScanner(System.in);89// Prompt the user to enter a string10 System.out.print("Enter a string: ");111213if()
isPalindrome() {
high = -
low index
high index
Chapter 9Strings and Text I/O
hexCharToDecimal(hexChar)
decimalValue
hex to decimal
A brute-force approach is to convert each hex character into a decimal number, multiply it by
for a hex digit at the
decimal value for the hex number.
This observation leads to the following efficient algorithm for converting a hex string to a dec-
Here is a trace of the algorithm for hex number
hexToDecimal(String hex) {
9.3The
hex char to decimal
The program reads a string from the console (line 11), and invokes the
two characters is to subtract their Unicodes. For example,
'5''0'
9.3The
Java provides a wrapper class for every primitive data type. These classes are
Chapter 9Strings and Text I/O
9.10
9.4The
Chapter 9Strings and Text I/O
+StringBuilder()
.
9.11
9.12
9.4The
Chapter 9Strings and Text I/O
9.13
9.4The
with the filtered string using the
isPalindrome(String s) {
Chapter 9Strings and Text I/O
filter(Strings)
TestMain {
i =
System.out.println(args[i]);
}
9.5Command-Line Arguments
9.14
The program takes three arguments (operand1 operator operand2) from the
Video Note
Chapter 9Strings and Text I/O
(!=
]
]
]
]
]
]
]
]
]
]
]
)
why file?
9.6The
Every file is placed in a directory in the file system. An
absolute filename
contains a file
object for the specified path name. The path name may be a
directory or a file.
object for the child under the directory parent. The child may be
a file name or a subdirectory.
object for the child under the directory parent. The parent is a
object. In the preceding constructor, the parent is a string.
9.15
\ in file names
Chapter 9Strings and Text I/O
instance does not create a file on the machine
. You can create a
instance for any file name regardless whether it exists or not. You can invoke the
method on a
instance to check whether the file exists.
Do not use absolute file names in your program. If you use a file name such as
, it will work on Windows but not on other platforms. You
should use a file name relative to the current directory. For example, you may create a
for the file
Welcome.java
tory. You may create a
for the file
directory in the current directory. The forward slash
) is the Java directory
separator, which is the same as on Unix. The statement
works
on Windows, Unix, and any other platform.
Listing 9.6 demonstrates how to create a
object for the file
. This file is
directory in the current directory.
"image/us.gif"
(a) On Windows(b) On Unix
9.16
object and displays file properties.
relative file name
Java directory separator (
9.7File Input and Output
Figure 9.16(a) shows a sample run of the program on Windows, and Figure 9.16(b), a sam-
ple run on Unix. As shown in the figures, the path-naming conventions on Windows are
different from those on Unix.
9.7File Input and Output
Creates a
PrintWriter
object for the specified file-name string.
Writes a string to the file.
PrintWriter
object for the specified file object.
Writes a character to the file.
int
value to the file.
Writes a
long
value to the file.
Writes a
float
value to the file.
Writes a
double
value to the file.
Writes a
boolean
value to the file.
A
println
9.17
public class
WriteData {
public static void
main(String[] args)
throws
Exception {
new
java.io.File(
"scores.txt"
);
if
(file.exists()) {
5 System.out.println(
"File already exists"
);
6 System.exit(
0
);
7 }
9
// Create a file
new
java.io.PrintWriter(file);
throws an exception
file exist?
Chapter 9Strings and Text I/O
jpj();
"John T Smith "
);
90
);
15 output.print(
"Eric K Jones "
);
16 output.println(
85
);
18
// Close the file
17
scores.txt
close file
create a file
Scanner
9.18
9.7File Input and Output
Listing 9.8 gives an example that creates an instance of
file scores.txt.
import
java.util.Scanner;
2
public class
ReadData {
4
public static void
main(String[] args)
throws
Exception {
5
// Create a File instance
6 java.io.File file =
new
java.io.File(
"scores.txt"
);
7
// Create a Scanner for the file
9 Scanner input =
new
Scanner(file);
10
// Read data from a file
12
while
(input.hasNext()) {
13 String firstName = input.next();
int
score = input.nextInt();
17 System.out.println(
19 }
// Close the file
22 input.close();
scores.txt
has next?
close file
for a given string. To create a
to read data from a file, you have to use the
for the file (line 9).
Invoking the constructor
may throw an I/O exception. So the
Chapter 9Strings and Text I/O
The line-separator string is defined by the system. It is
on Windows and
on Unix. To
get the line separator on a particular platform, use
behavior of
input from file
input from keyboard
9.8(GUI) File Dialogs
0]);check command usagesource file exists?
Chapter 9Strings and Text I/O
UMMARY
using one of the 11 constructors or using a string literal shorthand initializer.
object is immutable; its contents cannot be changed. To improve efficiency
and save memory, the JVM stores two literal strings that have the same character
8 == ) {
9.19
can be used to display a file dialog for opening a file.
Review Questions
You can use the
You can use the
UESTIONS
9.1
are four strings, given as follows:
What are the results of the following expressions?
(1)s1 == s2
(2)s2 == s3
(3)s1.equals(s2)
(4)s2.equals(s3)
Chapter 9Strings and Text I/O
(17)s1.endsWith(
(18)s1.toLowerCase()
(19)s1.toUpperCase()
(21)s1.replace(
(22)s1.replaceAll(
(23)s1.replaceFirst(
(24)s1.toCharArray()
To create a string Welcome to Java, you may use a statement like this:
Review Questions
Chapter 9Strings and Text I/O
,
Programming Exercises
ROGRAMMING
9.1*
Checking SSN
Chapter 9Strings and Text I/O
Checking substrings
Programming Exercises
Video Note
Number conversion
Chapter 9Strings and Text I/O
Write a test program that prompts the user to enter two strings and, if they are
9.13*
Passing a string to check palindromes
) Rewrite Listing 9.1 by passing the string
as a command-line argument.
9.14*
Summing integers
) Write two programs. The first program passes an unspecified
number of integers as separate strings to the
}
(a) Next-line brace style(b) End-of-line brace style
Your program can be invoked from the command line with the Java source-code
file as the argument. It converts the Java source code to a new format. For exam-
ple, the following command converts the Java source-code file
Test.java
9.17*
Counting characters, words, and lines in a file
number of characters (excluding control characters
), words, and
Programming Exercises
characters. The file name should be passed as a command-line argument, as shown
9.18*
Processing scores in a text file
) Suppose that a text file
Exercise9_18.txt
tains an unspecified number of scores. Write a program that reads the scores from
the file and displays their total and average. Scores are separated by blanks.
9.19*
) Write a program to create a file named
Exercise9_19.txt
if it does not exist. Write
integers created randomly into the file using text
I/O. Integers are separated by spaces in the file. Read the data back from the file
Replacing text
The program displays the number of characters, words, and lines in the given
file.
(a)(b)
rectness of the answer.
Chapter 9Strings and Text I/O
class is provided in the Java
A two-dimensional array stores states and their capitals.
Programming Exercises
Common prefix
Chapter 9Strings and Text I/O
Checking ISBN
) Use string operations to simplify Exercise 3.9. Enter the first 9
) Rewrite Exercise 9.31. The program reads the words stored
in a text file named
Exercise9_33.txt
. Words are delimited by spaces.
Replacing text
) Revise Exercise9_20 to replace a string in a file with a new
string for all files in the specified directory using the following command:
java Exercise9_34 dir oldString newString
Bioinformatics: finding genes
HINKINGIN
BJECTS
Objectives
To create immutable objects from immutable classes to protect the contents of objects
Chapter 10Thinking in Objects
10.1Introduction
The preceding two chapters introduced objects and classes. You learned how to define
classes, create objects, and use objects from several classes in the Java API (e.g.,
). This books
object-oriented programming. This chapter will show how procedural and object-oriented
programming differ. You will see the benefits of object-oriented programming and learn to
use it effectively.
Our focus here is on class design. We will use several examples to illustrate the advantages
of the object-oriented approach. The examples involve designing new classes and using them
in applications. We first introduce some language features supporting these examples.
10.2Immutable Objects and Classes
Normally, you create an object and allow its contents to be changed later. Occasionally it is desir-
able to create an object whose contents cannot be changed, once the object is created. We call
class, for exam-
java.util.Date dateCreated;
String name;
Student {
10.3The Scope of Variables
;
;
Circle {
public double
findArea() {
Foo {
private int
j = i +
;
}
(a) variable
Chapter 10Thinking in Objects
is declared as a data field with the initial value of
in the class, but is also declared
The keyword
Circle {
private double
radius;
public
Circle(
double
radius) {
this
.radius = radius;
}
public
Circle() {
(
1.0
);
}
public double
10.5Class Abstraction and Encapsulation
in the second constructor invokes the first constructor with a
value argument.
Tip
If a class has multiple constructors, it is better to implement them using
much as possible. In general, a constructor with no or fewer arguments can invoke the construc-
tor with more arguments using
. This often simplifies coding and makes the
class easier to read and to maintain.
Java requires that the
statement appear first in the constructor before any
other statements.
10.5Class Abstraction and Encapsulation
Class abstraction and encapsulation are two sides of the same coin. Many real-life exam-
ples illustrate the concept of class abstraction. Consider, for instance, building a computer
system. Your personal computer has many componentsa CPU, memory, disk, motherboard,
(signatures of
Video Note
Chapter 10Thinking in Objects
Loan
object.
class models the properties and behaviors of loans.
10.5Class Abstraction and Encapsulation
loanAmount)
Loan(
double
annualInterestRate,
no-arg constructor
Chapter 10Thinking in Objects
10.6Object-Oriented Thinking
Important Pedagogical Tip
The UML diagram for the
class is shown in Figure 10.4. Students should begin by writing a
test program that uses the
class even though they dont know how the
class is imple-
mented. This has three benefits:
It demonstrates that developing a class and using a class are two separate tasks.
It enables you to skip the complex implementation of certain classes without interrupting
the sequence of the book.
It is easier to learn how to implement a class if you are familiar with the class through using it.
For all the examples from now on, you may first create an object from the class and try to use its
methods and then turn your attention to its implementation.
10.6Object-Oriented Thinking
Chapters 17introduced fundamental programming techniques for problem solving using
double, height: double)
height: double)
object with the specified
name, age, weight, and height.
name, weight, height, and a default age 20.
Video Note
Chapter 10Thinking in Objects
class is available. Listing 10.3 gives a test program that uses this
)34 System.out.println("The BMI for "+ + " is "5 + +
9 + +
BMI(
BMI(
);
10.7Object Composition
Chapter 10Thinking in Objects
aggregating object
aggregating class
aggregated object
aggregated class
An object may be owned by several other aggregating objects. If an object is exclusively
1111..3
1
Supervisor
A person may have a supervisor.
Student {
private
Name name;
private
Address address;
Address {
Aggregated class
Aggregating class
Aggregated class
Person {
10.8Designing the
If a person may have several supervisors, as shown in Figure 10.8(a), you may use an array to
store supervisors, as shown in Figure 10.8(b).
Since aggregation and composition relationships are represented using classes in similar ways,
many texts dont differentiate them and call both compositions.
10.8Designing the
This books philosophy is
teaching by example and learning by doing
. The book provides a
aggregation or composition
(a)(b)
publicclass
Person[] supervisors;
A person may have several supervisors.
-courseName: String
+Course(courseName: String)
ing a course name. You can add students to the course using the
Chapter 10Thinking in Objects
)34567 course1.addStudent("Brian Smith");8 course1.addStudent("Anne Kennedy");91011 course2.addStudent("Steve Smith");1213 System.out.println("Number of students in course1: "14 + );
15 String[] students = ;
; i ; i++)
"Database Systems"
"Data Structures"
course. For simplicity, assume that the maximum course enrollment is
addStudent(String student) {
10.9Designing a Class for Stacks
dropStudent(String student) {
Data2
Data3
Data2
Data2
Data3
10.10
A stack holds data in a last-in, first-out fashion.
Video Note
Chapter 10Thinking in Objects
-elements: int[]
10.11
class encapsulates the stack storage and provides the
elements[0]
elements[size

size

1]
10.12
class encapsulates the stack storage and provides
)345for(inti = 0; i 10; i++)678while(!stack.empty())9 System.out.print(+
How do you implement the
. When you create a stack, the array is also created. The no-arg
constructor creates an array with the default capacity of
. The variable
size1
is the index of the element at the top of the
stack, as shown in Figure 10.12. For an empty stack,
10.10Designing the
size�=capacity
), create a new array of twice the current capacity (line 19), copy the con-
tents of the current array to the new array (line 20), and assign the reference of the new array to
the current array in the stack (line 21). Now you can add the new value to the array (line 24).
3private intsize;4public static final intDEFAULT_CAPACITY = 16;56/** Construct a stack with the default capacity 16 */7 {
12 {
StackOfIntegers(
StackOfIntegers()
StackOfIntegers
Chapter 10Thinking in Objects
10.13
class defines data for guessing birthdays.
10.10Designing the
static field
Chapter 10Thinking in Objects
private constructor
10.11Class Design Guidelines
10.11.3Encapsulation
modifier to hide its data from direct access by clients. This
makes the class easy to maintain.
Provide a
encapsulating data fields
easy to explain
Chapter 10Thinking in Objects
class abstraction347
class encapsulation347
classs contract347
classs variable345
immutable class344
immutable object344
stack357
keyword346
UMMARY
Once it is created, an immutable object cannot be modified. To prevent users from
modifying an object, you may define immutable classes.
The scope of instance and static variables is the entire class, regardless of where the
variables are declared. Instance and static variables can be declared anywhere in the
class. For consistency, they are declared at the beginning of the class.
The keyword
a constructor to invoke another constructor of the same class.
UESTIONS
10.1
Instance and static are integral parts of object-oriented programming. A data field or
Review Questions
Is the following class immutable?
Chapter 10Thinking in Objects
ROGRAMMING
10.1*
Data fields
A no-arg constructor that creates a
object for the current time. (The values
of the data fields will represent the current time.)
object with a specified elapsed time since
midnight, Jan 1, 1970, in milliseconds. (The values of the data fields will repre-
object with the specified hour, minute, and
, as shown in Listing 2.6,
ShowCurrentTime.java.)
) Add the following new constructor in the
Programming Exercises
Two data fields
Video Note
Chapter 10Thinking in Objects
Financial: the
) Exercise 7.12 writes a program for computing taxes
to contain the following instance data
fields:
:One of the four tax-filing statuses:
single filer,
married filing jointly,
married filing separately, and
Programming Exercises
) Revise the
class as follows:
The array size is fixed in Listing 10.6. Improve it to automatically increase the
array size by creating a new larger array and copying the contents of the cur-
10.1
2001 United States Federal Personal Tax Rates
Tax
rate
Single filers
Married filing jointly
Married filing
separately
Chapter 10Thinking in Objects
(b)
(c)
p
10.15
(c) A rectangle overlaps another rectangle.
10.12*
(a)(b)(c)
10.14
overlaps another circle.
Programming Exercises
(b)
p
10.17
(a)(b)(c)
10.16
A triangle overlaps another triangle.
10.14*
Data fields
A no-arg constructor that creates a
object with a specified elapsed time
object with the specified year, month,
and day.
Chapter 10Thinking in Objects
Draw the UML diagram for the class. Implement the class. Write a test program that
creates two
and display their hour, minute, and second.
: The first two constructors will extract year, month, and day from the elapsed
time. For example, if the elapsed time is
. For the no-arg constructor, the current
, as shown in Listing
2.6, ShowCurrentTime.java.)
NHERITANCEAND
Objectives
To develop a subclass from a superclass through inheritance (11.2).
Chapter 11Inheritance and Polymorphism
11.1Introduction
Object-oriented programming allows you to derive new classes from existing classes. This is
. Inheritance is an important and powerful feature in Java for reusing soft-
ware. Suppose you are to define classes to model circles, rectangles, and triangles. These
classes have many common features. What is the best way to design these classes so to avoid
redundancy and make the system easy to comprehend and easy to maintain? The answer is to
11.2Superclasses and Subclasses
You use a class to model objects of the same type. Different classes may have some common
properties and behaviors, which can be generalized in a class that can be shared by other
classes. Inheritance enables you to define a general class and later extend it to more special-
white
).
-radius: double
-height: double
11.1
Video Note
Geometric class hierarchy
11.2 Superclasses and Subclasses
avoid naming conflict
data fields
Chapter 11Inheritance and Polymorphism
11.2 Superclasses and Subclasses
Chapter 11Inheritance and Polymorphism
The keyword
class extends the
Rectangle1
extends
11.2 Superclasses and Subclasses
11.4
,
4
invoke
The following points regarding inheritance are worthwhile to note:
Chapter 11Inheritance and Polymorphism
11.3Using the
Keyword
ClassName() {
// some statements
ClassName(
double
ClassName(
double
ClassName() {
// some statements
Equivalent
Equivalent
11.3 Using the
Keyword
In any case, constructing an instance of a class invokes the constructors of all the superclasses
tor first invokes its superclass constructor before performing its own tasks. If the superclass is
derived from another class, the superclass constructor invokes its parent-class constructor
before performing its own tasks. This process continues until the last constructor along the
constructor chaining
Consider the following code:
)34 }56 {
12 {
17 {
23 {
Person()
Employee(String s)
Employee()
extends
Person
Faculty()
invoke overloaded
tasks;
tasks;
tasks;
Chapter 11Inheritance and Polymorphism
If a class is designed to be extended, it is better to provide a no-arg constructor to avoid pro-
gramming errors. Consider the following code:
Since no constructor is explicitly defined in
s default no-arg constructor is
defined implicitly. Since
s default constructor automati-
cally invokes
s no-arg constructor. However,
does not have a no-arg constructor,
has an explicit constructor defined. Therefore, the program cannot be compiled.
It is better to provide a no-arg constructor (if desirable) for every class to make the class easy to
extend and to avoid errors.
.toString()
no-arg constructor
no-arg constructor
11.5 Overriding vs. Overloading
Test {
public static void
main(String[] args) {
A a =
A();
a.p(
10
);
a.p(
10.0
);
}
}
invoke the
Chapter 11Inheritance and Polymorphism
11.6The
ClassName
extends
Object {
Equivalent
defined by a subclass is called a
and a type defined by its superclass is called a
11.8 Dynamic Binding
additional new features. A subclass is a specialization of its superclass; every instance of a
subclass is also an instance of its superclass, but not vice versa. For example, every circle is a
,
1
,
));
,
11.8Dynamic Binding
variable is the actual class for the object referenced by the variable. Here
s actual type is
Chapter 11Inheritance and Polymorphism
java.lang.Object
If
o
is an instance of
C
o
is also an
instance of
C
C
C
C
11.2
class. In Java,
extends
Student
override
override
Video Note
polymorphism and dynamic
11.9 Casting Objects and the
Operator
Invoking
m(newStudent())
explicit casting
downcasting
Chapter 11Inheritance and Polymorphism
is a Java keyword. Every letter in a Java keyword is in lowercase.
Tip
To help understand casting, you may also consider the analogy of fruit, apple, and orange with
class as the superclass for
. An apple is a fruit, so you can always
safely assign an instance of
to a variable for
. However, a fruit is not necessarily an
apple, so you have to use explicit casting to assign an instance of
Listing 11.7 demonstrates polymorphism and casting. The program creates two objects
(lines 56), a circle and a rectangle, and invokes the
instanceof
Rectangle1
instanceof
Circle4
lowercase keywords
11.10 The
s
Method
Chapter 11Inheritance and Polymorphism
11.3
Listing 11.8 gives an example of using
11.8
"London"
create
Video Note
11.11 The
9 cityList.add("Denver");10// cityList now contains [London, Denver]11 cityList.add("Paris");12// cityList now contains [London, Denver, Paris]13 cityList.add("Miami");14// cityList now contains [London, Denver, Paris, Miami]15 cityList.add("Seoul");16// contains [London, Denver, Paris, Miami, Seoul]17 cityList.add("Tokyo");18// contains [London, Denver, Paris, Miami, Seoul, Tokyo]1920 System.out.println("List size? "+ ); 21 System.out.println("Is Miami in the list? "+22 );
24 + );
26 );
3132// Remove a city from the list3334// contains [London, Denver, Xian, Paris, Seoul, Tokyo]3536// Remove a city at index 137 cityList.remove(1);38// contains [London, Xian, Paris, Seoul, Tokyo]3940// Display the contents in the list41 System.out.println(cityList.toString());4243// Display the contents in the list in reverse order44for(inti = cityList.size() - 1�; i = 0; i--)45 System.out.print(+
"Miami"
"Denver"
"Miami"
element index
remove element
remove element
Chapter 11Inheritance and Polymorphism
using its no-arg constructor (line 4). The
add(index, Object)
11.12 A Custom Stack Class
11.1
Operation
Array
ArrayList
Object[] a= new Object[10]
Adding a new element
Inserting a new element
Removing an element
Removing an element
Removing all elements
and remove elements in a list, but it is rather complex to add, insert, and remove elements in
an array. You have to write code to manipulate the array in order to perform these operations.
is also a class for storing objects, which is very similar to the
class. All the methods in
are also available in
introduced in JDK 1.1. The
class introduced in JDK 1.2 was intended to replace the
11.12A Custom Stack Class
values. This
section introduces a stack class to store objects. You can use an
, as shown in Listing 11.9. The UML diagram for the class is shown in Figure 11.4.
11.9
4 {
isEmpty()
java.util.ArrayList list =
MyStack
array list
11.4
class encapsulates the stack storage and provides the operations
Video Note
Chapter 11Inheritance and Polymorphism
8 {
String toString()
search(Object o)
push(Object o)
Object pop()
Object peek()
11.13 The
Data and Methods
11.2
Modifier
on members
from the
from the
same package
from a
from a different
package
(default)
private
The modifiers
are known as
modifiers
because they specify how class and class members are accessed. The visibility of
these modifiers increases in this order:
}
p1
;
package
p2;
C1 o =
can access o.x;
can access o.y;
can access o.z;
cannot access o.u;
can invoke o.m();
can access x;
can access y;
can access z;
cannot access u;
can invoke m();
can access x;
can access y;
cannot access z;
cannot access u;
can invoke m();
C1 o =
can access o.x;
cannot access o.y;
cannot access o.z;
cannot access o.u;
cannot invoke o.m();
11.5
Visibility increases
Table 11.2summarizes the accessibility of the members in a class. Figure 11.5illustrates how
Chapter 11Inheritance and Polymorphism
modifier to enable the members of the class to be accessed by
the subclasses in any package or classes in the same package. Use the
modifier to
enable the members of the class to be accessed by any class.
Your class can be used in two ways: for creating instances of the class, and for defining
subclasses by extending the class. Make the members
if they are not intended for
use from outside the class. Make the members
if they are intended for the users of the
actual type385
array list393
casting objects387
composition394
constructor chaining381
declared type385
dynamic binding385
Chapter Summary
UMMARY
You can derive a new class from an existing class. This is known as class inheritance.
The new class is called a subclass, child class or extended class. The existing class is
superclass
parent class
A constructor is used to construct an instance of a class. Unlike properties and
defined by its superclass is called a
11.
superclass375
supertype384
vector393
Chapter 11Inheritance and Polymorphism
UESTIONS
Sections 11.211.5
11.1
int
x) {
}
B() {
}
main(String[] args) {
B();
}
11.2
True or false?
Review Questions
Circle {
18
private
double length;
double
radius,
double
length) {
21 Circle(radius);
Chapter 11Inheritance and Polymorphism
Apple
Macintosh
Orange
11.6
Review Questions
11.14
What is wrong in the following code?
)3 Object fruit = newFruit();4 Object apple = (Apple)fruit;5 }6 }78classAppleextendsFruit {9 }1011classFruit {12 }Section 11.10
11.15
When overriding the
equals() {
Test {
public static void
main(String[] args) {
Object circle1 =
Object circle2 =
}
Sections 11.1111.12
11.16
How do you create an
? How do you append an object to a list? How
do you insert an object at the beginning of a list? How do you find the number of
objects in a list? How do you remove a given object from a list? How do you
Chapter 11Inheritance and Polymorphism
Sections 11.1311.14
11.18
What modifier should you use on a class so that a class in the same package can
access it, but a class in a different package cannot access it?
11.19
What modifier should you use so that a class in a different package cannot access
the class, but its subclasses in any package can access it?
11.20
In the code below, classes
(a)(b)
m1(String[] args) {
System.out.println(i);
}
(a)(b)
11.21
In the code below, classes
are in different packages. If the question marks
11.22
Programming Exercises
11.25
ROGRAMMING
Sections 11.211.4
11.1
that extends
Chapter 11Inheritance and Polymorphism
11.4
mented using composition. Create a new stack class that extends
Draw the UML diagram for the classes. Implement
gram that prompts the user to enter five strings and displays them in reverse order.
11.5
) Rewrite the
to replace an array to store students. You should not change the
class (i.e., the definition of the constructors and
11.7
Objectives
Chapter 12GUI Basics
12.1Introduction
The design of the API for Java GUI programming is an excellent example of how the object-
oriented principle is applied. This chapter serves two purposes. First, it introduces the basics
of Java GUI programming. Second, it uses GUI to demonstrate OOP. Specifically, this chap-
ter will introduce the framework of Java GUI API and discuss GUI components and their rela-
12.2Swing vs. AWT
We used simple GUI examples to demonstrate OOP in 8.6.3, Displaying GUI Components.
We used the GUI components such as
. Why do the GUI component classes have the prefix
? In fact, there is a class already named
When Java was introduced, the GUI classes were bundled in a library known as the Abstract
Windows Toolkit (AWT). AWTis fine for developing simple graphical user interfaces, but not for
developing comprehensive GUI projects. Besides, AWT is prone to platform-specific bugs. The
AWT user-interface components were replaced by a more robust, versatile, and flexible library
known as
Swingcomponents
. Swing components are painted directly on canvases using Java
code, except for components that are subclasses of
which must be drawn using native GUI on a specific platform. Swing components depend less on
heavyweight
why prefix J?
12.3The Java GUI API
12.3.2Container Classes
12.1
GUI Container Classes
is a window not contained inside another window. It is used to hold other Swing
user-interface components in Java GUI applications.
is an invisible container that holds user-interface components. Panels can be nested. You can place panels
is also often used as a canvas to draw graphics.
is a popup window or message box generally used as a temporary window to receive additional informa-
tion from the user or to provide notification that an event has occurred.
Swing Components
javax.swing
package
Swing GUI
java.awt
package
1
*
Chapter 12GUI Basics
12.3.3GUI Helper Classes
deals with the colors of GUI components. For example, you can spec-
ify background or foreground colors in components like
drawings.
specifies fonts for the text and drawings on GUI components.
For example, you can specify the font type (e.g., SansSerif), style
(e.g., bold), and size (e.g., 24 points) for the text on a button.
encapsulates the width and height of a component (in integer
specifies how components are arranged in a container.
12.4Frames
is a top-level container to hold GUI components.
Content
(b)
. (b) An OK button is added to the
Invoking
pixel and resolution
Chapter 12GUI Basics
12.4.2Adding Components to a Frame
The frame shown in Figure 12.3(a)is empty. Using the
This was cumbersome. The new version of Java since Java 5 allows you to place components
into the content pane by invoking a frames
This new feature is called
content-pane delegation
into the content pane of a frame. For simplicity we say that a component is added to a
was created using
newJButton("OK")
, and this object was added
add(Componentcomp)
, the window will be displayed as in
Figure 12.3(b). The button is always centered in the frame and occupies the entire frame no
matter how you resize it. This is because components are put in the frame by the content
panes layout manager, and the default layout manager for the content pane places the button
in the center. In the next section, you will use several different layout managers to place com-
create a button
12.5Layout Managers
12.5Layout Managers
In many other window systems, the user-interface components are arranged by using hard-
coded pixel measurements. For example, put a button at location (
10,10
) in the window.
Using hard-coded pixel measurements, the user interface might look fine on one system but
be unusable on another. Javas layout managers provide a level of abstraction that automati-
cally maps your user interface on all window systems.
The Java GUI components are placed in containers, where they are arranged by the con-
tainers layout manager. In the preceding program, you did not specify where to place the OK
button in the frame, but Java knows where to place it, because the layout manager works
-alignment: int
int, vgap: int)
manager.
manager with a specified alignment.
lays out components row by row.
Listing 12.3 gives a program that demonstrates flow layout. The program adds three labels
and text fields into the frame with a
manager, as shown in Figure 12.5.
Video Note
Chapter 12GUI Basics
This example creates a program using a style different from the programs in the preceding sec-
class. This example creates a class named
that extends the
(b)
manager to fill in the rows in
the container one after another.
12.5Layout Managers
In this example, the
resize the frame, the components are automatically rearranged to fit. In Figure 12.5(a), the
first row has three components, but in Figure 12.5(a), the first row has four components,
hgap: int, vgap: int)
with a specified number of rows and columns.
manager with a specified number of rows and
columns, horizontal gap, and vertical gap.
Chapter 12GUI Basics
You can specify the number of rows and columns in the grid. The basic rule is as follows:
The number of rows or the number of columns can be zero, but not both. If one is
zero and the other is nonzero, the nonzero dimension is fixed, while the zero dimen-
12.5Layout Managers
manager divides the container into grids; then the compo-
nents are added to fill in the cells row by row.
-hgap: int
manager with a specified number of
horizontal gap, and vertical gap.
lays out components in five areas.
Chapter 12GUI Basics
,
The buttons are added to the frame (lines 1115). Note that the
divides the container into five areas, each of which can hold a
12.6Using Panels as Subcontainers
12.5.4Properties of Layout Managers
Layout managers have properties that can be changed dynamically.
properties. You can use the
Video Note
Use panels as subcontainers
Chapter 12GUI Basics
12 (
21 (
23 (p1, BorderLayout.CENTER);
Panel
p2
Panel
p1
12.10
The program uses panels to organize components.
12.8The
It is worthwhile to note that the
class is the superclass for GUI component classes,
such as
. Every GUI component is a container. In theory, you could use the
);
);
IllegalArgumentException
Chapter 12GUI Basics
Tip
If your system supports other fonts, such as Times New Roman, you can use it to create a
object. To find the fonts available on your system, you need to obtain an instance of
using its static method
fonts on the system and its
names of all the available fonts. For example, the following statements print all the available font
find available fonts
-toolTipText: String
12.11
Video Note
Use Swing common properties
12.9Common Features of Swing GUI Components
nents (except
12.12
"Left"
"Center"
"Right"
// Create a font and a line border
21
// Create a panel to group two labels
"TimesRoman"
, Font.BOLD,
);
Chapter 12GUI Basics
12.10Image Icons
) is used to denote a relative file path under the Java classpath (e.g.,
in this example).
Tip
File names are not case sensitive in Windows but are case sensitive in Unix. To enable your pro-
grams to run on all platforms, name all the image files consistently, using lowercase.
An image icon can be displayed in a label or a button using
newJLabel(image-
newJButton(imageIcon)
labels and buttons. The example creates two labels and two buttons with icons, as shown
new
new
ImageIcon usIcon =
"image/us.gif"
GUI components cannot be shared by containers, because one GUI component can appear in
only one container at a time. Therefore, the relationship between a component and a container is
the composition denoted by a solid diamond, as shown in Figure 12.1.
naming files consistently
a button with image
12.13
The image icons are displayed in labels and buttons.
Chapter 12GUI Basics
Borders and icons can be shared. Thus you can create a border or icon and use it to set the
property for any GUI component. For example, the following statements set a
border
for two panels
AWT406
heavyweight component406
lightweight component406
layout manager411
Swing406
splash screen424
UMMARY
Every container has a layout manager that is used to position and place components in
You can use a
as a subcontainer to group components to achieve a desired layout.
Review Questions
UESTIONS
12.1
Which class is the root of the Java GUI component classes? Is a container class a
Chapter 12GUI Basics
12.10
. How do you create a
manager? How
12.11
How do you create a panel with a specified layout manager?
12.12
What is the default layout manager for a
? How do you add a component
12.13
publicstaticvoid
);
System.out.println(frame.isVisible());
}
Programming Exercises
12.19
How do you create an
from the file
What happens if you add a button to a container several times, as shown below?
Will the following code display three buttons? Will the buttons display the same
publicstaticvoid
17 JButton jbt2 =
20 p1.add(jbt1);
23 p2.add(jbt2);
26 p2.add(jbt1);
ROGRAMMING
12.1
manager
Chapter 12GUI Basics
manager
) Rewrite the preceding program to create
the same user interface, but instead of using
center.
manager
) Rewrite the preceding program to create the
same user interface. Instead of using
of two rows and three columns.
to group buttons
) Rewrite the preceding program to create the
same user interface. Instead of creating buttons and panels separately, define a
class that extends the
class. Place three buttons in your panel class, and
create two panels from the user-defined panel class.
) Write a program that displays four lines of text in four
labels, as shown in Figure 12.15(a). Add a line border on each label.
Sections 12.712.10
shown in Figure 12.15(b). Add a line border on each label. (Use any images of
your choice or those in the book, which can be obtained along with the books
Game: displaying a TicTacToe board
ing, as shown in Figure 12.15(c). What to display is randomly decided. Use the
12.14
Exercise 12.1 places the first three buttons in one panel and the other three
buttons in another panel.
12.15
(a) Exercise 12.5 displays four labels. (b) Exercise 12.6 displays four icons.
(c) Exercise 12.7 displays a TicTacToe board with image icons in labels.
Programming Exercises
Game: displaying three cards
label displays a card, as shown in Figure 12.16(b). The card image files are named
1.png, 2.png, 54.png and stored in the
directory. All three cards
are distinct and selected randomly. The image files can be obtained from
www.cs.armstrong.edu/liang/intro8e/book.zip
12.10*
Game: displaying a checkerboard
) Write a program that displays a checker-
or white, as shown in Figure 12.16(c).
12.16
(c) A checkerboard is displayed using buttons.
Video Note
Display a checker board
XCEPTION
ANDLING
Objectives
Chapter 13Exception Handling
13.1Introduction
Runtime errors
reads two integers
integer division
for the second number, a runtime error would occur, because you cannot
divide an integer by
does not raise an
exception
.) A simple way to fix the error is to add an
statement to test the second number,
as shown in Listing 13.2.
Video Note
Exception-handling
advantages
13.2Exception-Handling Overview
)5 Scanner input = newScanner(System.in);67// Prompt the user to enter two integers8 System.out.print("Enter two integers: ");9intnumber1 = input.nextInt();10intnumber2 = input.nextInt();1112if(number2 != 0)13 System.out.println(number1 + " / "+ number2 14 + " is "+ ());
reads two integers
In order to demonstrate the concept of exception handling, including how to create, throw,
catch, and handle an exception, we rewrite Listing 13.2 as shown in Listing 13.3.
reads two integers
Chapter 13Exception Handling
the code that is executed in normal circumstances. The
the code that is executed when
. In this event the program throws an exception
by executing
thrownew
13.3Exception-Handling Advantages
quotient(
Chapter 13Exception Handling
(FileNotFoundException ex) {
create a Scanner
for a file (line 12). If the file does not exist, the constructor
throws a
Listing 13.6 gives an example that handles an
exception.
)5 Scanner input = newScanner(System.in);6booleancontinueInput = true;78do{9 {
create a Scanner
smatchExcep-
13.4Exception Types
13.1
Exceptions thrown are instances of the classes shown in this diagram, or of subclasses of one of these
(InputMismatchException ex) {
When executing
input entered is not an integer. Suppose
block are now
executed. The statement
the user can enter a new line of input. The variable
value is
(line 17) when a valid input is received.
13.4Exception Types
Chapter 13Exception Handling
13.1
Examples of Subclasses of
Possible Reason for Exception
A class has some dependency on another class, but the latter class has
The JVM is broken or has run out of the resources it needs in order to
Examples of Subclasses of
Possible Reason for Exception
Attempt to use a class that does not exist. This exception would occur,
for example, if you tried to run a nonexistent class using the
java
command, or if your program were composed of, say, three class
files, only two of which could be found.
Related to input/output operations, such as invalid input, reading past
the end of a file, and opening a nonexistent file. Examples of sub-
Examples of Subclasses of
Possible Reason for Exception
reference variable.
Index to an array is out of range.
class is the root of exception classes. All Java exception classes inherit
. You can create your own exception classes by extend-
The exception classes can be classified into three major types: system errors, exceptions,
and runtime exceptions.
System errors
are thrown by the JVM and represented in the
class describes internal system errors. Such errors rarely occur. If one does,
there is little you can do beyond notifying the user and trying to terminate the pro-
gram gracefully. Examples of subclasses of
are listed in Table 13.1.
exception
runtime exception
by your program and by external circumstances. These errors can be caught and
Table 13.2.
Runtime exceptions
array, and numeric errors. Runtime exceptions are generally thrown by the JVM.
Examples of subclasses are listed in Table 13.3.
13.5More on Exception Handling
Declare exception
Exception handling in Java consists of declaring exceptions, throwing exceptions, and catching and
processing exceptions.
unchecked exception
checked exception
, and their subclasses are known as
unchecked exceptions
other exceptions are known as
checked exceptions
In most cases, unchecked exceptions reflect programming logic errors that are unrecover-
able. For example, a
is thrown if you access an object through a
reference variable before an object is assigned to it; an
thrown if you access an element in an array outside the bounds of the array. These are logic
errors that should be corrected in the program. Unchecked exceptions can occur anywhere in
a program. To avoid cumbersome overuse of
blocks, Java does not mandate that
you write code to catch or declare unchecked exceptions.
At present, Java does not throw integer overflow or underflow exceptions. The following state-
to the maximum integer.
It displays
, which is logically incorrect. The cause of this problem is overflow;
that is, the result exceeds the maximum for an
A future version of Java may fix this problem by throwing an overflow exception.
13.5More on Exception Handling
The preceding sections gave you an overview of exception handling and introduced several pre-
defined exception types. This section provides an in-depth discussion of exception handling.
Javas exception-handling model is based on three operations:
declaring an exception
throwing an exception
catching an exception
, as shown in Figure 13.2.
integer overflow/underflow
13.5.1Declaring Exceptions
Chapter 13Exception Handling
throw exception
exception message
catch exception
13.5More on Exception Handling
If no exceptions arise during the execution of the
block throws an exception, Java skips the remaining
statements in the try block and starts the process of finding the code to handle the exception.
The code that handles the exception is called the
exception handler
Chapter 13Exception Handling
Various exception classes can be derived from a common superclass. If a
block catches excep-
tion objects of a superclass, it can catch all the exception objects of the subclasses of that superclass.
The order in which exceptions are specified in
blocks is important. A compile error will
result if a catch block for a superclass type appears before a catch block for a subclass type. For
example, the ordering in (a) below is erroneous, because
. The correct ordering should be as shown in (b).
order of exception handlers
p2();
p2();
...
(a) Catch exception(b) Throw exception
...
...
...
...
...
...
Java forces you to deal with checked exceptions. If a method declares a checked exception (i.e., an
exception other than
), you must invoke it in a
block or declare to throw the exception in the calling method. For example, suppose that method
invokes method
may throw a checked exception (e.g.,
); you have
to write the code as shown in (a) or (b) below.
catch or declare checked
exceptions
is the root class for all exception objects.
13.5More on Exception Handling
You can use the
)3try{4 System.out.println();
1,2,3,4,5})invoke sum
Chapter 13Exception Handling
13.5.5Example: Declaring, Throwing, and Catching Exceptions
This example demonstrates declaring, throwing, and catching exceptions by modifying the
IllegalArgumentException(
IllegalArgumentException
13.6The
(IllegalArgumentException ex) {
try
class remains intact except that the class name is changed to
, a new constructor
Chapter 13Exception Handling
(java.io.IOException ex) {
"Welcome to Java"
"text.txt"
finally
13.9Chained Exceptions
13.7When to Use Exceptions
block contains the code that is executed in normal circumstances. The
contains the code that is executed in exceptional circumstances. Exception handling separates
error-handling code from normal programming tasks, thus making programs easier to read
and to modify. Be aware, however, that exception handling usually requires more time and
resources, because it requires instantiating a new exception object, rolling back the call stack,
Chapter 13Exception Handling
chained exceptions
. Listing 13.11 illustrates how to create and throw chained
exceptions.
13.11
Exception(
Exception(
chained exception
throw exception
Video Note
Create custom exception
13.10Creating Custom Exception Classes
13.12
5 {
InvalidRadiusException(
double
radius)
extends
Constructs an exception with no message.
Constructs an exception with the specified message.
InvalidRadiusException(newRadius);
InvalidRadiusException
Chapter 13Exception Handling
Invoking
checked custom exception
chained exception448
checked exception438
declare exception439
exception438
exception propagation441
throw exception436
unchecked exception438
UMMARY
Review Questions
Exception handling separates error-handling code from normal programming tasks,
thus making programs easier to read and to modify.
Exception handling should not be used to replace simple tests. You should test simple
exceptions whenever possible, and reserve exception handling for dealing with situa-
UESTIONS
Sections 13.113.3
13.1
Describe the Java
class, its subclasses, and the types of exceptions.
will the following programs throw, if any?
Test {
public static void
main(String[] args) {
System.out.println(
1
/
0
);
}
(a)
Test {
public static void
main(String[] args) {
String s =
"abc"
;
System.out.println(s.charAt(
3
));
}
(c)
Test {
public static void
main(String[] args) {
Object o =
null
;
System.out.println(o.toString());
(e)
)int[] list = newint
Test {
public static void
main(String[] args) {
Object o =
new
Object();
String d = (String)o;
(d)
Test {
public static void
main(String[] args) {
System.out.println(
1.0
/
0
);
}
(f)
Show the output of the following code.
Test {
public static void
main(String[] args) {
for
(
int
i =
0
; i
2
; i++) {
System.out.print(i +
" "
);
try
{
System.out.println(
1
/
0
);
}
catch
(Exception ex) {
}
(a)
public class
Test {
public static void
main(String[] args) {
try
{
for
(
int
i =
0
; i
2
; i++) {
System.out.print(i +
" "
);
System.out.println(
1
/
0
);
}
catch
(Exception ex) {
}
(b)
Point out the problem in the following code. Does the code throw any exceptions?
Chapter 13Exception Handling
What is the purpose of declaring exceptions? How do you declare an exception,
Review Questions
new int
];
"list[10] is "
+ list[
Chapter 13Exception Handling
(RuntimeException ex) {
System.out.println(
Programming Exercises
(Exception ex) {
System.out.println(
"Exception in main"
);
}
ROGRAMMING
Sections 13.213.10
13.1*
)Listing 9.5, Calculator.java, is a simple command-
line calculator. Note that the program terminates if any operand is nonnumeric.
Write a program with an exception handler that deals with nonnumeric operands;
then write another program without using an exception handler to achieve the
same objective. Your program should display a message that informs the user of
the wrong operand type before exiting (see Figure 13.6).
Chapter 13Exception Handling
)Write a program that prompts the user to read two
integers and displays their sum. Your program should prompt the user to read the
Video Note
BSTRACT
LASSES
NTERFACES
Objectives
To design and use abstract classes (14.2).
To process a calendar using the
To specify common behavior for objects using interfaces (14.4).
To define interfaces and define classes that implement
interfaces (14.4).
To define a natural order using the
interface (14.5).
To enable objects to listen for action events using
interface (14.6).
To make objects cloneable using the
interface (14.7).
Chapter 14Abstract Classes and Interfaces
14.1Introduction
You have learned how to write simple programs to create and display GUI components. Can you
write the code to respond to user actions, such as clicking a button? As shown in Figure 14.1,
when a button is clicked, a message is displayed on the console.
In order to write such code, you have to know interfaces. An interfaceis for defining com-
mon behavior for classes (especially unrelated classes). Before discussing interfaces, we
14.2Abstract Classes
14.1
The program responds to button-clicking action events.
Video Note
Abstract
14.2Abstract Classes
color: string, filled: boolean)
The new
Chapter 14Abstract Classes and Interfaces
14.2Abstract Classes
Chapter 14Abstract Classes and Interfaces
Note that you could not define the
Video Note
14.3Example:
java.util.GregorianCalendar
class defines common features of various calendars.
14.1
Field constants in the
The year of the calendar.
The month of the calendar with 0 for January.
The day of the calendar.
The minute of the calendar.
The second of the calendar.
The day number within the week with 1 for Sunday.
Same as DATE.
The day number in the year with 1 for the first day of the year.
The week number within the month with 1 for the first week.
The week number within the year with 1 for the first week.
Listing 14.5 gives an example that displays the date and time information for the current time.
Chapter 14Abstract Classes and Interfaces
"Current time is "
8 System.out.println(
"YEAR:\t"
8
,
);
YEAR:2007
MONTH:8
DATE:9
HOUR:9
HOUR_OF_DAY:21
MINUTE:23
SECOND:59
DAY_OF_WEEK:1
DAY_OF_MONTH:9
extract fields in calendar
14.4Interfaces
Toobtain the number of days in a month, use
publicabstract
Edible {
Video Note
The concept of interface
Chapter 14Abstract Classes and Interfaces
String howToEat() {
String howToEat() {
Fruit
implements
Edible {
String howToEat() {
Chicken
extends
Animal
implements
Edible {
Tiger
class extends
to specify that chickens are edi-
Equivalent
omitting modifiers
14.5Example: The
Interface
Tip
A constant defined in an interface can be accessed using the syntax
14.5Example: The
Interface
String
extends
Object
Comparable
Date
extends
Object
Comparable
java.util.Date
Object
Comparable
Max {
(a)(b)
Chapter 14Abstract Classes and Interfaces
Date d2 =
Date d3 = (Date)Max.max(d1, d2);
Comparable
14.6Example: The
Interface
You can now use the
interface
extends
buttoneventlistener
Clicking a button
fires anaction event
The listener object
processes the event
An event is
an object
A listener object processes the event fired from the source object.
interface
Chapter 14Abstract Classes and Interfaces
interface contains the
);
"Cancel"
// Create a panel to hold buttons
11 JPanel panel =
12 panel.add(jbtOK);
// Add panel to the frame
// Register listeners
18
20
public static void
main(String[] args) {
25
button is clicked, the
button is clicked, the
implements
ActionListener
implements
ActionListener
register listener
process event
process event
14.7Example: The
Interface
Chapter 14Abstract Classes and Interfaces
Todefine a custom class that implements the
interface, the class must override
Object clone()
how to implement
This exception is thrown if
14.8Interfaces vs. Abstract Classes
id = 1
house2 = house1.clone()
reference
1
1750.50
1750.50
id = 1
Chapter 14Abstract Classes and Interfaces
Interfaces vs. Abstract Classes
Variables
Constructors
Constructors are invoked by
the new operator.
Interface
All variables must be
publicstatic
No constructors. An interface
the new operator.
2_1
1
1_1
1_2
2_2
extends
extends
An interface can inherit other interfaces using the
keyword. Such an interface is
. For example,
in the following code is a subinterface of
NewInterface Interface1, ..., InterfaceN {
,
subinterface
14.8Interfaces vs. Abstract Classes
Class names are nouns. Interface names may be adjectives or nouns. For example, both
are interfaces.
is an adjective, and
Abstract classes and interfaces can both be used to specify common behavior of objects. How do
you decide whether to use an interface or a class? In general, a
strong is-a relationship
describes a parent-child relationship should be modeled using classes. For example, Gregorian cal-
endar is a calendar, so the relationship between the class
is modeled using class inheritance. A
weakis-a relationship
known as an
is-kind-of relationship
, indicates that an object possesses a certain property. A weak
is-a relationship can be modeled using interfaces. For example, all strings are comparable, so the
class implements the
interface.
In general, interfaces are preferred over abstract classes because an interface can define a
common supertype for unrelated classes. Interfaces are more flexible than classes. Consider
String howToEat()
String howToEat()
publicabstract
interface preferred
naming convention
Chapter 14Abstract Classes and Interfaces
type. Any
to invoke the
String howToEat()
String howToEat()
String howToEat()
String howToEat()
interface
14.9Processing Primitive Data Type Values as Objects
Object
Number
Double
Float
Long
Short
Byte
Character
Most wrapper class names for a primitive type are the same as the primitive data type name with
the first letter capitalized. The exceptions are
Each numeric wrapper class extends the abstract
naming convention
java.lang.Number
+byteValue(): byte
intValue(): int
+
longValue(): long
+
floatValue(): float
+
doubleValue(): double
+
java.lang.Comparable
Chapter 14Abstract Classes and Interfaces
You can construct a wrapper object either from a primitive data type value or from a string
representing the numeric valuefor example,
newInteger(5)
newInteger("5")
The wrapper classes do not have no-arg constructors. The instances of all wrapper classes
are immutable; this means that, once the objects are created, their internal values cannot be
represents the maximum value of the corresponding primitive data type. For
val-
ues. For
values. The following statements display the maximum integer (2,147,483,647), the
minimum positive float and the maximum double floating-point number
14.10Sorting an Array of Objects
sort
sort
sort
Chapter 14Abstract Classes and Interfaces
36 {
sort(Comparable[] list)
14.12The
Arrays are objects. An array is an instance of the
class. Furthermore, if
, every instance of
is an instance of
. Therefore, the following statements are all true:
10]instanceofObjectnewInteger[10]instanceofObjectnewInteger[10]instanceofComparable[]newInteger[10]instanceofNumber[]newNumber[10]instanceofObject[]CautionAlthough an intvalue can be assigned to a doubletype variable, int[]anddouble[]are
two incompatible types. Therefore, you cannot assign an
array to a variable of
new
Integer(
2
);
Equivalent
(a)(b)
Converting a primitive value to a wrapper object is called
. The reverse conversion
. The compiler will automatically box a primitive value that appears in a
context requiring an object, and will unbox an object that appears in a context requiring a
primitive value. Consider the following example:
1,2,3};2 System.out.println(intArray[0] + intArray[1] + intArray[2]);In line 1, primitive values
are automatically boxed into objects
,intArray[1],andintArray[2]are automatically converted into
Chapter 14Abstract Classes and Interfaces
));
multiply
(line 9) is a constant defined in the
newBigInteger("1")
A new result is obtained by invoking the
Java provides data types for integers and floating-point numbers, but not for rational num-
bers. This section shows how to design a class to represent rational numbers.
14.13Case Study: The
Add, Subtract, Multiply, Divide
java.lang.Comparable
Rational
Rational
-numerator: long
14.10
,
3
,
2
Chapter 14Abstract Classes and Interfaces
r1- r2
r1xr2
r1/r2
Rational(
Rational()
Rational
extends
Number
implements
Comparable
9 System.out.println(r1 +
" + "
+ r2 +
" - "
+ r2 +
" * "
+ r2 +
" / "
+ r2 +
" is "
14.13Case Study: The
51 {
Rational divide(Rational secondRational)
Rational multiply(Rational secondRational)
Rational subtract(Rational secondRational)
Rational add(Rational secondRational)
d
c
d
a
d
c
d
a
c
d
a
d
c
Chapter 14Abstract Classes and Interfaces
Chapter Summary
its contents cannot be changed. The
class is immutable. The
wrapper classes for primitive type values are also immutable.
Tip
The numerator and denominator are represented using two variables. It is possible to use an array
of two integers to represent the numerator and denominator. See Exercise 14.18. The signatures
of the public methods in the
class are not changed, although the internal representa-
tion of a rational number is changed. This is a good example to illustrate the idea that the data
fields of a class should be kept private so as to encapsulate the implementation of the class from
class has serious limitations. It can easily overflow. For example, the fol-
lowing code will display an incorrect result, because the denominator is too large.
overflow
Tofix it, you may implement the
denominator (see Exercise 14.19).
abstract class458
UMMARY
Chapter 14Abstract Classes and Interfaces
An interface is treated like a special class in Java. Each interface is compiled into a
separate bytecode file, just like a regular class.
interface defines the
UESTIONS
14.1
Which of the following classes definitions defines a legal abstract class?
A {
void unfinished();
A {
abstract void
unfinished();
A {
abstract void
unfinished();
A {
unfinished();
A {
abstract int
unfinished();
Review Questions
Which of the following is a correct interface?
A {
I1, I2 {
print() { };
A {
True or false? If a class implements
invoke the
Chapter 14Abstract Classes and Interfaces
14.13
What is wrong in the following code?
Review Questions
What is the output of the following code?
)System.out.println(Integer.parseInt("10"));System.out.println(Integer.parseInt("10", 10));System.out.println(Integer.parseInt("10", 16));System.out.println(Integer.parseInt("11"));System.out.println(Integer.parseInt("11", 10));System.out.println(Integer.parseInt("11", 16));}}Sections 14.1014.12
What are autoboxing and autounboxing? Are the following statements correct?
,new String[100],new Object[50], or newCalendar[20]into a variable of
type?14.25What is the output of the following code?
)java.math.BigInteger x = newjava.math.BigInteger("3");java.math.BigInteger y = newjava.math.BigInteger("7");x.add(y);System.out.println(x);}}Comprehensive
Define the following terms: abstract classes, interfaces. What are the similarities
Chapter 14Abstract Classes and Interfaces
An interface can extend an abstract class.
An abstract class can extend an interface.
ROGRAMMING
Sections 14.114.7
14.1*
Video Note
Redesign the
Programming Exercises
14.11
Section 14.12
14.11**
)Find the first ten numbers (greater than
that are divisible by
14.12**
)Find the first ten numbers with
divisible by
14.13**
Square numbers
) Find the first ten square numbers that are greater than
14.14**
Large prime numbers
) Write a program that finds five prime numbers larger
Chapter 14Abstract Classes and Interfaces
14.12
The program takes three arguments (operand1, operator, and operand2) from
+
2
+
3

,
e
=
1
+
1
!
+
1
!
+
1
!
+
1
!
!
p

1
Programming Exercises
You will need to use the
using the following formula:
You can also obtain the absolute value for a complex number using the follow-
for representing complex numbers and the
plex-number operations, and override the
+
2
a
b
a
+
/
1
c
+
=
1
/
1
c
d
+
1
c
d
1
a
+
*
1
c
+
=
1
+
1
i
a
+
1
c
+
=
1
a
-
c
2
+
1
b
-
d
2
i
a
+
c
+
1
a
+
c
2
+
1
b
+
d
2
i
2
-
1
a
+
Objectives
To describe Java coordinate systems in a GUI component (15.2).
Chapter 15Graphics
15.1Introduction
Suppose you wish to draw shapes such as a bar chart, a clock, or a stop sign, as shown in
Figure 15.1. How do you do so?
(a)(b)(c)
15.1
X
axis
Y
axis
(
x
,
y
)
x
y
Java Coordinate
axis
Conventional
(0, 0)
Y
axis
The Java coordinate system is measured in pixels, with
at its upper-
left corner.
c2
Component
c1
(0, 0)
(x3, y3)
Component
c3
c3
Each GUI component has its own coordinate system.
15.3The
15.3The
Chapter 15Graphics
In order to draw things on a component, you need to define a class that extends
and overrides its
"Banner"
0
,
);
,
0
,
);
.paintComponent(g);
paintComponent(Graphics g) {
NewPanel
extends
JPanel {
new panel class
override
draw things in the superclass
draw line
JPanel
object placed
A line and a string are drawn on a panel.
draw string
15.4Drawing Strings, Lines, Rectangles, and Ovals
The program will work, but it is not preferred, because
not for drawing. For consistency, this book will define a canvas class by subclassing
Tip
Some textbooks define a canvas class by subclassing
. The problem is that, if you
wish to set a background in the canvas, you have to write the code to paint the background color.
A simple
(b)
drawLine
(a)
drawString
drawString(s,x,y)
w
w
drawRect(x,y,w,h)
Chapter 15Graphics
h
h
(a)
drawRoundRect
(b)
drawOval
(x, y)
(x, y)
ah/2
(a)The
drawRoundRect(x,y,w,h,aw,ah)
Video Note
15.5Case Study: The
and
OVAL
are
constants, indicating the figure type.
displays various types of figures on the panel.
15.10
objects are created to display six figures.
Chapter 15Graphics
public static finalint
override
draw lines
fill a rectangle
draw a rectangle
fill round-cornered rect
draw round-cornered rect
fill an oval
15.5Case Study: The
67 ((
draw an oval
override
Chapter 15Graphics
w
h
startAngle
15.11
.paintComponent(g);
override
15.7Drawing Polygons and Polylines
30

15.12
The program draws four filled arcs.
);
);
);
Angles may be negative. A negative starting angle sweeps clockwise from the easterly direc-
tion, as shown in Figure 15.13. A negative spanning angle sweeps clockwise from the starting
angle. The following two statements draw the same arc:
The first statement uses negative starting angle
and negative spanning angle
shown in Figure 15.13(a). The second statement uses negative starting angle
and positive
, as shown in Figure 15.13(b).
30arc from 0
30arc from 90
30arc from 180
30arc from 270
negative degrees

and
negative spanning angle 20

30

20


and positive spanning angle 20


20

15.13
Angles may be negative.
15.7Drawing Polygons and Polylines
Todraw a polygon, first create a
class, as shown in
A polygon is a closed two-dimensional region. This region is bounded by an arbitrary
number of line segments, each being one side (or edge) of the polygon. A polygon comprises
(x,y)
-coordinate pairs in which each pair defines a vertex of the polygon, and two
successive pairs are the endpoints of a line that is a side of the polygon. The first and final
points are joined by a line segment that closes the polygon.
Here is an example of creating a polygon and adding points into it:
Chapter 15Graphics
npoints: int)
15.14
)(x[1], y[1])(x[3], y[3])(x[4], y[4])(x[2], y[2])(a) Polygon(b) Polyline
(x[1], y[1])
(x[3], y[3])
(x[4], y[4])
(x[2], y[2])
15.15
15.7Drawing Polygons and Polylines
Todraw a polyline, use the
drawPolyline(int[]x,int[]y,intnPoints)
.paintComponent(g);
paintComponent(Graphics g)
Chapter 15Graphics
Descent
Ascent line
Descent line
15.17
draw polygon
(x, y)
xCenter

radius

cos(2

/6)
y is
yCenter

radius

sin(2

/6)
(xCenter, yCenter)
2

6
15.16
15.8Centering a String Using the
of a font and the width of a string when it is drawn using the font:
MessagePanel
object
15.18
Chapter 15Graphics
MessagePanel
The
x
-coordinate for the message.
The
y
-coordinate for the message.
15.19
"Welcome to Java"
, xCoordinate, yCoordinate);
"Welcome to Java"
Video Note
15.9Case Study: The
6 MessagePanel messagePanel1 = ;
"Wecome to Java"
Chapter 15Graphics
MessagePanel(String message)
MessagePanel()
MessagePanel
extends
JPanel
15.9Case Study: The
override
Chapter 15Graphics
override
Video Note
15.10Case Study: The
StillClock
10
The rest of this section explains how to implement the
class without knowing how it is implemented, you may skip the implementation if you wish.
Todraw a clock, you need to draw a circle and three hands for second, minute, and hour.
Todraw a hand, you need to specify the two ends of the line. As shown in Figure 15.22(b),
(xCenter,yCenter)
(xEnd,yEnd)
Chapter 15Graphics
StillClock()
(xCenter, yCenter)
(xEnd, yEnd)
12
6
(b)
(a) The DisplayClock program displays a clock that shows the current time.
15.10Case Study: The
16 {
override
Chapter 15Graphics
15.11Displaying Images
bgcolor: Color, observer:
+drawImage(image: Image, x: int, y: int,
observer: ImageObserver): void
+drawImage(image: Image, x: int, y: int,
width: int, height: int, observer:
+drawImage(image: Image, x: int, y: int,
width: int, height: int, bgcolor: Color,
x
,
y
) in the graphics context's coordinate space. Transparent pixels in
the image are drawn in the specified color
bgcolor
. The observer is the
object on which the image is displayed. The image is cut off if it is
You can apply the
new
Chapter 15Graphics
,
0
paintComponent(Graphics g) {
"image/us.gif"
ImagePanel
extends
JPanel {
15.12Case Study: The
15.12
create image viewer
Chapter 15Graphics
26 {
paintComponent(Graphics g)
Review Questions
public void
UMMARY
Each component has its own coordinate system with the origin (
) at the upper-left
corner of the window. The
increases downward.
class is an abstract class for displaying figures and images on the
screen on different platforms. The
class is implemented on the native plat-
UESTIONS
15.1
Suppose that you want to draw a new message below an existing message. Should
class abstract? How is a
Chapter 15Graphics
Programming Exercises
(a)(b) (c)
(a) Exercise 15.1 displays a grid. (b) Exercise 15.2 displays two objects of
. (c) Exercise 15.3 displays a checkerboard.
(a)(b)
(a) Exercise 15.4 displays a multiplication table. (b) Exercise 15.5 displays
15.14
How do you create an
15.15
ROGRAMMING
15.1*
Displayinga grid
) Write a program that displays a grid, as shown in
Figure 15.27(a). Use red color for vertical lines and blue for horizontals
Creating a custom button class
) Develop a custom button class named
that extends
and displays the button text inside an oval.
Figure 15.27(b)shows two buttons created using the
Displaying a checkerboard
) Exercise 12.10 displays a checkerboard in which
. Rewrite a program that draws a checker-
Chapter 15Graphics
(b)
(c)
(a)(b)(c)
(a) Exercise 15.9 draws four fans. (b) Exercise 15.10 draws a cylinder. (c)
Exercise 15.11 draws a diagram for function
shapes as shown in Figure 15.29(a)using the new
Displaying a TicTacToe board
nothing. What to display is randomly decided whenever a panel is repainted.
Programming Exercises
(a)(b)
(a) Exercise 15.12 draws a diagram for function
). (b) Exercise
15.13 draws the sine and cosine functions.
g.drawPolyline(p.xpoints,p.ypoints,p.npoints)
for a
returns an array of
coordinates,
array of
-coordinates, and
15.12**
) Write a program that draws a diagram for the sine
function, as shown in Figure 15.31(a).
The Unicode for is
. To display use
("-2\u03c0",x,y)
drawFunction() {
x =
-100
p.addPoint(x +
- (
int
}
* connecting points
paintComponent(Graphics g) {
Video Note
Plot a sine function
Chapter 15Graphics
(a)(b)(c)
(a) Exercise 15.15 uses a pie chart to show the percentages of projects,
quizzes, midterm exam, and final exam in the overall grade. (b) Exercise 15.16 displays font
) Write a program that displays the message Java is
Programming Exercises
(a) Exercise 15.18 displays two clocks. (b) Exercise 15.19 displays a clock with
random hour and minute values. (c) Exercise 15.23 displays a rectanguloid. (d) Exercise 15.24
15.19*
class with three new Boolean properties
Chapter 15Graphics
(a)(b)
(a) Exercise 15.25 displays several n-sided polygons. (b) Exercise 15.26 uses
0303012
1903003
23090034
390901245
430150235
59015034
(a)(b)(c)
(a)-(b) The program reads the information about the graph and displays it visually.
(c) The program displays an arrow line.
uxyv1,v2,...
, describes that the vertex
ROGRAMMING
Objectives
To describe events, event sources, and event classes (16.2).
To define listener classes, register listener objects with the source object,
and write the code to handle events (16.3).
To define listener classes using inner classes (16.4).
To define listener classes using anonymous inner classes (16.5).
To explore various coding styles for creating and registering
Chapter 16Event-Driven Programming
16.1Introduction
and total payment, as shown in Figure 16.1(a). How do you accomplish the task? You have to
use event-driven programmingto write the code to respond to the button-clicking event.
Suppose you wish to write a program that animates a rising flag, as shown in Figure
16.1(b)(d). How do you accomplish the task? There are several ways to solve this problem.
An effective one is to use a timer in event-driven programming, which is the subject of this
chapter.
In event-driven programming, code is executed when an event occurs (e.g., a button click,
a mouse movement, or a timer). 14.6, Example: The
Interface, gave
you a taste of event-driven programming. You probably have many questions, such as why a
listener class is defined to implement the
interface. This chapter will give
16.2Event and Event Source
When you run a Java GUI program, the program interacts with the user, and the events drive
its execution. An
event
(d)
(c)
(b)
16.1
(a) The program computes loan payments. (b)(d) A flag is rising upward.
EventObject
An event is an object of the
16.3Listeners, Registrations, and Handling Events
An event objectcontains whatever properties are pertinent to the event. You can identify
the source object of an event using the
16.1
User Action, Source Object, and Event Type
Source Object
Event Type Fired
Click a button
Select a new item
Click a radio button
Move the scroll bar
Move the scroll bar
Window opened, closed, iconified,
deiconified, or closing
Mouse pressed, released, clicked,
entered, or exited
Mouse moved or dragged
Key released or pressed
Component added or removed from
Component moved, resized,
hidden, or shown
If a component can fire an event, any subclass of the component can fire the same type of event.
For example, every GUI component can fire
is the superclass of all GUI components.
All the event classes in Figure 16.2are included in the
package except
, which are in the
pack-
age. AWT events were originally designed for AWT components, but many Swing components
fire them.
16.3Listeners, Registrations, and Handling Events
Java uses a delegation-based model for event handling: a source object fires an event, and
an object interested in the event handles it. The latter object is called a
. For an
object to be a listener for an event on a source object, two things are needed, as shown in
ActionEvent/ActionListener
Chapter 16Event-Driven Programming
1.The listener object must be an instance of the corresponding event-listener interfaceto
When you click the button, the
object fires an
and passes it to invoke
the listeners
(2) Register by invoking
source.add
X
Listener(listener);
(a) A generic source component with a generic listener
(1) A listener object is an
(b) A
JButton
source component with an
ActionListener
(1) An action event listener is an
ActionListener
Action
+add
X
Listener(listener:
X
Listener)
handler(event: XEvent)
source.add
Action
Listener(listener);
+addActionListener(listener: ActionListener)
actionPerformed(event: ActionEvent)
CustomListenerClass
listener:
ListenerClass
XListener
interface
java.awt.event.ActionListener
A listener must be an instance of a listener interface and must be registered with a source component.
listener interface
Event
register listener
register listener
16.3Listeners, Registrations, and Handling Events
(Handlers)
The event object contains information pertinent to the event, which can be obtained using
Chapter 16Event-Driven Programming
You can obtain useful information from an event object.
+add
X
Listener(
X
Listener listener)
X
Event
n
n
.handler(event)
object
+add
Action
Listener(
Action
Listener listener)
Event
n
n
.actionPerformed(event)
The source object notifies the listeners of the event by invoking the handler of
Wenow write a program that uses two buttons to control the size of a circle, as shown in
Wewill develop this program incrementally. First we write a program in Listing 16.1 that
displays the user interface with a circle in the center (line 14) and two buttons in the bottom
first version
16.3Listeners, Registrations, and Handling Events
Enlarge
buttons to enlarge and shrink the size
16.1
buttons
circle canvas
second version
Chapter 16Event-Driven Programming
"Enlarge"
JButton jbtShrink =
"Shrink"
CirclePanel canvas =
public
ControlCircle2() {
11 JPanel panel =
// Use the panel to group buttons
12 panel.add(jbtEnlarge);
// Add canvas to center
16
// Add buttons to the frame
17
enlarge() {
CirclePanel
extends
JPanel {
actionPerformed(ActionEvent e) {
EnlargeListener
implements
ActionListener {
create/register listener
Video Note
Listener and its registration
16.4Inner Classes
the Shrink button
Test {
OuterClass {
private int
data;
(b)(c)
defined inside
in Figure 16.7(c)is another example of
an inner class. An inner class may be used just like a regular class. Normally, you define a class
an inner class if it is used only by its outer class. An inner class has the following features:
. For example, the inner class
Chapter 16Event-Driven Programming
anonymous inner class
An inner class can be defined
first create an instance of the outer class, then use the following syntax to create an
If the inner class is static, use the following syntax to create an object for it:
reduces the number of source files. It also makes class files easy to organize, since they are all
named with the primary class as the prefix. For example, rather than creating two source files,
Test.java
A.java
just one source file
Test.java
in Figure 16.7(b). The resulting class files are
Test.class
Test$A.class
Another practical use of inner classes is to avoid class-naming conflict. Two versions of
are defined in Listings 16.1 and 16.2. You can define them as inner classes to
avoid conflict.
16.5Anonymous Class Listeners
A listener class is designed specifically to create a listener object for a GUI component (e.g., a
button). The listener class will not be shared by other applications and therefore is appropriate
to be defined inside the frame class as an inner class.
Inner-class listeners can be shortened using anonymous inner classes. An
is an inner class without a name. It combines defining an inner class and creating an
instance of the class in one step. The inner class in Listing 16.2 can be replaced by an anony-
mous inner class as shown below.
ControlCircle2() {
// Omitted
ActionListener{
(a) Inner class EnlargeListener
(b) Anonymous inner class
The syntax for an anonymous inner class is as follows:
16.5Anonymous Class Listeners
Since an anonymous inner class is a special kind of inner class, it is treated like an inner class
with the following features:
An anonymous inner class must always extend a superclass or implement an inter-
face, but it cannot have an explicit
The program handles the events from four buttons.
"Process New"
actionPerformed(ActionEvent e) {
anonymous listener
Video Note
Anonymous listener
Chapter 16Event-Driven Programming
16.6Alternative Ways of Defining Listener Classes
"New"
JButton jbtOpen =
"Open"
JButton jbtSave =
"Save"
JButton jbtPrint =
"Print"
10
public
// Create a listener
22 ButtonListener listener =
// Register listener with buttons
25 jbtNew.addActionListener(listener);
class
ButtonListener
implements
ActionListener {
32
public void
actionPerformed(ActionEvent e) {
33
"Process New"
"Process Open"
"Process Save"
"Process Print"
register listener
handle event
Chapter 16Event-Driven Programming
This program defines just one inner listener class (lines 3142), creates a listener from the
class (line 22), and registers it to four buttons (lines 2528). When a button is clicked, the but-
ton fires an
and invokes the listeners
"New"
JButton jbtOpen =
"Open"
JButton jbtSave =
"Save"
private
JButton jbtPrint =
"Print"
11
public
FrameAsListenerDemo() {
13
// Create a panel to hold buttons
14 JPanel panel =
15 panel.add(jbtNew);
// Register listener with buttons
23
);
);
);
/** Implement actionPerformed */
30
32 System.out.println(
"Process New"
else if
34 System.out.println(
"Process Open"
else if
36 System.out.println(
"Process Save"
else if
38 System.out.println(
"Process Print"
actionPerformed(ActionEvent e) {
);
register listeners
handle event
16.7Problem: Loan Calculator
of
GridLayout(5,2)
JPanel
The frame class extends
listener class for action events. The listener is registered to four buttons (lines 2326). When
a button is clicked, the button fires an
and invokes the listeners
the monthly and total payments, and displays the values in the text fields.
Chapter 16Event-Driven Programming
// Add the panels to the frame
39 add(p1, BorderLayout.CENTER);
// Register listener
43
/** Handle the Compute Payment button */
47
public void
actionPerformed(ActionEvent e) {
49
ButtonListener
implements
ActionListener {
,
2
register listener
16.8Window Events
16.10
The window events are displayed on the console when you run the program
Chapter 16Event-Driven Programming
windowClosing(WindowEvent event) {
windowOpened(WindowEvent event) {
windowDeactivated(WindowEvent event) {
windowActivated(WindowEvent event) {
windowIconified(WindowEvent event) {
windowDeiconified(WindowEvent event) {
16.9Listener Interface Adapters
Convenience Adapters
83 );
can be fired by the
class or by any subclass of
, it can fire
extends
convenience adapter
, the preceding example can be simplified as shown in Listing 16.8,
if you are interested only in the window-activated event. The
create an anonymous listener instead of
Chapter 16Event-Driven Programming
windowActivated(WindowEvent event) {
register listener
16.11
class encapsulates information for mouse events.
16.10Mouse Events
component.
Invoked after the mouse button has been released on the
source component.
Invoked after the mouse button has been clicked (pressed and
released) on the source component.
Invoked after the mouse enters the source component.
java.awt.event.MouseListener
interface
java.awt.event.MouseMotionListener
16.12
interface handles mouse pressed, released, clicked, entered, and exited events. The
interface handles mouse dragged and moved events.
16.13
You can move the message by dragging the mouse.
listen for such actions as pressing, releasing, entering, exiting, or clicking the mouse, and
interface to listen for such actions as dragging or
moving the mouse.
16.10.1Example: Moving a Message on a Panel Using a Mouse
This example writes a program that displays a message in a panel, as shown in Listing 16.9.
You can use the mouse to move the message. The message moves as the mouse drags and is
always displayed at the mouse point. A sample run of the program is shown in Figure 16.13.
Video Note
Move message using the
Chapter 16Event-Driven Programming
mouseDragged(MouseEvent e) {
MovableMessagePanel
extends
JPanel {
16.11Key Events
Key Constants
The Home key
The Shift key
The End key
The Backspace key
The Page Up key
The Caps Lock key
The Page Down key
The Num Lock key
The up-arrow key
The Enter key
The down-arrow key
The keyCode unknown
The left-arrow key
The function keys
The right-arrow key
The Esc key
The number keys from 0 to 9
The Tab key
The Control key
16.14
class encapsulates information about key events.
keyPressed(e: KeyEvent): void
Invoked after a key is pressed on the source component.
+
keyTyped(e: KeyEvent): void
+
keyReleased(e: KeyEvent): void
Invoked after a key is released on the source component.
java.awt.event.KeyListener
16.15
interface handles key pressed, released, and typed events.
16.11Key Events
Chapter 16Event-Driven Programming
For the key-pressed and key-released events,
keyPressed(KeyEvent e) {
KeyboardPanel
extends
JPanel {
register listener
override handler
16.16
The program responds to key events by displaying a character and moving it
up, down, left, or right.
16.12Animation Using the
+Timer(delay: int, listener:
16.17
object fires an
at a fixed rate.
46 );
redraw character
efficient?
object serves as the source of an
and registered with a
object. You create a
sole constructor with a delay and a listener, where
specifies the number of milliseconds
Chapter 16Event-Driven Programming
MovingMessagePanel
extends
JPanel {
16.18
A message moves in the panel.
16.12Animation Using the
class extends
is defined as an inner class inside the main class, because it is used only in this class. Further-
more, the inner class is defined static, because it does not reference any instance members of
An inner class listener is defined in line 46 to listen for
for the listener. The timer is started in line 32. The timer fires an
every second, and the listener responds in line 49 to repaint the panel. When a panel is
TimerListener
implements
ActionListener {
actionPerformed(ActionEvent e) {
event handler
Video Note
Animate a clock
Chapter 16Event-Driven Programming
anonymous inner class542
convenience listener adapter551
event534
event delegation535
event handler559
event listener535
event-listener interface536
event object535
event registration535
event source (source object)535
event-driven programming534
inner class554
UMMARY
The root class of the event classes is
deal with special types of events, such as action events, window events,
component events, mouse events, and key events. You can identify the source object of
an event using the
16.19
A live clock is displayed in the panel.
Review Questions
Convenience adapters are support classes that provide default implementations for all
UESTIONS
16.1
Can a button fire a
? Can a button fire a
? Can a button
fire an
Why must a listener be an instance of an appropriate listener interface? Explain
how to register a listener object and how to implement a listener interface.
Can a source have multiple listeners? Can a listener listen on multiple sources?
Chapter 16Event-Driven Programming
ROGRAMMING
16.1
Finding which button has been clicked on the console
) Add the code to Exercise
12.1 that will display a message on the console indicating which button has been
clicked.
)AnyGUI component can fire a
defines the
);
Listener
implements
ActionListener {
public void
actionPerform
(ActionEvent e) {
System.out.println
java.awt.event.*;
import
javax.swing.*;
public class
Test
extends
JFrame {
public
Test() {
JButton jbtOK =
);
public void
actionPerformed
(ActionEvent e) {
System.out.println
Programming Exercises
(a)(b)
(a) Exercise 16.3 displays which button is clicked on a message panel. (b) The program performs
addition, subtraction, multiplication, and division on double numbers.
Moving the ball
) Write a program that moves the ball in a panel. You should
(a)(c)
(a) The user enters the investment amount, years, and interest rate to com-
pute future value. (b) Exercise 16.8 displays the mouse position. (c) Exercise 16.9 uses the
arrow keys to draw the lines.
Creating a simple calculator
ply, and divide operations (see Figure 16.20(b)).
Creating an investment-value calculator
future value of an investment at a given interest rate for a specified number of
years. The formula for the calculation is as follows:
Use text fields for interest rate, investment amount, and years. Display the future
amount in a text field when the user clicks the
button, as shown in
Chapter 16Event-Driven Programming
xx+20x+40
(a)(b)
(a) Exercise 16.15 displays a moving car. (b) You can redraw a car with a new base point.
toward east, north, west, or south when the right-arrow key, up-arrow key, left-
arrow key, or down-arrow key is clicked, as shown in Figure 16.21(c).
16.10**
) Write a program that receives a string from
the keyboard and displays it on a panel. The
key signals the end of a
string. Whenever a new string is entered, it is displayed on the panel.
16.11*
Displaying a character
Video Note
Animate a rising flag
Programming Exercises
(a)(b)(c)
Chapter 16Event-Driven Programming
(a)(b)(c)
(d)(e)(f)
arrow keys to aim the balloon. (c) Press the up-arrow key to fire a ball. (d) The ball moves
straight toward the balloon. (e) The ball hits the balloon. (f) A new balloon is displayed in a
(d)
(c)
(b)
Exercise 16.23 allows the user to create new points with a mouse click and highlights the pair of the clos-
est points. Exercise 16.24 allows the user to start and stop a clock.
Moving a circle using mouse
pixels. You can point the mouse inside the circle and drag (i.e.,
move with mouse pressed) the circle wherever the mouse goes, as shown in
Game: eye-hand coordination
pixels filled with a random color at a random location on a panel, as shown in
Figure 16.27(c). When you click the circle, it is gone and a new random-color
circle is displayed at another random location. After twenty circles are clicked,
display the time spent in the panel, as shown in Figure 16.27(d).
Programming Exercises
(a)(b)(c)(d)
(a)(b) You can point, drag, and move the circle. (c) When you click a circle, a new circle is displayed at
a random location. (d) After 20 circles are clicked, the time spent in the panel is displayed.
(a)(b)(c)(d)
(a) A path ends at a boundary point. (b) A path ends at dead-end point. (c)(d) Animation shows the
Simulation: self-avoiding random walk
) A self-avoiding walk in a lattice is a
avoiding walks have applications in physics, chemistry, and mathematics.
They can be used to model chainlike entities such as solvents and polymers.
ends at a point on the boundary, as shown in Figure 16.28(a), or ends at a dead-
end point (i.e., surrounded by four points that are already visited), as shown in
Animation: self-avoiding random walk
) Revise the preceding exercise to dis-
play the walk step by step in an animation, as shown in Figure 16.28(c)(d).
Simulation: self-avoiding random walk
) Write a simulation program to show
Chapter 16Event-Driven Programming
Exercise 16.33 animates a palindrome swing.
Exercise 16.34 animates a hangman game.
the user can remove a point by pointing to it and left-clicking the mouse, as
shown in Figure 16.29(c).
Clicking the or button increases or decreases the number of sides of a
regular polygon in Exercise 16.31. Exercise 16.32 allows the user to create/remove points
dynamically.
) Exercise 9.31 presents a console version of the popular hang-
Programming Exercises
(a)(b)(c)
Exercise 16.36 enables the user to click a cell to flip a coin.
REATING
NTERFACES
Objectives
Tocreate graphical user interfaces with various user-interface components:
To create listeners for various types of events (17.217.11).
To explore
To explore
To explore
To explore
To explore
To explore
To explore
To explore
To explore
To explore
To display multiple windows in an application (17.12).
Chapter 17Creating Graphical User Interfaces
Component
Container
JComponent
JToggleButton
JTextComponent
JComboBox
JList
JScrollBar
JSlider
JLabel
JButton
JRadioButton
JTextField
17.1
These Swing GUI components are frequently used to create user interfaces.
17.1Introduction
A graphical user interface (GUI) makes a system user friendly and easy to use. Creating a
GUI requires creativity and knowledge of how GUI components work. Since the GUI compo-
nents in Java are very flexible and versatile, you can create a wide assortment of useful user
interfaces.
Many Java IDEs provide tools for visually designing and developing GUI interfaces. This
enables you to rapidly assemble the elements of a user interface (UI) for a Java application or
are used to name reference variables for
17.2Buttons
button
is a component that triggers an action event when clicked. Swing provides regular
buttons, toggle buttons, check box buttons, and radio buttons. The common features of these
buttons are defined in
javax.swing.AbstractButton
, as shown in Figure 17.2.
This section introduces the regular buttons defined in the
and provides several constructors to create buttons, as shown in Figure 17.3.
17.2.1Icons, Pressed Icons, and Rollover Icons
A regular button has a default icon, a pressed icon, and a rollover icon. Normally you use the
default icon. The other icons are for special effects. A pressed icon is displayed when a button
is pressed, and a rollover icon is displayed when the mouse is over the button but not pressed.
naming convention for
17.2Buttons
-actionCommand: String
The action command of this button.
17.2
defines common features of different types of buttons.
For example, Listing 17.1 displays the American flag as a regular icon, the Canadian flag as a
pressed icon, and the British flag as a rollover icon, as shown in Figure 17.4.
17.1
javax.swing.AbstractButton
+JButton()
Creates a default button with no text and icon.
+addActionListener(listener:
Adds an
ActionListener
for the button.
17.3
defines a regular push button.
import
javax.swing.*;
2
public class
TestButtonIcons
extends
JFrame {
4
public static void
main(String[] args) {
5
fiibl()
17.4
A button can have several types of icons.
12 }
public
TestButtonIcons() {
15 ImageIcon usIcon =
new
ImageIcon(
"image/usIcon.gif"
);
16 ImageIcon caIcon =
new
ImageIcon(
"image/caIcon.gif"
);
17 ImageIcon ukIcon =
new
ImageIcon(
"image/ukIcon.gif"
);
18
new
JButton(
"Click it"
, usIcon);
(b) Pressed icon
(c) Rollover icon
Chapter 17Creating Graphical User Interfaces
17.2.2Alignments
specifies how the icon and text are placed horizontally on a button.
Horizontally center
Horizontally right
17.5
You can specify how the icon and text are placed on a button horizontally.
Vertically topVertically centerVertically bottom
17.6
You can specify how the icon and text are placed on a button vertically.
Vertical alignment
specifies how the icon and text are placed vertically on a button. You
17.2Buttons
17.2.3Text Positions
Horizontal text position
specifies the horizontal position of the text relative to the icon. You can
Text positioned centerText positioned right
17.7
You can specify the horizontal position of the text relative to the icon.
Vertical text position
specifies the vertical position of the text relative to the icon. You can
Text positioned topText positioned
17.8
You can specify the vertical position of the text relative to the icon.
The constants
are also used in many other Swing components. These constants are centrally
defined in the
interface. Since all Swing GUI components
implement
, you can reference the constants through
GUI component. For example,
can fire many types of events, but often you need to add listeners to respond to an
. When a button is pressed, it fires an
17.2.4Using Buttons
This section presents a program, shown in Listing 17.2, that displays a message on a panel
and uses two buttons,
, to move the message on the panel to the left or right. The
layout of the UI is shown in Figure 17.9.
1.Create the user interface.
class was
created in Listing 15.8, MessagePanel.java. Place it in the center of the frame. Create
two buttons,
Video Note
Chapter 17Creating Graphical User Interfaces
2.Process the event.
Create and register listeners for processing the action event to move the message left or
JButton jbtRight =
);
JButton jbtLeft =
);
"Welcome to Java"
MessagePanel messagePanel
JPanel
with
FlowLayout
17.9
buttons causes the message on the panel to move to the
left and right, respectively.
17.2Buttons
(a)(b)(c)
17.10
Chapter 17Creating Graphical User Interfaces
17.11
defines a check box button.
toggle button
Here is an example of a check box with text Student, foreground
mnemonic key
Video Note
Use check boxes
Creates a default check box button with no text and icon.
ActionListener
for this object.
Adds an
ItemListener
for this object.
17.3Check Boxes
with
GridLayout
for
three check boxes
17.12
Three check boxes are added to specify how the message is displayed.
There are at least two approaches to writing this program. The first is to revise the preced-
class to insert the code for adding the check boxes and processing their
events. The second is to create a subclass that extends
first approach as an exercise. Listing 17.3 gives the code to implement the second approach.
17.3
JCheckBox jchkItalic =
"Italic"
JCheckBox jchkBold =
"Bold"
JCheckBox jchkCentered =
"Centered"
register listener
register listener
Chapter 17Creating Graphical User Interfaces
itemStateChanged(ItemEvent e)
17.4Radio Buttons
17.4Radio Buttons
Radio buttons
, also known as
option buttons
of choices. In appearance radio buttons resemble check boxes, but check boxes display a
square that is either checked or blank, whereas radio buttons display a circle that is either
filled (if selected) or blank (if not selected).
and provides several constructors to create
radio buttons, as shown in Figure 17.13. These constructors are similar to the constructors for
Here is an example of a radio button with text
foreground,
ground, mnemonic key
Creates a default radio button with no text and icon.
17.13
defines a radio button.
Video Note
Use radio buttons
Chapter 17Creating Graphical User Interfaces
with
GridLayout
17.14
Three radio buttons are added to specify the color of the message.
is not a subclass of
not be added to a container.
When a radio button is changed (selected or deselected), it fires an
. To see if a radio button is selected, use the
Again there are at least two approaches to writing this program. The first is to revise the
class to insert the code for adding the radio buttons and processing
their events. The second is to create a subclass that extends
gives the code to implement the second approach.
17.4
"Red"
JRadioButton jrbRed, jrbGreen, jrbBlue;
extends
CheckBoxDemo
17.5Labels
group buttons
register listener
register listener
register listener
Chapter 17Creating Graphical User Interfaces
hAlignment: int)
17.15
displays text or an icon, or both.
. For example,
the following code displays a label with text and an icon:
17.6Text Fields
text field
ImageIcon(
"image/grapes.gif"
);
JLabel(
"Grapes"
Video Note
Use labels and text fields
17.6Text Fields
17.16
17.5
JTextField jtfMessage =
extends
RadioButtonDemo
create frame
with
BorderLayout
17.17
Chapter 17Creating Graphical User Interfaces
requestFocusInWindow()
wrap word
17.7Text Areas
17.18
Listing 17.7 gives a program that displays an image and a text in a label, and a text in a text
area, as shown in Figure 17.19.
DescriptionPanel
BorderLayout
A text area
17.19
The program displays an image in a label, a title in a label, and a text in the text area.
1.Create a class named
that extends
, as shown in Listing
17.6. This class contains a text area inside a scroll pane, and a label for displaying an
image icon and a title. This class is used in the present example and will be reused in
later examples.
2.Create a class named
that extends
, as shown in Listing 17.7.
Chapter 17Creating Graphical User Interfaces
TextAreaDemo
-jlblImage: JLabel
17.20
text description of a national flag.
17.7Text Areas
The text area is inside a
(line 27), which provides scrolling functions for the
text area. Scroll bars automatically appear if there is more text than the physical size of the
DescriptionPanel descriptionPanel =
create
create UI
Chapter 17Creating Graphical User Interfaces
Creates a default empty combo box.
17.21
17.8Combo Boxes
example. Place the combo box in the north of the frame and the description panel in the
2.Process the event.
JComboBox jcbo =
extends
JFrame
DescriptionPanel
17.22
A countrys info, including a flag image and a description of the flag, is dis-
Chapter 17Creating Graphical User Interfaces
17.9Lists
(line 28), which was presented in
Listing 17.6, DescriptionPanel.java. The program creates a combo box with initial values
-selectionForeground: Color
The index of the first selected item.
+addListSelectionListener(listener:
Adds a
ListSelectionListener
to this object.
17.23
(a) Single selection(b) Single-interval
17.24
has three selection modes: single selection, single-interval selection,
and multiple-interval selection.
Chapter 17Creating Graphical User Interfaces
with
GridLayout
An image is
JList
inside
a scroll
17.25
The following statements create a list with six items,
foreground,
selection foreground,
selection background, and visible row count
17.9Lists
event handler
Chapter 17Creating Graphical User Interfaces
Block decrement
Bubble
Block increment
Maximum value
Unit increment
17.26
A scroll bar represents a range of values graphically.
Normally, the user changes the value of the scroll bar by making a gesture with the mouse.
For example, the user can drag the scroll bars bubble up and down, or click in the scroll bars
unit-increment or block-increment areas. Keyboard gestures can also be mapped to the scroll
bar. By convention, the Page Up and Page Down keys are equivalent to clicking in the scroll
bars block-increment and block-decrement areas.
The width of the scroll bars track corresponds to
. When a scroll
bar is set to its maximum value, the left side of the bubble is at
has the following properties, as shown in Figure 17.27.
When the user changes the value of the scroll bar, the scroll bar fires an instance of
, which is passed to every registered listener. An object that wishes to be
notified of changes to the scroll bars value must implement the
17.10Scroll Bars
Listing 17.10 gives a program that uses horizontal and vertical scroll bars to control a mes-
sage displayed on a panel. The horizontal scroll bar is used to move the message to the left or
the right, and the vertical scroll bar to move it up and down. A sample run of the program is
shown in Figure 17.28.
int, extent: int, min: int, max: int)
Specifies horizontal or vertical style, default is horizontal.
reaches the right end of the scroll bar for horizontal style or the
Specifies the minimum value the scroll bar represents when the bubble
reaches the left end of the scroll bar for horizontal style or the top of
Specifies the relative width of the scroll bars bubble. The actual width
increment (decrement) area of the scroll bar, as shown in Figure
Specifies the value added (subtracted) when the user activates the unit-
increment (decrement) area of the scroll bar, as shown in Figure
Creates a default vertical scroll bar.
+addAdjustmentListener(listener:
Adds an
AdjustmentListener
to this object.
minimum, and maximum.
17.27
enables you to select from a range of values.
Horizontal scroll bar
Message panel
17.28
The scroll bars move the message on a panel horizontally and vertically.
1.Create the user interface.
object and place it in the center of the frame. Create a vertical
2.Process the event.
handler to move the
message according to the bar movement in the scroll bars.
Chapter 17Creating Graphical User Interfaces
17.10
vertical scroll bar
17.11Sliders
The program creates two scroll bars (
(lines 2930), respectively.
You can specify the orientation of the scroll bar in the constructor or use the
Horizontal slider
17.29
The sliders move the message on a panel horizontally and vertically.
Chapter 17Creating Graphical User Interfaces
When the user changes the value of the slider, the slider fires an instance of
, which is passed to any registered listeners. Any
object that wishes to be notified of changes to the sliders value must implement the
+JSlider(min: int, max: int)
The maximum value represented by the slider (default: 100).
JSlider.HORIZONTAL
).
True if the labels are painted at tick marks (default: false).
17.30
enables you to select from a range of values.
vertical slider
17.11Sliders
Chapter 17Creating Graphical User Interfaces
17.31
but has more features. As shown in this example, you can
(lines 3135). You can
also choose to hide the track (line 36). Since the values of a vertical slider decrease from top
17.12Creating Multiple Windows
17.12
// Register listener
25
/** Handle the button action */
27
public void
actionPerformed(ActionEvent e) {
28
JFrame histogramFrame =
Histogram histogram =
Chapter 17Creating Graphical User Interfaces
extends
JPanel
create main frame
17.12Creating Multiple Windows
MultipleWindowsDemo
-jta: JTextArea
17.32
Chapter 17Creating Graphical User Interfaces
You cannot add an instance of
to a container. For example, adding
to the main frame would cause a runtime exception. However, you can create a frame instance
UMMARY
You learned how to create graphical user interfaces using Swing GUI components
. You also learned how to handle
events on these components.
You can display a text and icon on buttons (
UESTIONS
Sections 17.217.4
17.1
How do you create a button labeled OK? How do you change text on a button?
Programming Exercises
ROGRAMMING
Pedagogical Note
Instructors may assign the exercises from the next chapter as exercises for this chapter.
Instead of writing Java applets, ask students to write Java applications.
Sections 17.217.5
17.1*
Revising Listing 17.2, ButtonDemo.java
) Rewrite Listing 17.2 to add a group of
radio buttons to select background colors. The available colors are red, yellow,
white, gray, and green (see Figure 17.33).
17.2*
17.33
The and buttons move the message on the panel, and you can also
FigurePanel
17.34
The program displays lines, rectangles, and ovals when you select a shape
17.35
Chapter 17Creating Graphical User Interfaces
(a)(b)
17.36
(a) The program displays the text from a file to a text area. (b) The program
Panel with
17.37
Programming Exercises
17.9**
Demonstrating
properties
17.39
GridLayout
Panel with
Panel with
GridLayout
for two combo boxes
BorderLayout
Panel with
BorderLayout
Panel with
GridLayout
for two combo boxes
Panel with
GridLayout
for two labels
17.40
17.38
The program displays the time specified in the text fields.
17.10*
Adding new features into Listing 17.2, ButtonDemo.java, incrementally
)Improve
Listing 17.2 incrementally, as follows (see Figure 17.41):
1.Add a text field labeled
"Enteranewmessage"
buttons. When you type a new message in the text field and press the
key, the new message is displayed in the message panel.
2.Add a combo box labeled
"Selectaninterval"
the buttons. The combo box enables the user to select a new interval for mov-
ing the message. The selection values range from
with interval
The user can also type a new interval in the combo box.
3.Add three radio buttons that enable the user to select the foreground color for
. The radio buttons are grouped in a
panel, and the panel is placed in the north of the frames content pane.
Chapter 17Creating Graphical User Interfaces
17.42
JTextArea
inside
a scroll pane
17.43
FlowLayout
Panel with
FlowLayout
MessagePanel
17.41
The program uses buttons, labels, text fields, combo boxes, radio buttons,
check boxes, and borders.
17.12*
Demonstrating
properties
Video Note
Use text areas
Programming Exercises
17.14*
shown inFigure17.45. When you select items, they are displayed in a label
below the list.
Sections 17.1117.13
17.15**
ground color for a label, as shown in Figure17.46
are used for selecting the red, green, and blue components of the color. Use a
17.16**
) Revise the preceding exercise using sliders.
17.17***
month, year, first day of the month, and number of days in the month.
JTextArea
inside
a scroll pane
17.44
given loan based on various interest rates.
JLabel
JList
inside a
scroll pane
17.45
You can choose single selection, single-interval selection, or multiple-interval
GridLayout
for three scroll bars
Panel with
Panel with
BorderLayout
17.46
The foreground color changes in the label as you adjust the scroll bars.
Chapter 17Creating Graphical User Interfaces
with
GridLayout
JLabel
17.47
17.48
Chapter 18Applets and Multimedia
18.1Introduction
When browsing the Web, often the graphical user interface and animation you see are devel-
18.1
The Sudoku game is displayed in a Web browser.
Video Note
First applet
18.3The HTML File and the
javax.swing.*;
DisplayLabel() {
new
"Great!"
, JLabel.CENTER));
Chapter 18Applets and Multimedia
18.3The HTML File and the
(b)
The DisplayLabel program is loaded from a local host in (a) and from a Web
server in (b).
Web Server
A Web browser requests an HTML page from a Web server.
Chapter 18Applets and Multimedia
(a)(b)
Video Note
Run applets standalone
18.5Enabling Applets to Run as Applications
main(String[] args) {
DisplayLabel() {
DisplayLabel
extends
create frame
Chapter 18Applets and Multimedia
LoadedInitialized
18.7Passing Strings to Applets
18.1
The HTML source file is given in Listing 18.4.
Y
�/
X
�/
= MESSAGE
value
"DisplayMessage.class"
Chapter 18Applets and Multimedia
init()
extends
18.7Passing Strings to Applets
privateint
privateint
isStandalone =
false
extends
Chapter 18Applets and Multimedia
18.8Case Study: Bouncing Ball
2.Create a subclass of
and two control buttons
, as shown in Listing 18.8.
Timer timer =
delay =
The balls movement is controlled by the Suspend and Resume buttons and the
scroll bar.
+BallControl()
1
+Ball()
+BounceBallApp()
18.10
Chapter 18Applets and Multimedia
paintComponent(Graphics g) {
TimerListener
implements
ActionListener {
button
18.8Case Study: Bouncing Ball
new
extends
JScrollBar jsbDelay =
JButton jbtResume =
"Resume"
register listener
register listener
register listener
new delay
Chapter 18Applets and Multimedia
(a) The X player won the game(b) Draw-no winners(c) The O player won the game
18.11
Two players play a TicTacToe game.
18.9Case Study: TicTacToe
From the many examples in this and earlier chapters you have learned about objects, classes,
18.12
class paints the token on a cell.
Video Note
TicTacToe
18.9Case Study: TicTacToe
The TicTacToe board consists of nine cells, created using
Indicates which player has the turn, initially X.

3, two-dimensional array for cells.
A label to display game status.
18.13
class, it can be defined as an inner
TicTacToe()
extends
Chapter 18Applets and Multimedia
extends
JPanel
isWon(
check rows
register listener
18.9Case Study: TicTacToe
mouseClicked(MouseEvent e)
MyMouseListener
extends
MouseAdapter {
paintComponent(Graphics g)
Chapter 18Applets and Multimedia
, you would
have to pass an object of
incremental development
A resource file
18.11Playing Audio in Any Java Program
You can now create an
Listing 18.11 gives the code that displays an image from
tory. The file
is under the class directory, and its URL is obtained using the
18.11
Chapter 18Applets and Multimedia
18.14
clip for the file. Line 14 repeatedly plays the audio.
18.12
18.12Case Study: Multimedia Animations
. They are stored under the
The program presents the nations, starting from the first one. For each nation, it displays its
flag and plays its anthem. When the audio for a nation finishes, the next nation is presented, and
so on. After the last nation is presented, the program starts to present all the nations again. You
button and resume it by clicking the
button, as shown in Figure 18.15. You can also directly select a nation from a combo box.
18.15
"Resume"
private
JButton jbtSuspend =
"Suspend"
private
JComboBox jcboNations =
21 {
"Denmark"
});
22
public
ImageAudioAnimation() {
24
// Load image icons and audio clips
25
i =
26 icons[i] =
AudioClip currentAudioClip;
AudioClip[] audioClips =
Video Note
Audio and image
Chapter 18Applets and Multimedia
Chapter Summary
A label is created in line 17 to display a flag image. An array of flag images for seven nations
created for an audio file through the URL of the current class. The audio files are stored in the
UMMARY
Chapter 18Applets and Multimedia
UESTIONS
18.1
javax.swing.*;
public class
javax.swing.*;
public class
(a)(b)
Programming Exercises
ROGRAMMING
Pedagogical Note
For every applet in the exercise, add a main method to enable it to run standalone.
18.1
DisplayMessage
extends
DisplayMessage
extends
(a) Revision 1
(b) Revision 2
Chapter 18Applets and Multimedia
18.16
(a)
(c)
18.17
New Game
button starts a new game. (c) The tax calculator computes the tax for the
specified taxable income and tax status.
Programming Exercises
Game: TicTacToe
) Rewrite the program in 18.9, Case Study: TicTacToe,
with the following modifications:
Add a button named
New Game
, as shown in Figure 18.17(b). The
New
button starts a new game.
Financial application: tax calculator
), division (
Converting numbers
18.11**
(b)
18.18
(a) Exercise 18.8 is a Java implementation of a popular calculator. (b) Exer-
Chapter 18Applets and Multimedia
(a)(b)
18.19
(a) The histogram displays the average temperature of every hour in the last
24 hours. (b) The program simulates a running fan.
18.12**
Controlling a group of fans
The program runs and controls a group of fans.
The program simulates elevator operations.
18.14*
Controlling a group of clocks
Video Note
Control a group of clocks
Programming Exercises
should continuously enlarge by 1 in width and 1 in height until it reaches a
width of 300 and a height of 300. The viewing area should shrink and enlarge
18.16***
Simulating a stock ticker
Three clocks run independently with individual control and group control.
The program displays a stock-index ticker.
18.17**
Racing cars
(b)
Chapter 18Applets and Multimedia
(b)
Programming Exercises
Creating an alarm clock
(a)(b)
The program displays current hour, minute, and second and enables you to
Chapter 18Applets and Multimedia
(b) After a session is started
(a) The traffic flows vertically(b) The traffic flows horizontally
Programming Exercises
vertically; when the light turns green, the traffic flows horizontally. The light
changes automatically every one minute. Before the light changes to red from
green, it first changes to yellow for a brief five seconds.
(a)(b)(c)
(a)(b)(c)(d)
Chapter 18Applets and Multimedia
one minute. When the minutes are expired, the program starts to play music
continuously.
Pattern recognition: consecutive four equal numbers
(a)(b)(c)
button to highlight the four consecutive numbers in a
INARY
Objectives
To discover how I/O is processed in Java (19.2).
Chapter 19Binary I/O
19.1Introduction
Data stored in a text file are represented in human-readable form. Data stored in a binary file
are represented in binary form. You cannot read binary files. They are designed to be read by
programs. For example, Java source programs are stored in text files and can be read by a text
editor, but Java classes are stored in binary files and are read by the JVM. The advantage of
binary files is that they are more efficient to process than text files.
Although it is not technically precise and correct, you can envision a text file as consisting
of a sequence of characters and a binary file as consisting of a sequence of bits. For example,
the decimal integer
, in a text
file, and the same integer is stored as a
-type value
in a binary file, because decimal
equals hex
Java offers many classes for performing file input and output. These can be categorized as
text I/Oclasses
binaryI/O classes.
In 9.7, File Input and Output, you learned how to
read/write strings and numeric values from/to a text file using
19.2How is I/O Handled in Java?
object encapsulates the properties of a file or a path but does not contain
19.3Text I/O vs. Binary I/O
Input object
created from an
input class
Output object
created from an
output class
Input stream
01011...1001
11001...1011
Output stream
File
19.1
The program receives data through an input object and sends data through an
The encoding of the character
is stored in the file
Binary I/O program
The Unicode of
Encoding/
199
"
e.g., 199
0x390x39
(b)
Text I/O requires encoding and decoding, whereas binary I/O does not.
encoding when writing a character and converts a file-specific encoding to a Unicode when
readinga character. For
example, suppose you write string
using text I/O to a file. Each
character is written to the file. Since the Unicode for character
is converted to a code that depends on the encoding scheme for the file. (Note that the
prefix
denotes a hex number.) In the United States, the default encoding for text files on Win-
dows is ASCII. The ASCII code for character
in hex) and for character
in hex). So to write the characters
sent to the output, as shown in Figure 19.2(a).
The new version of Java supports supplementary Unicode. For simplicity, however, this book con-
siders only the original Unicode from
Binary I/O does not require conversions. If you write a numeric value to a file using binary
I/O, the exact value in the memory is copied into the file. For example, a byte-type value
in the memory and appears exactly as
the file, as shown in Figure 19.2(b). When you read a byte using binary I/O, one byte value is
In general, you should use text input to read a file created by a text editor or a text output
program, and use binary input to read a file created by a Java binary output program.
Chapter 19Binary I/O
+
read(): int
+read(b: byte[]): int
19.4Binary I/O Classes
+FileInputStream(file: File)
FileInputStream
from a
File
object.
Creates a
FileInputStream
from a file name.
FileOutputStream
from a
File
object.
Creates a
FileOutputStream
from a file name.
If
append
is true, data are appended to the existing file.
If
append
is true, data are appended to the existing file.
inputs a stream of bytes from a file.
outputs a stream of bytes to a file.
len: int): void
All the methods in the binary I/O classes are declared to throw
19.4.1
is for reading/writing bytes from/to files. All the
with a nonexistent file.
To construct a
, use the constructors shown in Figure 19.7.
If the file does not exist, a new file will be created. If the file already exists, the first two con-
Chapter 19Binary I/O
main(String[] args)
throws
IOException
{
// Perform I/O operations
}
main(String[] args) {
try
{
// Perform I/O operations
}
catch
(IOException ex) {
ex.printStackTrace();
Using try-catch block
end of a file
is created for file
byte values into the file (lines 910). Invoking
is the same as invoking
for file
. Values are read from the file and displayed on the console in lines 1921.
The expression
((value=input.read())!=
"temp.dat"
"temp.dat"
IOException
19.4Binary I/O Classes
A binary file cannot be displayed in text mode.
The file
created in this example is a binary file. It can be read from a Java
program but not from a text editor, as shown in Figure 19.8.
Tip
When a stream is no longer needed, always close it using the
method. Not closing
streams may cause data corruption in the output file, or other programming errors.
The root directory for the file is the classpath directory. For the example in this book, the root
directory is
. So the file
. If you wish to place
in a specific directory, replace line 8 by
An instance of
can be used as an argument to construct a
an instance of
can be used as an argument to construct a
. You can create a
to append text into a file using
does not exist, it is created. If
already exists, new data are appended to the file.
Filter streams
are streams that filter bytes for some purpose. The basic byte input stream pro-
where is the file?
appending to text file
Chapter 19Binary I/O
19.10
enables you to write primitive data type values and strings into an output stream.
to
the output stream.
the output stream.
output stream.
to the output
stream, in order, 2 bytes per character.
value to the output stream.
value to the output stream.
value to the output stream.
value to the output stream.
value to the output stream.
string in UTF format.
(out: OutputStream)
interface

java.io.DataOutput
are copied from memory to the output without any conversions. Characters in a string may be
written in several ways, as discussed in the next section.
Characters and Strings in Binary I/O
A Unicode consists of two bytes. The
writeChar(charc)
from the input stream.
from the input stream.
from the input stream.
interface

java.io.DataInput
filters an input stream of bytes into primitive data type values and strings.
19.4Binary I/O Classes
, in two bytes if their code is greater than
"temp.dat"
);
"John"
"temp.dat"
Chapter 19Binary I/O
is created for file
are written to the file in lines 1015. Line 18 closes the output stream. A
is created for the same file in lines 2122. Student names and scores are read back from the
file and displayed on the console in lines 2527.
read and write Java primitive type values
and strings in a machine-independent fashion, thereby enabling you to write a data file on one
machine and read it on another machine that has a different operating system or file structure.
You have to read data in the same order and format in which they are stored. For example, since
names are written in UTF-8 using
, you must read names using
(EOFException ex) {
25 System.out.println(+
19.4Binary I/O Classes
19.11
buffers input stream.
BufferedInputStream
from an
InputStream
object.
Creates a
BufferedInputStream
from an
InputStream
object with specified buffer size.
+BufferedInputStream(in: InputStream)
java.io.InputStream
java.io.FilterInputStream
java.io.BufferedInputStream
The program writes three double values to the file using
(lines 1317). When reading past the end of file,
is thrown. The exception is caught in line 19.
BufferedOutputStream
from an
OutputStream
object.
Creates a
BufferedOutputStream
from an
OutputStream
object with specified size.
+BufferedOutputStream(out: OutputStream)
java.io.OutputStream
java.io.FilterOutputStream
java.io.BufferedOutputStream
19.12
buffers output stream.
Chapter 19Binary I/O
19.13
The program copies a file.
If no buffer size is specified, the default size is
bytes. A buffered input stream reads as
many data as possible into its buffer in a single read call. By contrast, a buffered output stream
Video Note
Copy file
19.5Problem: Copying Files
)r);
0]);check usagesource file
Chapter 19Binary I/O
java.io.ObjectInputStream
java.io.DataInput
interface
java.io.ObjectInput
interface
ObjectStreamConstants
19.14
can read objects, primitive type values, and strings.
java.io.ObjectOutputStream
java.io.DataOutput
interface
java.io.ObjectOutput
interface
ObjectStreamConstants
19.15
can write objects, primitive type values, and strings.
The expression
((r=input.read())!=
Video Note
19.6Object I/O
You may wrap an
on any
using the following constructors:
Listing 19.5 writes student names, scores, and current date to a file named
)throwsIOException {5// Create an output stream for file object.dat6789// Write a string, double value, and object to the file10 output.writeUTF("John");11 output.writeDouble(85.5);121314// Close output stream15 output.close();16 }17 }AnObjectOutputStreamis created to write data into file
a double value, and an object are written to the file in lines 1012. To improve performance,
you may add a buffer in the stream using the following statement to replace lines 67:
Multiple objects or primitives can be written to the stream. The objects must be read back
"object.dat"
"object.dat"
Chapter 19Binary I/O
// Close output stream
17 input.close();
Exception
transient
19.6Object I/O
is serialized. Variable
is not
serialized because it is a static variable, and variable
is not serialized because it is marked
were not marked
would occur.
If an object is written to an object stream more than once, will it be stored in multiple copies? No,
it will not. When an object is written for the first time, a serial number is created for it. The JVM
writes the complete content of the object along with the serial number into the object stream.
After the first time, only the serial number is stored if the same object is written again. When the
objects are read back, their references are the same, since only one object is actually created in the
memory.
19.6.2Serializing Arrays
An array is serializable if all its elements are serializable. An entire array can be saved using
into a file and later can be restored using
of five
values and an array of three strings and reads them back to display on the console.
"array.dat"
));
Chapter 19Binary I/O
stream with the specified file name,
string, and mode.
String)
mode: String)
java.io.DataOutput
interface
java.io.DataInput
19.16
Lines 1516 write two arrays into file
array.dat
same order they were written. Since
19.7Random-Access Files
both read and write. For example, the following statement creates a new stream,
allows the program to read from and write to the file
already exists,
does not exist, a new file
file pointer
For a
RandomAccessFileraf
empty file
readInt()
(a) Before
19.17
value is read, the file pointer is moved 4 bytes ahead.
Chapter 19Binary I/O
4
);
);
*
4
*
4
move pointer
close file
is created for the file named
to allow both
Review Questions
binary I/O650
deserialization664
file pointer667
random-access file667
sequential-access file666
serialization664
stream650
text I/O650
UMMARY
UESTIONS
Sections 19.119.2
19.1
What is a text file, and what is a binary file? Can you view a text file or a binary
file using a text editor?
How do you read or write data in Java? What is a stream?
Chapter 19Binary I/O
19.10
Review Questions
For each of the following statements on a
DataOutputStreamout
, how many
What are the advantages of using buffered streams? Are the following statements
Chapter 19Binary I/O
streams read and write a data file created by
stream for the file
address.dat
to allow the updat-
ing of student information in the file. Create a
for the file
address.dat
ROGRAMMING
19.1*
Creating a text file
) Write a program to create a file named
Exercise19_1.txt
does not exist. Append new data to it. Write 100 integers created randomly into the
file using text I/O. Integers are separated by a space.
Creating a binary data file
) Write a program to create a file named
Exercise19_2.dat
if it does not exist. Append new data to it. Write 100 integers
created randomly into the file using binary I/O.
Summing all the integers in a binary data file
) Suppose a binary data file named
Exercise19_3.dat
. The file contains an unspecified number of integers. Write a program to
find the sum of integers.
Converting a text file into UTF
a text and writes each line as a UTF-8 string into a binary file. Display the sizes of
the text file and the binary file. Use the following command to run the program:
Storing objects and arrays into a file
) Write a program that stores an array of five
values
value
into the file named
Exercise19_5.dat
Programming Exercises
19.18
(a)(b)
19.19
(a) The program splits a file. (b) The program combines files into a new file.
. Rewrite the
program that creates five
objects and stores them in a file named
Exercise19_6.dat
Restoring objects from a file
) Suppose a file named
Exercise19_7.dat
. The file contains
Rewrite the
objects from the file and computes the total loan amount. Sup-
pose you dont know how many
objects are in the file. Use
) Suppose you want to track how many times a program has
been executed. You may store an
to count the file. Increase the count by
Video Note
Split a large file
Chapter 19Binary I/O
outputs a stream of bits to a file.
19.12*
Combining files
Programming Exercises
(a)(b)
The exercises enable the user to manipulate the contents of the file in binary and hex.
19.20**
Objective
Chapter 20Recursion
20.1Introduction
Suppose you want to find all the files under a directory that contain a particular word. How do
you solve this problem? There are several ways to do so. An intuitive and effective solution is
to use recursion by searching the files in the subdirectories recursively.
The classic Eight Queens puzzle is to place eight queens on a chessboard such that no two
can attack each other (i.e., no two queens are on the same row, same column, or same diago-
nal), as shown in Figure 20.1. How do you write a program to solve this problem? A good
Touse recursion is to program using
(n-
(n-1)!
(n-1)!
, you can apply the same idea recursively until
20.1
The Eight Queens problem can be solved using recursion.
20.2Problem: Computing Factorials
)
n)
)
n)
infinite recursion
Chapter 20Recursion
Invoking
spawns recursive calls to
for
factorial(4)
n: 4
Space Required
for
factorial(4)
n: 4
Space Required
for
factorial(3)
n: 3
Space Required
for
factorial(4)
n: 4
Space Required
for
factorial(3)
n: 3
Space Required
for
factorial(2)
n: 2
Space Required
for
factorial(4)
n: 4
4
Space Required
for
factorial(3)
n: 3
Space Required
for
factorial(2)
n: 2
Space Required
for
factorial(1)
n: 1
Space Required
for
factorial(4)
n: 4
5
Space Required
for
factorial(3)
n: 3
Space Required
for
factorial(2)
n: 2
Space Required
for
factorial(1)
n: 1
Space Required
for
factorial(0)
n: 0
for
factorial(4)
n: 4
Space Required
for
factorial(3)
n: 3
Space Required
for
factorial(2)
n: 2
Space Required
for
factorial(1)
n: 1
for
factorial(4)
n: 4
Space Required
for
factorial(3)
n: 3
Space Required
for
factorial(2)
n: 2
Space Required
for
factorial(4)
n: 4
Space Required
for
factorial(3)
n: 3
for
factorial(4)
n: 4
1
is being executed, the
20.3Problem: Computing Fibonacci Numbers
Pedagogical Note
It is simpler and more efficient to implement the
method using a loop. However, we
use the recursive
method here to demonstrate the concept of recursion. Later in this
chapter, we will present some problems that are inherently recursive and are difficult to solve
without using recursion.
20.3Problem: Computing Fibonacci Numbers
immediately. Thus, the problem of computing
fib(index-2)
fib(index-1)
idea recursively until
index=0
index=1
Chapter 20Recursion
)
long
The program does not show the considerable amount of work done behind the scenes by the
computer. Figure 20.4, however, shows successive recursive calls for evaluating
Invoking
spawns recursive calls to
20.4Problem Solving Using Recursion
As shown in Figure 20.4, there are many duplicated recursive calls. For instance,
requires roughly twice as many recursive calls as does computing
fib(index-1)
try larger index values, the number of calls substantially increases.
Besides the large number of recursive calls, the computer requires more time and space to
recursive call
think recursively
Chapter 20Recursion
publicclass
isPalindrome(String s) {
isPalindrome(String s,
isPalindrome(String s) {
20.5Recursive Helper Methods
sort(
double
[] list,
Chapter 20Recursion
20 list[low] = min;2122// Sort the remaining list(low+1 .. high)2324 }25 }26 }Two overloaded
recursiveBinarySearch(
key,
recursiveBinarySearch(
recursive call
Video Note
Binary search
20.6Problem: Finding the Directory Size
f
A directory contains files and subdirectories.
The first
Video Note
Directory size
Chapter 20Recursion
21 size += ;
()all subitemsrecursive call
object represents a directory (line 18), each subitem (file or subdirectory) in the
directory is recursively invoked to obtain its size (line 21). If the
object represents a file
(line 24), the file size is obtained (line 25).
20.7Problem: Towers of Hanoi
The Towers of Hanoi is a classic computer-science problem, to which many Websites are devoted.
One of them worth looking at is
www.cut-the-knot.com/recurrence/hanoi.html
In the case of three disks, you can find the solution manually. For a larger number of disks,
howevereven for fourthe problem is quite complex. Fortunately, the problem has an
inherently recursive nature, which leads to a straightforward recursive solution.
n==1
, you could simply move the disk from A
, you could split the original problem into three subproblems and solve them
sequentially.
1.Move the first
disks from A to C with the assistance of tower B, as shown in Step
2.Move disk
from A to B, as shown in Step 2 in Figure 20.7.
3.Move
disks from C to B with the assistance of tower A, as shown in Step 3 in
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
The goal of the Towers of Hanoi problem is to move disks from tower A to
tower B without breaking the rules.
Chapter 20Recursion
B
B
n
n
n
n
The Towers of Hanoi problem can be decomposed into three subproblems.
Listing 20.8 gives a program that prompts the user to enter the number of disks and invokes
20.7Problem: Towers of Hanoi
19 {
24 ;
27 ;
n,
char
This problem is inherently recursive. Using recursion makes it possible to find a natural, sim-
ple solution. It would be difficult to solve the problem without using recursion.
. The successive recursive calls are shown in
Figure 20.8. As you can see, writing the program is easier than tracing the recursive calls.
The system uses stacks to trace the calls behind the scenes. To some extent, recursion pro-
moveDisks(1,'A','B','C')
moveDisks(2,'A','C','B')
moveDisks(1,'C','A','B')
moveDisks(2,'C','B','A')
move disk 1 from A to B
moveDisks(1,'B','C','A')
move disk 1 from B to C
moveDisks(1,'C','A','B')
move disk 1 from C to A
moveDisks(1,'A','B','C')
move disk 1 from A to B
Invoking
moveDisks(3,'A','B','C')
spawns calls to
recursively.
Chapter 20Recursion
(a) Order 0(b) Order 1
(c) Order 2(d) Order 3
A Sierpinski triangle is a pattern of recursive triangles.
20.8Problem: Fractals
fractal
Video Note
Fractal (Sierpinski triangle)
20.8Problem: Fractals
displayTriangles(Graphics g,
listener
Chapter 20Recursion
p3
p2
Draw the Sierpinski triangle
p12p31
20.10
Drawing a Sierpinski triangle spawns calls to draw three small Sierpinski
triangles recursively.
20.9Problem: Eight Queens
20.9Problem: Eight Queens
This section gives a recursive solution to the Eight Queens problem presented at the begin-
ning of the chapter. The task is to find a solution to place a queen in each row on a chessboard
such that no two queens can attack each other. You may use a two-dimensional array to repre-
sent a chessboard. However, since each row can have only one queen, it is sufficient to use a
one-dimensional array to denote the position of the queen in the row. So, you may define
as follows:
new int[8];Assignjtoqueens[i]to denote that a queen is placed in row
shows the contents of array
(a)(b)
20.11
denotes the position of the queen in row
isValid(
Chapter 20Recursion
// Place a queen at (row, column)30if(isValid(row, column) && )
)
20.11Tail Recursion
20.10Recursion vs. Iteration
Examples are the directory-size problem, the Towers of Hanoi problem, and the fractal prob-
lem, which are rather difficult to solve without using recursion.
(a)
search(row)
(b)
(c)
(d)
search(row

1)
20.12
Invoking
fills in a queen in a column on the row.
recursion overhead
recursion advantages
Chapter 20Recursion
(lines 613) in Listing 20.4 is tail recursive because there are no pending operations after
recursively invoking
in line 12. However, the recursive
base case678
infinite recursion679
UMMARY
Review Questions
UESTIONS
Sections 20.120.3
20.1
Test {
public static void
main(String[] args) {
System.out.println(
"Sum is "
Test {
public static void
main(String[] args) {
Chapter 20Recursion
20.14
Show the output of the following two programs:
Test {
main(String[] args) {
Test {
Test test =
new
Test();
System.out.println(test.toString());
}
new
Test();
}
}
20.15
Test {
main(String[] args) {
Test {
public static void
main(String[] args) {
20.16
ROGRAMMING
20.1*
Factorial
class introduced in 14.12, you can find the
factorial for a large number (e.g.,
fib(n-2)
fib(n-1)
Programming Exercises
Computing greatest common divisor using recursion
gcd(m,n)
be defined recursively as follows:
gcd(m,n)
gcd(m,n)
gcd(n,m%n)
+
2
+

+
i
+
1
m
1
i
2
=
1
+
2
+
3
+
4
+
5
+
6
+

+
i
1
m
1
i
2
=
1
+
1
+
1
+

+
1
Chapter 20Recursion
20.12**
Printing the characters in a string reversely
) Rewrite Exercise 20.9 using a
(a)(b)
20.13
(a) Exercise 20.19 uses the
Increase
Decrease
buttons to increase or
Programming Exercises
Displaying circles
Chapter 20Recursion
Kochsnowflake fractal
) The text presented the Sierpinski triangle fractal. In
(a) Correct path(b) Illegal path
20.14
The program finds a path from the upper-left corner to the bottom-right corner.
(a)(b)(c)(d)
20.15
A Koch snowflake is a fractal starting with a triangle.
Nonrecursive directory size
) Rewrite Listing 20.7, DirectorySize.java, without
Number of files in a directory
directory and displays the number of the files in the directory.
Finding words
) Write a program that finds all occurrences of a word in all the files
Video Note
Search a string in a directory
Programming Exercises
Game: Knights Tour
) The Knights Tour is an ancient puzzle. The objective is to
move a knight, starting from any square on a chessboard, to every other square
once, as shown in Figure 20.16(a). Note that the knight makes only L-shape moves
(two spaces in one direction and one space in a perpendicular direction). As shown
in Figure 20.16(b), the knight can move to eight squares. Write a program that dis-
20.17
A knight traverses along the path.
0
6
(a)
(b)
(c)
20.16
Chapter 20Recursion
(a)(b)(c)(d)
20.18
20.19
Recursive tree
(a)(b)(c)(d)
A recursive tree with the specified depth.
Appendix A
Java Keywords
Appendix B
Java Keywords
The following fifty keywords are reserved for use by the Java language:
TABLEB.2
TABLE B.1
Operator Precedence Chart
The operators are shown in decreasing order of precedence from top to bottom. Operators in
the same group have the same precedence, and their associativity is shown in the table.
Operator
Parentheses
Unary logical negation
Division
Right shift with sign extension
Right shift with zero extension
Operator
(Exclusive OR)
Ternary condition
Division assignment
Java Modifiers
Modifier
block
A final class cannot be
*Default access has no modifier associated with it. For example:
Modifier
block
the evaluation result is the
instance data field.
E.1
Special Floating-Point Values
*
y
+
y
-
y
q
q
q
q
q
q
q
q
q
q
q
q
Special Floating-Point Values
Dividing an integer by zero is invalid and throws
Number Systems
1Introduction
Computers use binary numbers internally, because computers are made naturally to store and
process 0s and 1s. The binary number system has two digits, 0 and 1. A number or character
gram, it is assumed to be a decimal number. Internally, computer software is used to convert
decimal numbers into binary numbers, and vice versa.
Wewrite computer programs using decimal numbers. However, to deal with an operating
system, we need to reach down to the machine level by using binary numbers. Binary num-
bers tend to be very long and cumbersome. Often hexadecimal numbers are used to abbrevi-
ate them, with each hexadecimal digit representing four binary digits. The hexadecimal
7
*
16
4
*
16
2
*
16
3
*
16
*
16
7
*
16
*
16
*
16
2
2
2
=
8
+
4
+
0
+
1
=
13

1

1

0

1

10
7
*
10
4
*
10
2
*
10
3
*
10
hexadecimal number
Binary
Conversion Formula
*
2
0
*
2
*
2
0
*
2
0
*
2
0
*
2
*
2
1
*
2
*
2
0
*
2
1
*
2
0
*
2
1
*
2
0
*
2
Decimal
Hex
F.1
You can perform number conversions using the Windows Calculator.
b
b
Quotient
14
b
30
b
60
61
b
b
122
1
123
30
Tip
The Windows Calculator, as shown in Figure F.1, is a useful tool for performing number conver-
sions. To run it, choose
Programs
Accessories
Calculator
from the
Start
View
Scientific
Hexadecimal
Conversion Formula
*
16
15
*
16
*
16
15
*
16
15
*
16
15
*
16
*
16
3
*
16
1
*
16
Toconvert a decimal number
to a hexadecimal number is to find the hexadecimal digits
and such that
These numbers can be found by successively dividing
mainders are and
For example, the decimal number 123 is 7B in hexadecimal. The conversion is done as
follows:
167
16123
1110001101
binary to hex
UESTIONS
Convert the following decimal numbers into hexadecimal and binary numbers.
Convert the following binary numbers into hexadecimal and decimal numbers.
Convert the following hexadecimal numbers into binary and decimal numbers.
F.1
Converting Hexadecimal to Binary
Hexadecimal
operator, truth table for, 88
operator, truth table for, 88
character, 29
(division), 33
(division assignment operator), 37
operator, truth table for, 88
operator, truth table for, 88
Index
Assignment operator, 3031
Associativity, 9798
ImageAudioAnimation.java, 635637
playing in Java programs, 634
BallControl.java, 626627
Ball.java, 625626
BASIC, 6
Behavior, of objects, 264
Binary files, 650, 652
copying files (problem), 660662
random access files, 666668
interface, 664665
TestFileStream.java, 654655
text I/O vs., 650652
Index
Combo boxes, 590593
ComboBoxDemo.java, 591593
defined, 590
Command-line arguments, 320322
Common design error, 281, 364
Communication devices, 2, 5
interface, 467469
ComparableRectangle.java, 468469
Index
Event, defined, 484
Event-driven programming, 534560
defined, 534
Events:
key, 555557
Exception, defined, 435
advantages of, 434437
custom exception classes, 448450
exception types, 437439
overview, 432434
Quotient.java, 432
QuotientWithException.java, 433434
QuotientWithIf.java, 432433
TestFileClass.java, 324325
ReadFileUsingJFileChooser.java, 329330
WriteData.java, 325326
relative, 323
File pointer, 666668
Files, naming consistently, 423
Index
Index
Java class, 265, 272
java ClassName, 15
java command, 15, 22
Java compiler, 12, 14
Java Development Toolkit (JDK), 10
Java Enterprise Edition (Java EE), 10
Java expressions, evaluating, 3637
.java extension, 14
.java file, 14
Java GUI API, 406408
Java keywords,
Keywords
Java language specification, 1011
Java Micro Edition (Java ME), 10
Java modifiers,
Modifiers
Java program-development process, 13
Java program, simple, 1113
Java source-code file, creating, 14
Java source programs, case sensitivity of, 14
Java Standard Edition (Java SE), 10
Java Virtual Machine (JVM), 14, 208
Index
Index
Index
Regular expression, 307
Relative file name, 324
Index
Subinterface, 474
SubtractionQuiz.java, 8384
SubtractionQuizLoop.java, 121122
Subwindows, 602
ragged array, 238
Type casting, 31, 410
defined, 41
explicit casting, 4142
syntax for, 41
UML (Unified Modeling Language)
Unary operator, 35
Unchecked exceptions, 439
Underflow, 33
supplementary, 45, 651
DisplayImagePlayAudio.java, 634
DisplayImageWithURL.java, 633
USB flash drives, 4
UseGuessDateClass.java, 360361
User actions, source object and event type, 534
User interfaces:
buttons, 572578
ButtonDemo.java, 576578
defined, 572
rollover icons, 572573
TestButtonIcons.java, 573574
text positions, 575
check boxes, 578581
combo boxes, 590593
Index
multiple windows, creating, 602606
radio buttons, 581583
text areas, 586589
text fields, 584586

Приложенные файлы

  • pdf 1030489
    Размер файла: 10 MB Загрузок: 0

Добавить комментарий