Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 2
Elementary Programming
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations
In the preceding chapter, you learned how to create,
compile, and run a Java program. Starting from this
chapter, you will learn how to solve practical problems
programmatically. Through these problems, you will learn
Java primitive data types and related subjects, such as
variables, constants, data types, operators, expressions,
and input and output.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (1 of 2)
2.1 To write Java programs to perform simple computations (§2.2).
2.2 To obtain input from the console using the Scanner class (§2.3).
2.3 To use identifiers to name variables, constants, methods, and classes (§2.4).
2.4 To use variables to store data (§§2.5–2.6).
2.5 To program with assignment statements and assignment expressions (§2.6).
2.6 To use constants to store permanent data (§2.7).
2.7 To name classes, methods, variables, and constants by following their naming
conventions (§2.8).
2.8 To explore Java numeric primitive data types: byte, short, int, long, float, and
double (§2.9).
2.9 To read a byte, short, int, long, float, or double value from the keyboard (§2.9.1).
2.10 To perform operations using operators +, , , , and
* / %
 (§2.9.2).
2.11 To perform exponent operations using Math.pow(a, b) (§2.9.3).
2.12 To write integer literals, floating-point literals, and literals in scientific notation (§2.10).
2.13 To use JShell to quickly test Java code (§2.11).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (2 of 2)
2.14 To write and evaluate numeric expressions (§2.12).
2.15 To obtain the current system time using System.currentTimeMillis() (§2.13).
2.16 To use augmented assignment operators (§2.14).
2.17 To distinguish between postincrement and preincrement and between
postdecrement and predecrement (§2.15).
2.18 To cast the value of one type to another type (§2.16).
2.19 To describe the software development process and apply it to develop the loan
payment program (§2.17).
2.20 To write a program that converts a large amount of money into smaller units (§2.18).
2.21 To avoid common errors and pitfalls in elementary programming (§2.19).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introducing Programming With an
Example
Listing 2.1 Computing the Area of a Circle
This program computes the area of the circle.
ComputeArea Note: Clicking the green button displays
the source code with interactive
animation. You can also run the code in
a browser. Internet connection is
needed for this button.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (1 of 5)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (2 of 5)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (3 of 5)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (4 of 5)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (5 of 5)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Reading Input From the Console
1. Create a Scanner object
Scanner input = new Scanner(System.in);
2. Use the method nextDouble() to obtain to a double
value. For example,
System.out.print("Enter a double value: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();
ComputeAreaWithConsoleInput ComputeAverage
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Implicit Import and Explicit Import
java.util.* ; // Implicit import
java.util.Scanner; // Explicit Import
No performance difference
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Identifiers
• An identifier is a sequence of characters that consist of
letters, digits, underscores (_), and dollar signs ($).
• An identifier must start with a letter, an underscore (_), or
a dollar sign ($). It cannot start with a digit.
• An identifier cannot be a reserved word. (See Appendix
A, “Java Keywords,” for a list of reserved words).
• An identifier cannot be true, false, or null.
• An identifier can be of any length.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Variables
// Compute the first area
radius = 1.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ + area + "
for radius "+radius);
// Compute the second area
radius = 2.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ + area + "
for radius "+radius);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Declaring Variables
int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Assignment Statements
x = 1; // Assign 1 to x;
radius = 1.0; // Assign 1.0 to radius;
a = 'A'; // Assign 'A' to a;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Declaring and Initializing in One Step
• int x = 1;
• double d = 1.4;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Named Constants
final datatype CONSTANTNAME = VALUE;
final double PI = 3.14159;
final int SIZE = 3;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Naming Conventions (1 of 2)
• Choose meaningful and descriptive names.
• Variables and method names:
– Use lowercase. If the name consists of several words,
concatenate all in one, use lowercase for the first
word, and capitalize the first letter of each subsequent
word in the name. For example, the variables radius
and area, and the method computeArea.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Naming Conventions (2 of 2)
• Class names:
– Capitalize the first letter of each word in the name.
For example, the class name ComputeArea.
• Constants:
– Capitalize all letters in constants, and use
underscores to connect words. For example, the
constant PI and MAX_VALUE
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Numerical Data Types
Name Range Storage Size
byte
negative 2 to the power 7 to 2 to the power 7 minus 1 left parenthesis negative 128 to 127 right parenthesis.
8-bit signed
short
negative 2 to the power 15 to 2 to the power 15 minus 1 left parenthesis (negative 32768 to 32767 right parenthesis.
16-bit signed
int
negative 2 to the power 31 to 2 to the power 31 minus 1 left parenthesis negative 2147483648 to 2147483647 right parenthesis.
32-bit signed
long negative 2 to the power 63 to 2 to the power 63 minus 1 left parenthesis that is,
negative 9223372036854775808 to 9223372036854775807 right parenthesis.
64-bit signed
float
negative range, negative -3.4028235 E + 38 to negative 1.4 E minus 45, positive range, 1.4 E minus 45 to 3.4028235 E + 38.
32-bit IEEE 754
double
negative range, negative 1.7976931348623157 E + 308 to negative 4.9 E minus 324, positive range, 4.9 E minus 324 to 1.7976931348623157 E + 308.
64-bit IEEE 754
 
7 7
2 to 2 1 128 to 127
  
 
15 15
2 to 2 1 32768 to 32767
  
 
31 31
2 to 2 1 2147483648 to 2147483647
  
 
63 63
2 to 2 1
i.e., 9223372036854775808 to 9223372036854775807
 

Negative range:
3.4028235E 38 to 1.4E 45
Positive range:
1.4E 45 to 3.4028235E 38
   
 
Negative range:
1.7976931348623157E 308 to 4.9E 324
Positive range:
4.9E 324 to 1.7976931348623157E 308
   
 
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Reading Numbers From the Keyboard
Scanner input = new Scanner(System.in);
int value = input.nextInt();
Method Description
nextByte() reads an integer of the byte type.
nextShort() reads an integer of the short type.
nextInt() reads an integer of the int type.
nextLong() reads an integer of the long type.
nextFloat() reads a number of the float type.
nextDouble() reads a number of the double type.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Numeric Operators
Name Meaning Example Result
+ Addition 34 + 1 35
The symbol of minus
Subtraction 34.0 minus 0.1
33.9
* Multiplication 300 times 30
9000
division slash
Division
1.0 divided by 2.0.
0.5
symbol of modulo remainder
Remainder
20 modulo remainder 3
2
 34.0 0.1

300 * 30
/ 1.0 / 2.0
% 20 % 3
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Integer Division
+, ,
 *, /, and %
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
5 % 2 yields 1 (the remainder of the division)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Remainder Operator
Remainder is very useful in programming. For example, an
even number % 2 is always 0 and an odd number % 2 is
always 1. So you can use this property to determine
whether a number is even or odd. Suppose today is
Saturday and you and your friends are going to meet in 10
days. What day is in 10 days? You can find that day is
Tuesday using the following expression:
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Displaying Time
Write a program that obtains minutes and remaining
seconds from seconds.
DisplayTime
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Note
Calculations involving floating-point numbers are
approximated because these numbers are not stored
with complete accuracy. For example,
System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
displays 0.5000000000000001, not 0.5, and
System.out.println(1.0 - 0.9);
displays 0.09999999999999998, not 0.1. Integers are
stored precisely. Therefore, calculations with integers
yield a precise integer result.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Exponent Operations
System.out.println(Math.pow(2, 3));
// Displays 8.0
System.out.println(Math.pow(4, 0.5));
// Displays 2.0
System.out.println(Math.pow(2.5, 2));
// Displays 6.25
System.out.println(Math.pow(2.5, -2));
// Displays 0.16
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Number Literals
A literal is a constant value that appears directly in the
program. For example, 34, 1,000,000, and 5.0 are literals
in the following statements:
int i = 34;
long x = 1000000;
double d = 5.0;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Integer Literals
An integer literal can be assigned to an integer variable as
long as it can fit into the variable. A compilation error would
occur if the literal were too large for the variable to hold.
For example, the statement byte b = 1000 would cause a
compilation error, because 1000 cannot be stored in a
variable of the byte type.
An integer literal is assumed to be of the int type, whose
value is between    
31 31
2 2147483648 to 2 1 2147483647 .
  
To denote an integer literal of the long type, append it with
the letter L or l. L is preferred because l (lowercase L) can
easily be confused with 1 (the digit one).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Floating-Point Literals
Floating-point literals are written with a decimal point. By
default, a floating-point literal is treated as a double type
value. For example, 5.0 is considered a double value, not a
float value. You can make a number a float by appending
the letter f or F, and make a number a double by appending
the letter d or D. For example, you can use 100.2f or 100.2F
for a float number, and 100.2d or 100.2D for a double
number.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
double versus float
The double type values are more accurate than the float
type values. For example,
System.out.println("1.0 / 3.0 is " + 1.0 /
3.0);
displays
16 digits
3
1 0.3333333333 33333
.0 / 3.0 is
System.out.println("1.0F / 3.0F is " + 1.0F
/ 3.0F);
displays
7 digits
0.33333334
1.0 / 3.0 is
F F
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Scientific Notation
Floating-point literals can also be specified in scientific
notation, for example, 1.23456e+2, same as 1.23456e2, is
equivalent to 123.456, and 
1.23456e 2 is equivalent to
0.0123456. E (or e) represents an exponent and it can be
either in lowercase or uppercase.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
JShell
JShell is a command line interactive tool introduced in Java
9. JShell enables you to type a single Java statement and
get it executed to see the result right away without having
to write a complete class. This feature is commonly known
as REPL (Read-Evaluate-Print Loop), which evaluates
expressions and executes statements as they are entered
and shows the result immediately.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Arithmetic Expressions
  
10 5
3 4 4 9
9( )
5
y a b c
x x
x x y
  
 
  
is translated to
       
 
3 4 * / 5 10 * 5 * / 9 * 4 / 9 /
x y a b c x x x y
       
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
How to Evaluate an Expression
Though Java has its own way to evaluate an expression
behind the scene, the result of a Java expression and its
corresponding arithmetic expression are the same.
Therefore, you can safely apply the arithmetic rule for
evaluating a Java expression.
3 + 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
53
(1) inside parentheses
first
(2) multiplication
(3) multiplication
(4) addition
(6) subtraction
(5) addition
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Converting Temperatures
Write a program that converts a Fahrenheit degree to
Celsius using the formula:
 
5
32
9
celsius fahrenheit
 
 
 
 
Note: you have to write
   
 
celsius 5.0 / 9 * fahrenheit 32
FahrenheitToCelsius
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Displaying Current Time
Write a program that displays current time in GMT in the
format hour:minute:second such as 1:45:19.
The currentTimeMillis method in the System class returns
the current time in milliseconds since the midnight, January
1, 1970 GMT. (1970 was the year when the Unix operating
system was formally introduced.) You can use this method
to obtain the current time, and then compute the current
second, minute, and hour as follows.
ShowCurrentTime
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Augmented Assignment Operators
Operator Name Example Equivalent
+= Addition assignment i += 8 i = i + 8
negative = Subtraction assignment i minus = 8 I = I minus 8
*= Multiplication assignment i *= 8 i = i * 8
forward slash =
Division assignment I forward slash = 8 I = I over 8
%= Remainder assignment i %= 8 i = i % 8
  i -= 8 i= i - 8
/ = i / = 8 i= i / 8
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Increment and Decrement Operators (1 of 3)
Operator Name Description Example (assume i = 1)
++var preincrement Increment var by 1, and use
the new var value in the
statement
int j = ++i;
// j is 2, i is 2
var++ postincrement Increment var by 1, but use
the original var value in the
statement
int j = i++;
// j is 1, i is 2
dash dash variable;
predecrement Decrement var by 1, and use
the new var value in the
statement
int j = --i;
// j is 0, i is 0
variable dash dash;
postdecrement Decrement var by 1, and use
the original var value in the
statement
int j = i--;
// j is 1, i is 0
-- var
var --
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Increment and Decrement Operators (2 of 3)
int i = 10;
int newNum = 10 * i++; int newNum = 10 * i;
i = i + 1;
Same effect as
int i = 10;
int newNum = 10 * (++i); i = i + 1;
int newNum = 10 * i;
Same effect as
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Increment and Decrement Operators (3 of 3)
Using increment and decrement operators makes
expressions short, but it also makes them complex and
difficult to read. Avoid using these operators in expressions
that modify multiple variables, or the same variable for
multiple times such as this: int k = ++i + i.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Assignment Expressions and
Assignment Statements
Prior to Java 2, all the expressions can be used as
statements. Since Java 2, only the following types of
expressions can be statements:
variable op= expression; // Where op is +, , *, /, or %
++variable;
variable++;
  variable;
 
variable ;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Numeric Type Conversion
Consider the following statements:
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Conversion Rules
When performing a binary operation involving two
operands of different types, Java automatically converts the
operand based on the following rules:
1. If one of the operands is double, the other is converted
into double.
2. Otherwise, if one of the operands is float, the other is
converted into float.
3. Otherwise, if one of the operands is long, the other is
converted into long.
4. Otherwise, both operands are converted into int.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Type Casting
Implicit casting
double d = 3; (type widening)
Explicit casting
int i = (int)3.0; (type narrowing)
int i = (int)3.9; (Fraction part is truncated)
What is wrong? int x = 5 / 2.0;
byte, short, int, long, float, double
range increases
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Keeping Two Digits After
Decimal Points
Write a program that displays the sales tax with two digits
after the decimal point.
SalesTax
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Casting in an Augmented Expression
In Java, an augmented expression of the form x1 op= x2 is
implemented as x1 = (T)(x1 op x2), where T is the type for
x1. Therefore, the following code is correct.
int sum = 0;
sum += 4.5; // sum becomes 4 after this statement
sum += 4.5 is equivalent to sum = (int)(sum + 4.5).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Software Development Process
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Requirement Specification
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
System Analysis
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
System Design
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
IPO
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Implementation
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Testing
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Deployment
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Maintenance
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Computing Loan Payments
This program lets the user enter the interest rate, number of
years, and loan amount, and computes monthly payment
and total payment.
 
12
1
1
1
numberOfYears
loanAmount monthlyInterestRate
monthlyPayment
monthlyInterestRate





ComputeLoan
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Monetary Units
This program lets the user enter the amount in decimal
representing dollars and cents and output a report listing
the monetary equivalent in single dollars, quarters, dimes,
nickels, and pennies. Your program should report
maximum number of dollars, then the maximum number of
quarters, and so on, in this order.
ComputeChange
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Common Errors and Pitfalls
• Common Error 1: Undeclared/Uninitialized Variables and
Unused Variables
• Common Error 2: Integer Overflow
• Common Error 3: Round-off Errors
• Common Error 4: Unintended Integer Division
• Common Error 5: Redundant Input Objects
• Common Pitfall 1: Redundant Input Objects
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Common Error 1: Undeclared/Uninitialized
Variables and Unused Variables
double interestRate = 0.05;
double interest = interestrate * 45;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Common Error 2: Integer Overflow
int value = 2147483647 + 1;
// value will actually be 2147483648
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Common Error 3: Round-off Errors
System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
System.out.println(1.0 - 0.9);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Common Error 4: Unintended Integer
Division
int number1 = 1;
int number2 = 2;
double average = (number1 + number2) / 2;
System.out.println(average);
(a)
int number1 = 1;
int number2 = 2;
double average = (number1 + number2) / 2.0;
System.out.println(average);
(b)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Common Pitfall 1: Redundant Input
Objects
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int v1 = input.nextInt();
Scanner input1 = new Scanner(System.in);
System.out.print("Enter a double value: ");
double v2 = input1.nextDouble();
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 3
Selections
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations
If you assigned a negative value for radius in Listing 2.2,
ComputeAreaWithConsoleInput.java, the program would
print an invalid result. If the radius is negative, you don't
want the program to compute the area. How can you deal
with this situation?
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (1 of 2)
3.1 To declare boolean variables and write Boolean
expressions using relational operators (§3.2).
3.2 To implement selection control using one-way if statements
(§3.3).
3.3 To implement selection control using two-way if-else
statements (§3.4).
3.4 To implement selection control using nested if and multi-
way if statements (§3.5).
3.5 To avoid common errors and pitfalls in if statements (§3.6).
3.6 To generate random numbers using the Math.random()
method (§3.7).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (2 of 2)
3.7 To program using selection statements for a variety of
examples (SubtractionQuiz, BMI, ComputeTax) (§§3.7–3.9).
3.8 To combine conditions using logical operators (&&, ||, and !)
(§3.10).
3.9 To program using selection statements with combined
conditions (LeapYear, Lottery) (§§3.11–3.12).
3.10 To implement selection control using switch statements and
expressions (§3.13).
3.11 To write expressions using the conditional expression (§3.14).
3.12 To examine the rules governing operator precedence and
associativity (§3.15).
3.13 To apply common techniques to debug errors (§3.16).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The boolean Type and Operators
Often in a program you need to compare two values, such
as whether i is greater than j. Java provides six comparison
operators (also known as relational operators) that can be
used to compare two values. The result of the comparison
is a Boolean value: true or false.
boolean b = (1 > 2);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Relational Operators
Java
Operator
Mathematics
Symbol
Name Example
(radius is 5)
Result
< < less than radius < 0 false
<=
Less than or equal to
less than or equal to radius <= 0 false
> > greater than radius > 0 true
>=
Greater than or equal to
greater than or equal to radius >= 0 true
== = equal to radius == 0 false
!=
Not equal to
not equal to radius != 0 true



Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: A Simple Math Learning Tool
This example creates a program to let a first grader
practice additions. The program randomly generates two
single-digit integers number1 and number2 and displays a
question such as “What is 7 + 9?” to the student. After the
student types the answer, the program displays a message
to indicate whether the answer is true or false.
AdditionQuiz
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
One-Way if Statements
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Note
if i > 0 {
System.out.println("i is positive");
}
(a) Wrong (b) Correct
if (i > 0) {
System.out.println("i is positive");
}
if (i > 0) {
System.out.println("i is positive");
}
(a)
Equivalent
(b)
if (i > 0)
System.out.println("i is positive");
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Simple if Demo
Write a program that prompts the user to enter an integer.
If the number is a multiple of 5, print HiFive. If the number
is divisible by 2, print HiEven.
SimpleIfDemo
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Two-Way if Statement
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
if-else Example
if (radius >= 0) {
area = radius * radius * 3.14159;
System.out.println("The area for the “
+ “circle of radius " + radius +
" is " + area);
}
else {
System.out.println("Negative input");
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Multiple Alternative if Statements
if (score >= 90.0)
System.out.print("A");
else
if (score >= 80.0)
System.out.print("B");
else
if (score >= 70.0)
System.out.print("C");
else
if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
(a)
Equivalent
if (score >= 90.0)
System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
(b)
This is better
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Multi-Way if-else Statements
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace if-else Statement (1 of 5)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace if-else Statement (2 of 5)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace if-else Statement (3 of 5)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace if-else Statement (4 of 5)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace if-else Statement (5 of 5)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Note (1 of 2)
The else clause matches the most recent if clause in the
same block.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Note (2 of 2)
Nothing is printed from the preceding statement. To force the else
clause to match the first if clause, you must add a pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
This statement prints B.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Common Errors
Adding a semicolon at the end of an if clause is a common mistake.
This mistake is hard to find, because it is not a compilation error or
a runtime error, it is a logic error.
This error often occurs when you use the next-line block style.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
TIP
if (number % 2 == 0)
even = true;
else
even = false;
(a)
Equivalent boolean even
= number % 2 == 0;
(b)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
CAUTION
if (even == true)
System.out.println(
"It is even.");
(a)
Equivalent if (even)
System.out.println(
"It is even.");
(b)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: An Improved Math Learning
Tool
This example creates a program to teach a first grade child
how to learn subtractions. The program randomly
generates two single-digit integers number1 and number2
with number1 >= number2 and displays a question such as
“What is 
9 2?” to the student. After the student types the
answer, the program displays whether the answer is correct.
SubtractionQuiz
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Body Mass Index
Body Mass Index (BMI) is a measure of health on
weight. It can be calculated by taking your weight in
kilograms and dividing by the square of your height in
meters. The interpretation of BMI for people 16 years or
older is as follows:
BMI Interpretation
BMI < 18.5 Underweight
18.5 <= BMI < 25.0 Normal
25.0 <= BMI < 30.0 Overweight
30.0 <= BMI Obese
ComputeAndInterpretBMI
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Computing Taxes (1 of 2)
The US federal personal income tax is calculated based on
the filing status and taxable income. There are four filing
statuses: single filers, married filing jointly, married filing
separately, and head of household. The tax rates for 2009
are shown below.
Marginal
Tax Rate Single
Married Filing Jointly or
Qualifying Widow(er)
Married Filing
Separately Head of Household
10% $0 - $8,350 $0 - $16,700 $0 - $8,350 $0 - $11,950
15% $8,351 - $33,950 $16,701 - $67,900 $8,351 - $33,950 $11,951 - $45,500
25% $33,951 - $82,250 $67,901 - $137,050 $33,951 - $68,525 $45,501 - $117,450
28% $82,251 - $171,550 $137,051 - $208,850 $68,526 - $104,425 $117,451 - $190,200
33% $171,551 - $372,950 $208,851 - $372,950 $104,426 - $186,475 $190,201 - $372,950
35% $372,951+ $372,951+ $186,476+ $372,951+
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Computing Taxes (2 of 2)
if (status == 0) {
// Compute tax for single filers
}
else if (status == 1) {
// Compute tax for married file jointly
// or qualifying widow(er)
}
else if (status == 2) {
// Compute tax for married file separately
}
else if (status == 3) {
// Compute tax for head of household
}
else {
// Display wrong status
} ComputeTax
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Logical Operators
Operator Name Description
! not logical negation
&& and logical conjunction
|| or logical disjunction
^ exclusive or logical exclusion
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Truth Table for Operator !
p !p Example (assume age = 24, weight = 140)
true false !(age > 18) is false, because (age > 18) is true.
false true !(weight == 150) is true, because (weight == 150) is false.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Truth Table for Operator &&
p1 p2 p1 && p2 Example (assume age = 24, weight = 140)
false false false
(age <= 18) && (weight < 140) is false,
because both conditions are both false.
false true false Blank
true false false
(age > 18) && (weight > 140) is false, because
(weight > 140) is false.
true true true
(age > 18) && (weight >= 140) is true, because
both (age > 18) and (weight >= 140) are true.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Truth Table for Operator ||
p1 p2 p1 || p2 Example (assume age = 24, weight = 140)
false false false Blank
false true true
(age > 34) || (weight <= 140) is true, because
(age > 34) is false, but (weight <= 140) is true.
true false true
(age > 14) || (weight >= 150) is false, because
(age > 14) is true.
true true true Blank
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Truth Table for Operator ^
p1 p2 p1 ^ p2 Example (assume age = 24, weight = 140)
false false false
(age > 34) ^ (weight > 140) is true, because
(age > 34) is false and (weight > 140) is false.
false true true
(age > 34) ^ (weight >= 140) is true, because
(age > 34) is false but (weight >= 140) is true.
true false true
(age > 14) ^ (weight > 140) is true, because
(age > 14) is true and (weight > 140) is false.
true true false Blank
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Examples (1 of 2)
Here is a program that checks whether a number is
divisible by 2 and 3, whether a number is divisible by 2 or
3, and whether a number is divisible by 2 or 3 but not both:
TestBooleanOperators
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Examples (2 of 2)
System.out.println("Is " + number + " divisible by 2 and 3? " +
((number % 2 == 0) && (number % 3 == 0)));
System.out.println("Is " + number + " divisible by 2 or 3? " +
((number % 2 == 0) || (number % 3 == 0)));
System.out.println("Is " + number +
" divisible by 2 or 3, but not both? " +
((number % 2 == 0) ^ (number % 3 == 0)));
TestBooleanOperators
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The & and | Operators (1 of 2)
Supplement III.B, “The & and | Operators”
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The & and | Operators (2 of 2)
If x is 1, what is x after this expression?
(x > 1) & (x++ < 10)
If x is 1, what is x after this expression?
(1 > x) && ( 1 > x++)
How about (1 == x) | (10 > x++)?
(1 == x) || (10 > x++)?
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Determining Leap Year?
This program first prompts the user to enter a year as an
int value and checks if it is a leap year.
A year is a leap year if it is divisible by 4 but not by 100, or
it is divisible by 400.
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
LeapYear
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Lottery
Write a program that randomly generates a lottery of a two-
digit number, prompts the user to enter a two-digit number,
and determines whether the user wins according to the
following rule:
• If the user input matches the lottery in exact order, the
award is $10,000.
• If the user input matches the lottery, the award is $3,000.
• If one digit in the user input matches a digit in the lottery,
the award is $1,000.
Lottery
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
switch Statements
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(1);
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
switch Statement Flow Chart
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
switch Statement Rules (1 of 2)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
switch Statement Rules (2 of 2)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace switch Statement (1 of 7)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace switch Statement (2 of 7)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace switch Statement (3 of 7)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace switch Statement (4 of 7)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace switch Statement (5 of 7)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace switch Statement (6 of 7)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace switch Statement (7 of 7)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Chinese Zodiac
Write a program that prompts the user to enter a year and
displays the animal for the year.
ChineseZodiac
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
118
JDK 14 Arrow Operator (->)
Forgetting a break statement when it is needed is a common
error. To avoid this type of errors, JDK 14 introduced a new
arrow operator (->). You can use the arrow operator to replace
the colon operator (:). With the arrow operator, there is no
need to use the break statement. When a case is matched, the
matching statement(s) are executed, and the switch statement
is finished.
int day = 1;
switch (day) {
case 1 -> System.out.print(1 + " ");
case 2 -> System.out.print(2 + " ");
case 3 -> System.out.print(3 + " ");
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
119
JDK 14 switch Expression
Java 14 also introduced switch expressions. A switch expression
returns a value. Here is an example:
int day = 1;
System.out.println(
switch (day) {
case 1 -> 1 + " ";
case 2 -> 2 + " ";
case 3 -> 3 + " ";
default -> " ";
}
);
The switch expression in this example returns a string. A
switch expression must cover all cases, while a switch
statement does not have to cover all cases. In the preceding
example, the default clause is to required to cover the
integers not listed in the cases.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
120
JDK 14 switch Combining Cases
In Java 14, the cases can be combined. For example, the
preceding code can be simplified as follows:
int day = 1;
System.out.println(
switch (day) {
case 1, 2, 3 -> day + " ";
default -> " ";
}
);
case 1, 2, 3 means case 1, case 2, or case 3.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
121
The yield Keyword
In Java 14, the cases can be combined. For example, the
preceding code can be simplified as follows:
int day = 1;
System.out.println(
switch (day) {
case 1, 2, 3 -> day + " ";
default -> " ";
}
);
case 1, 2, 3 means case 1, case 2, or case 3.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
122
The yield Keyword
If the result for a matching case in a switch expression is not a
simple value, you need to use the yield keyword to return the
value. Here is an example,
int year = 2000;
int month = 2;
System.out.println(
switch (month) {
case 2 -> {
if (isLeapYear(year))
yield "29 days";
else
yield "28 days";
}
default -> " ";
}
);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Conditional Operators
if (x > 0)
y = 1
else
y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
(boolean-expression) ? expression1 : expression2
Ternary operator
Binary operator
Unary operator
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Conditional Operator (1 of 2)
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);
System.out.println(
(num % 2 == 0)? num + “is even” :
num + “is odd”);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Conditional Operator (2 of 2)
boolean-expression ? exp1 : exp2
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Operator Precedence
• var++, var--
• +, - (Unary plus and minus), ++var,--var
• (type) Casting
• ! (Not)
• *, /, % (Multiplication, division, and remainder)
• +, - (Binary addition and subtraction)
• <, <=, >, >= (Relational operators)
• ==, !=; (Equality)
• ^ (Exclusive OR)
• && (Conditional AND) Short-circuit AND
• || (Conditional OR) Short-circuit OR
• =, +=, -=, *=, /=, %= (Assignment operator)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Operator Precedence and Associativity
The expression in the parentheses is evaluated first.
(Parentheses can be nested, in which case the expression
in the inner parentheses is executed first.) When evaluating
an expression without parentheses, the operators are
applied according to the precedence rule and the
associativity rule.
If operators with the same precedence are next to each
other, their associativity determines the order of evaluation.
All binary operators except assignment operators are left-
associative.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Operator Associativity
When two operators with the same precedence are
evaluated, the associativity of the operators determines
the order of evaluation. All binary operators except
assignment operators are left-associative.
a b c d
   is equivalent to ((a b) c) d
  
Assignment operators are right-associative. Therefore,
the expression
a b c 5
    is equivalent to a (b (c 5))
   
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example
Applying the operator precedence and associativity rule,
the expression 3 4 * 4 5 * (4 3) 1
    is evaluated as
follows:
3 + 4 * 4 > 5 * (4 + 3) - 1
3 + 4 * 4 > 5 * 7 – 1
3 + 16 > 5 * 7 – 1
3 + 16 > 35 – 1
19 > 35 – 1
19 > 34
false
(1) inside parentheses first
(2) multiplication
(3) multiplication
(4) addition
(5) subtraction
(6) greater than
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Operand Evaluation Order
Supplement III.A, “Advanced discussions on how an
expression is evaluated in the JVM.”
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Debugging
Logic errors are called bugs. The process of finding and
correcting errors is called debugging. A common approach
to debugging is to use a combination of methods to narrow
down to the part of the program where the bug is located.
You can hand-trace the program (i.e., catch errors by
reading the program), or you can insert print statements in
order to show the values of the variables or the execution
flow of the program. This approach might work for a short,
simple program. But for a large, complex program, the
most effective approach for debugging is to use a debugger
utility.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Debugger
Debugger is a program that facilitates debugging. You can
use a debugger to
• Execute a single statement at a time.
• Trace into or stepping over a method.
• Set breakpoints.
• Display variables.
• Display call stack.
• Modify variables.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Debugging in NetBeans
Supplement II.E, Learning Java Effectively with NetBeans
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Debugging in Eclipse
Supplement II.G, Learning Java Effectively with Eclipse
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 4
Mathematical Functions,
Characters, and Strings
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations
Suppose you need to estimate the area enclosed by four
cities, given the GPS locations (latitude and longitude) of
these cities, as shown in the following diagram. How would
you write a program to solve this problem? You will be able
to write such a program after completing this chapter.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (1 of 2)
4.1 To solve mathematics problems by using the methods in the Math class
(§4.2).
4.2 To represent characters using the char type (§4.3).
4.3 To encode characters using ASCII and Unicode (§4.3.1).
4.4 To represent special characters using the escape sequences (§4.4.2).
4.5 To cast a numeric value to a character and cast a character to an integer
(§4.3.3).
4.6 To compare and test characters using the static methods in the Character
class (§4.3.4).
4.7 To introduce objects and instance methods (§4.4).
4.8 To represent strings using the String objects (§4.4).
4.9 To return the string length using the length() method (§4.4.1).
4.10 To return a character in the string using the charAt(i) method (§4.4.2).
4.11 To use the + operator to concatenate strings (§4.4.3).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (2 of 2)
4.12 To return an uppercase string or a lowercase string and to trim a string
(§4.4.4).
4.13 To read strings from the console (§4.4.4).
4.14 To read a character from the console (§4.4.5).
4.15 To compare strings using the equals method and the compareTo
methods (§4.4.6).
4.16 To obtain substrings (§4.4.7).
4.17 To find a character or a substring in a string using the indexOf method
(§4.4.8).
4.18 To program using characters and strings (GuessBirthday) (§4.5.1).
4.19 To convert a hexadecimal character to a decimal value (HexDigit2Dec)
(§4.5.2).
4.20 To revise the lottery program using strings (LotteryUsingStrings)
(§4.5.3).
4.21 To format output using the System.out.printf method (§4.6).
4.22 To form multi-line strings using text blocks (§4.7).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Mathematical Functions
Java provides many useful methods in the Math class for
performing common mathematical functions.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Math Class
• Class constants:
– PI
– E
• Class methods:
– Trigonometric Methods
– Exponent Methods
– Rounding Methods
– min, max, abs, and random Methods
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trigonometric Methods
• sin(double a)
• cos(double a)
• tan(double a)
• acos(double a)
• asin(double a)
• atan(double a)
Radians
toRadians(90)
Examples:
Math.sin(0) returns 0.0
Math.sin(Math.PI / 6)
returns 0.5
Math.sin(Math.PI / 2)
returns 1.0
Math.cos(0) returns 1.0
Math.cos(Math.PI / 6)
returns 0.866
Math.cos(Math.PI / 2)
returns 0
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Exponent Methods
• exp(double a)
Returns e raised to the power of a.
• log(double a)
Returns the natural logarithm of a.
• log10(double a)
Returns the 10-based logarithm of
a.
• pow(double a, double b)
Returns a raised to the power of b.
• sqrt(double a)
Returns the square root of a.
Examples:
Math.exp(1) returns 2.71
Math.log(2.71) returns 1.0
Math.pow(2, 3) returns 8.0
Math.pow(3, 2) returns 9.0
Math.pow(3.5, 2.5) returns
22.91765
Math.sqrt(4) returns 2.0
Math.sqrt(10.5) returns 3.24
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Rounding Methods
• double ceil(double x)
x rounded up to its nearest integer. This integer is returned as a
double value.
• double floor(double x)
x is rounded down to its nearest integer. This integer is returned as a
double value.
• double rint(double x)
x is rounded to its nearest integer. If x is equally close to two
integers, the even one is returned as a double.
• int round(float x)
Return (int)Math.floor(x+0.5).
• long round(double x)
Return (long)Math.floor(x+0.5).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Rounding Methods Examples
Math.ceil(2.1) returns 3.0
Math.ceil(2.0) returns 2.0
Math.ceil(-2.0) returns –2.0
Math.ceil(-2.1) returns -2.0
Math.floor(2.1) returns 2.0
Math.floor(2.0) returns 2.0
Math.floor(-2.0) returns –2.0
Math.floor(-2.1) returns -3.0
Math.rint(2.1) returns 2.0
Math.rint(2.0) returns 2.0
Math.rint(-2.0) returns –2.0
Math.rint(-2.1) returns -2.0
Math.rint(2.5) returns 2.0
Math.rint(-2.5) returns -2.0
Math.round(2.6f) returns 3
Math.round(2.0) returns 2
Math.round(-2.0f) returns -2
Math.round(-2.6) returns -3
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
min, max, and abs
• max(a, b) and min(a, b)
Returns the maximum or
minimum of two parameters.
• abs(a)
Returns the absolute value of
the parameter.
• random()
Returns a random double value
in the range [0.0, 1.0).
Examples:
Math.max(2, 3) returns 3
Math.max(2.5, 3) returns
3.0
Math.min(2.5, 3.6)
returns 2.5
Math.abs(-2) returns 2
Math.abs(-2.1) returns
2.1
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The random Method
Generates a random double value greater than or equal to
0.0 and less than 1.0 (0 <= Math.random() < 1.0).
Examples:
(int)(Math.random() * 10)
Returns a random integer
between 0 and 9.
50 + (int)(Math.random() * 50)
Returns a random integer
between 50 and 99.
In general,
a + Math.random() * b
Returns a random number between
a and a + b, excluding a + b.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Computing Angles of a
Triangle
A
B
C
a
b
c
A = acos((a * a - b * b - c * c) / (-2 * b * c))
B = acos((b * b - a * a - c * c) / (-2 * a * c))
C = acos((c * c - b * b - a * a) / (-2 * a * b))
x1, y1
x2, y2
x3, y3
Write a program that prompts the user to enter the x- and
y-coordinates of the three corner points in a triangle and
then displays the triangle’s angles.
ComputeAngles
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Character Data Type
NOTE: The increment and decrement operators can also be
used on char variables to get the next or preceding Unicode
character. For example, the following statements display
character b.
char ch = 'a';
System.out.println(++ch);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Unicode Format
Java characters use Unicode, a 16-bit encoding scheme
established by the Unicode Consortium to support the
interchange, processing, and display of written texts in the
world’s diverse languages. Unicode takes two bytes,
preceded by u, expressed in four hexadecimal numbers
that run from 'u0000' to 'uFFFF'. So, Unicode can
represent 65535 + 1 characters.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
ASCII Code for Commonly Used
Characters
Characters Code Value in Decimal Unicode Value
'0' to '9' 48 to 57 u0030 to u0039
'A' to 'Z' 65 to 90 u0041 to u005A
'a' to 'z' 97 to 122 u0061 to u007A
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Escape Sequences for Special
Characters
Escape Sequence Name Unicode Code Decimal Value
b Backspace u0008 8
t Tab u0009 9
n Linefeed u000A 10
f Formfeed u000C 12
r Carriage Return u000D 13
 Backslash u005C 92
” Double Quote u0022 34
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Appendix B: ASCII Character Set (1 of 2)
ASCII Character Set is a subset of the Unicode from u0000 to u007f
TABLE B.1 ASCII Character Set in the Decimal Index
Blank
0 1 2 3 4 5 6 7 8 9
0 nul soh stx etx eot enq ack bel bs ht
1 nl vt ff cr so si dle dcl dc2 dc3
2 dc4 nak syn etb can em sub esc fs gs
3 rs us sp ! “ # $ % & ‘
4 ( ) * + , - . / 0 1
5 2 3 4 5 6 7 8 9 : ;
6 < = > ? @ A B C D E
7 F G H I J K L M N O
8 P Q R S T U V W X Y
9 Z [  ] ^ _ ` a b c
10 d e f g h i j k l m
11 n o p q r s t u v w
12 x y z { | } ~ del
Blank Blank
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Appendix B: ASCII Character Set (2 of 2)
ASCII Character Set is a subset of the Unicode from u0000 to u007f
TABLE B.2 ASCII Character Set in the Hexadecimal Index
Blank
0 1 2 3 4 5 6 7 8 9 A B C D E F
0 nul soh stx etx eot enq ack bel bs ht nl vt ff cr so si
1 dle dcl dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us
2 sp ! “ # $ % & ‘ ( ) * + , - . /
3 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
4 @ A B C D E F G H I J K L M N O
5 P Q R S T U V W X Y Z [  ] ^ _
6 ‘ a b c d e f g h i j k l m n o
7 p q r s t u v w x y z { | } ~ del
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Casting between char and Numeric
Types
int i = 'a'; // Same as int i = (int)'a';
char c = 97; // Same as char c = (char)97;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Comparing and Testing Characters
if (ch >= 'A' && ch <= 'Z')
System.out.println(ch + " is an uppercase letter");
else if (ch >= 'a' && ch <= 'z')
System.out.println(ch + " is a lowercase letter");
else if (ch >= '0' && ch <= '9')
System.out.println(ch + " is a numeric character");
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Methods in the Character Class
Method Description
isDigit(ch) Returns true if the specified character is a digit.
isLetter(ch) Returns true if the specified character is a letter.
isLetterOfDigit(ch) Returns true if the specified character is a letter or
digit.
isLowerCase(ch) Returns true if the specified character is a
lowercase letter.
isUpperCase(ch) Returns true if the specified character is an
uppercase letter.
toLowerCase(ch) Returns the lowercase of the specified character.
toUpperCase(ch) Returns the uppercase of the specified character.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The String Type
The char type only represents one character. To represent a string
of characters, use the data type called String. For example,
String message = "Welcome to Java";
String is actually a predefined class in the Java library just like the
System class and Scanner class. The String type is not a primitive
type. It is known as a reference type. Any Java class can be used
as a reference type for a variable. Reference data types will be
thoroughly discussed in Chapter 9, “Objects and Classes.” For the
time being, you just need to know how to declare a String variable,
how to assign a string to the variable, how to concatenate strings,
and to perform simple operations for strings.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Simple Methods for String Objects (1 of 2)
Method Description
length() Returns the number of characters in this string.
charAt(index) Returns the character at the specified index from this string.
concat(s1) Returns a new string that concatenates this string with
string s1.
toUpperCase() Returns a new string with all letters in uppercase.
toLowerCase() Returns a new string with all letters in lowercase.
trim() Returns a new string with whitespace characters trimmed
on both sides.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Simple Methods for String Objects (2 of 2)
Strings are objects in Java. The methods in the preceding
table can only be invoked from a specific string instance.
For this reason, these methods are called instance
methods. A non-instance method is called a static
method. A static method can be invoked without using an
object. All the methods defined in the Math class are static
methods. They are not tied to a specific object instance.
The syntax to invoke an instance method is
referenceVariable.methodName(arguments).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Getting String Length
String message = "Welcome to Java";
System.out.println("The length of " + message + " is "
+ message.length());
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Getting Characters from a String
String message = "Welcome to Java";
System.out.println("The first character in message is "
+ message.charAt(0));
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Converting Strings
"Welcome".toLowerCase() returns a new string, welcome.
"Welcome".toUpperCase() returns a new string,
WELCOME.
" Welcome ".trim() returns a new string, Welcome.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
String Concatenation
String s3 = s1.concat(s2); or String s3 = s1 + s2;
// Three strings are concatenated
String message = "Welcome " + "to " + "Java";
// String Chapter is concatenated with number 2
String s = "Chapter" + 2; // s becomes Chapter2
// String Supplement is concatenated with character B
String s1 = "Supplement" + 'B'; // s1 becomes SupplementB
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Reading a String From the Console
Scanner input = new Scanner(System.in);
System.out.print("Enter three words separated by
spaces: ");
String s1 = input.next();
String s2 = input.next();
String s3 = input.next();
System.out.println("s1 is " + s1);
System.out.println("s2 is " + s2);
System.out.println("s3 is " + s3);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Reading a Character From the Console
Scanner input = new Scanner(System.in);
System.out.print("Enter a character: ");
String s = input.nextLine();
char ch = s.charAt(0);
System.out.println("The character entered is " + ch);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Comparing Strings
Method Description
equals(s1) Returns true if this string is equal to string s1.
equalsIgnoreCase(s1) Returns true if this string is equal to string s1;
it is case insensitive.
compareTo(s1) Returns an integer greater than 0, equal to 0,
or less than 0 to indicate whether this string is
greater than, equal to, or less than s1.
compareToIgnoreCase(s1) Same as compareTo except that the
comparison is case insensitive.
startsWith(prefix) Returns true if this string starts with the
specified prefix.
endsWith(suffix) Returns true if this string ends with the
specified suffix.
OrderTwoCities
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Obtaining Substrings
Method Description
substring(beginIndex) Returns this string’s substring that begins with the
character at the specified beginIndex and extends to
the end of the string, as shown in Figure 4.2.
substring(beginIndex,
endIndex)
Returns this string’s substring that begins at the specified
beginIndex and extends to the character at index
endIndex – 1, as shown in Figure 9.6. Note that the
character at endIndex is not part of the substring.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Finding a Character or a Substring in a
String (1 of 2)
Method Description
indexOf(ch) Returns the index of the first occurrence of ch in the string.
Returns -1 if not matched.
indexOf(ch, fromIndex) Returns the index of the first occurrence of ch after
fromIndex in the string. Returns -1 if not matched.
indexOf(s) Returns the index of the first occurrence of string s in this
string. Returns -1 if not matched.
indexOf(s, fromIndex) Returns the index of the first occurrence of string s in this string
after fromIndex. Returns -1 if not matched.
lastIndexOf(ch) Returns the index of the last occurrence of ch in the string.
Returns -1 if not matched.
lastIndexOf(ch, fromIndex) Returns the index of the last occurrence of ch before
fromIndex in this string. Returns -1 if not matched.
lastIndexOf(s) Returns the index of the last occurrence of string s. Returns -1
if not matched.
lastIndexOf(s, fromIndex) Returns the index of the last occurrence of string s before
fromIndex. Returns -1 if not matched.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Finding a Character or a Substring in a
String (2 of 2)
int k = s.indexOf(' ');
String firstName = s.substring(0, k);
String lastName = s.substring(k + 1);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Conversion between Strings and
Numbers
int intValue = Integer.parseInt(intString);
double doubleValue = Double.parseDouble(doubleString);
String s = number + "";
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Guessing Birthday
The program can guess your birth date. Run to see how it
works.
GuessBirthday
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Mathematics Basis for the Game
19 is 10011 in binary. 7 is 111 in binary. 23 is 11101 in
binary
10000
10
+ 1
10011
00110
10
+ 1
00111
19 7
10000
1000
100
+ 1
11101
23
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Converting a Hexadecimal
Digit to a Decimal Value
Write a program that converts a hexadecimal digit into a
decimal value.
HexDigit2Dec
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Revising the Lottery
Program Using Strings
A problem can be solved using many different approaches.
This section rewrites the lottery program in Listing 3.7 using
strings. Using strings simplifies this program.
LotteryUsingStrings
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Formatting Output
Use the printf statement.
System.out.printf(format, items);
Where format is a string that may consist of substrings and
format specifiers. A format specifier specifies how an item
should be displayed. An item may be a numeric value,
character, boolean value, or a string. Each specifier begins
with a percent sign.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Frequently-Used Specifiers
Specifier Output Example
%b a boolean value true or false
%c a character 'a'
%d a decimal integer 200
%f a floating-point number 45.460000
%e a number in standard
scientific notation
4.556000e+01
%s a string "Java is cool"
int count = 5;
double amount = 45.56;
System.out.printf("count is %d and amount is %f", count, amount);
display count is 5 and amount is 45.560000
items
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
FormatDemo
The example gives a program that uses printf to display a
table.
FormatDemo
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
179
Text blocks became a standard feature since Java 15. It
enables you to form a multi-line string. Here is an example of a
text block:
String tb = """
Java
Python
C++""";
System.out.println(tb);
The code displays three
lines
Java
Python
C++
A text block contains multiple line. The first line starts with
three double quotation marks (""") followed by space
characters. The last line ends with three double quotation
marks (""").
Text Blocks
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
180
You can use indentation in a text block. To achieve this, the
compiler first removes the maximum left common space
characters for all lines. For example, the maximum common
left space characters for all lines in the following text block is
2, because there are two leading space characters before
“Java”.
String tb = """
Java
Python
C++""";
After removing two leading space
characters from each line, the resulting
string is
Java
Python
C++
After removing the maximum common left space characters,
the indentation of the text block is preserved.
Indentation in Text Blocks
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
181
Indentation in Text Blocks: ending """
Note if the ending """ is on a separate line by itself, its
leading spaces are counted in the maximum common left
space. For example, in the following code,
String tb = """
Java
Python
C++
""";
The maximum common left space is 0, because
there are no space before the ending """. The
resulting string will be
Java
Python
C++
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
182
Right Trailing Space
The right trailing space are trimmed by default. If you want to
keep right trailing space, use s. For example, the following
code keep three right space characters after “Python”.
String tb = """
Java
Python s
C++""";
Note that there are two spaces
after Python and before s.
Including s, there will be three
spaces after “Python”.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
183
Escape Characters
You used s escape character for a space. You can also use
other escape characters in needed. For example, for the
following text block:
String tb = """
Java
tPythonn
C++""";
The resulting string is
Java
Python
C++
The space before “Python” is due to the tab character (t). The
space line after “Python” is due to the new line character “n”.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
184
""" in Text Block as Literal
If you need to put """ into the text block, you can use """. For
example, for the following text block:
String tb = """
Java"""
Python
C++""";
The resulting string is
Java"""
Python
C++
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
185
New String Methods
As part of the new feature on text blocks, several new String
methods are introduced. You can use the stripIndent() to
remove the maximum common left space from a multi-line
string in the same way as a text block is processed.
You can use the formatted(args) method to format a string.
For example, for the following code:
String tb = """
Product: %s
Price: $%.2f""".formatted("Salt", 4.52);
The resulting string is
Produce: Salt
Price: $4.52
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 5
Loops
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations
Suppose that you need to print a string (e.g., "Welcome to
Java!") a hundred times. It would be tedious to have to
write the following statement a hundred times:
System.out.println("Welcome to Java!");
So, how do you solve this problem?
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Opening Problem
Problem:
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introducing while Loops
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java");
count++;
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (1 of 2)
5.1 To write programs for executing statements repeatedly
using a while loop (§5.2).
5.2 To write loops for the guessing number problem (§5.3).
5.3 To follow the loop design strategy to develop loops (§5.4).
5.4 To control a loop with a sentinel value (§5.4).
5.5 To obtain large input from a file using input redirection
rather than typing from the keyboard (§5.5).
5.6 To write loops using do-while statements (§5.6).
5.7 To write loops using for statements (§5.7).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (2 of 2)
5.8 To discover the similarities and differences of three types of
loop statements (§5.8).
5.9 To write nested loops (§5.9).
5.10 To learn the techniques for minimizing numerical errors
(§5.10).
5.11 To learn loops from a variety of examples (GCD,
FutureTuition, Dec2Hex) (§5.11).
5.12 To implement program control with break and continue
(§5.12).
5.13 To process characters in a string using a loop in a case
study for checking palindrome (§5.13).
5.14 To write a program that displays prime numbers (§5.14).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
while Loop Flow Chart
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (1 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (2 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (3 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (4 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (5 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (6 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (7 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (8 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (9 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Repeat Addition Until Correct
Recall that Listing 3.1 AdditionQuiz.java gives a program
that prompts the user to enter an answer for a question on
addition of two single digits. Using a loop, you can now
rewrite the program to let the user enter a new answer until
it is correct.
RepeatAdditionQuiz
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Guessing Numbers
Write a program that randomly generates an integer
between 0 and 100, inclusive. The program prompts the
user to enter a number continuously until the number
matches the randomly generated number. For each user
input, the program tells the user whether the input is too
low or too high, so the user can choose the next input
intelligently. Here is a sample run:
GuessNumberOneTime
GuessNumber
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: An Advanced Math Learning
Tool
The Math subtraction learning tool program generates just
one question for each run. You can use a loop to generate
questions repeatedly. This example gives a program that
generates five questions and reports the number of the
correct answers after a student answers all five questions.
SubtractionQuizLoop
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Ending a Loop with a Sentinel Value
Often the number of times a loop is executed is not
predetermined. You may use an input value to signify the
end of the loop. Such a value is known as a sentinel
value.
Write a program that reads and calculates the sum of an
unspecified number of integers. The input 0 signifies the
end of the input.
SentinelValue
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Caution (1 of 3)
Don’t 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 inaccurate results. Consider the
following code for computing 1 + 0.9 + 0.8 + ... + 0.1:
double item = 1; double sum = 0;
while (item != 0) { // No guarantee item will be 0
sum += item;
item −= 0.1;
}
System.out.println(sum);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
do-while Loop
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
for Loops
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (1 to 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (2 to 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (3 to 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (4 to 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (5 to 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (6 to 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (7 to 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (8 to 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (9 to 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (10 to 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Note (1 of 2)
The initial-action in a for loop can be a list of zero or more
comma-separated expressions. The action-after-each-
iteration in a for loop can be a list of zero or more comma-
separated statements. Therefore, the following two for loops
are correct. They are rarely used in practice, however.
for (int i = 1; i < 100; System.out.println(i++));
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
// Do something
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Note (2 of 2)
If the loop-continuation-condition in a for loop is omitted, it
is implicitly true. Thus the statement given below in (a),
which is an infinite loop, is correct. Nevertheless, it is better
to use the equivalent loop in (b) to avoid confusion:
for ( ; ; ) {
// Do something
}
(a)
Equivalent while (true) {
// Do something
}
(b)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Caution (2 of 3)
Adding a semicolon at the end of the for clause before the
loop body is a common mistake, as shown below:
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Caution (3 of 3)
Similarly, the following loop is also wrong:
In the case of the do loop, the following semicolon is needed to
end the loop.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Which Loop to Use?
The three forms of loop statements, while, do-while, and for, are
expressively equivalent; that is, you can write a loop in any of these
three forms. For example, a while loop in (a) in the following figure can
always be converted into the following for loop in (b):
while (loop-continuation-condition) {
// Loop body
}
(a)
Equivalent
(b)
for ( ; loop-continuation-condition; ) {
// Loop body
}
A for loop in (a) in the following figure can generally be converted into
the following while loop in (b) except in certain special cases (see
Review Question 3.19 for one of them):
for (initial-action;
loop-continuation-condition;
action-after-each-iteration) {
// Loop body;
}
(a)
Equivalent
(b)
initial-action;
while (loop-continuation-condition) {
// Loop body;
action-after-each-iteration;
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Recommendations
Use the one that is most intuitive and comfortable for you.
In general, a for loop may be used if the number of
repetitions is known, as, for example, when you need to
print a message 100 times. A while loop may be used if the
number of repetitions is not known, as in the case of
reading the numbers until the input is 0. A do-while loop
can be used to replace a while loop if the loop body has to
be executed before testing the continuation condition.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Nested Loops
Problem: Write a program that uses nested for loops to
print a multiplication table.
MultiplicationTable
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Minimizing Numerical Errors
Numeric errors involving floating-point numbers are
inevitable. This section discusses how to minimize such
errors through an example.
Here is an example that sums a series that starts with 0.01
and ends with 1.0. The numbers in the series will increment
by 0.01, as follows: 0.01 + 0.02 + 0.03 and so on.
TestSum
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Finding the Greatest Common
Divisor
Problem: Write a program that prompts the user to enter two
positive integers and finds their greatest common divisor.
Solution: Suppose you enter two integers 4 and 2, their
greatest common divisor is 2. Suppose you enter two integers
16 and 24, their greatest common divisor is 8. So, how do you
find the greatest common divisor? Let the two input integers
be n1 and n2. You know number 1 is a common divisor, but it
may not be the greatest commons divisor. So you can check
whether k (for k = 2, 3, 4, and so on) is a common divisor for
n1 and n2, until k is greater than n1 or n2.
GreatestCommonDivisor
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Predicting the Future Tuition
Problem: Suppose that the tuition for a university is
$10,000 this year and tuition increases 7% every year.
In how many years will the tuition be doubled?
FutureTuition
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Predicating the Future Tuition
double tuition = 10000; int year = 0 // Year 0
tuition = tuition * 1.07; year++; // Year 1
tuition = tuition * 1.07; year++; // Year 2
tuition = tuition * 1.07; year++; // Year 3
...
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Converting Decimals to
Hexadecimals
Hexadecimals are often used in computer systems
programming (see Appendix F for an introduction to number
systems). How do you convert a decimal number to a
hexadecimal number? To convert a decimal number d to a
hexadecimal number is to find the hexadecimal digits
1 2 2 1 0
, , , , , , and
n n n
h h h h h h
  such that
1 2 2 1 0
1 2 2 1 0
16 16 16 16 16 16
n n n
n n n
d h h h h h h
 
 
            
These hexadecimal digits can be found by successively
dividing d by 16 until the quotient is 0. The remainders are
0 1 2 2 1
, , , , , , and .
n n n
h h h h h h
 
Dec2Hex
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Monte Carlo Simulation
The Monte Carlo simulation refers to a technique that uses random
numbers and probability to solve problems. This method has a wide
range of applications in computational mathematics, physics,
chemistry, and finance. This section gives an example of using the
Monto Carlo simulation for estimating .

x
y
1
-1
1
-1
circleArea / squareArea / 4.


 can be approximated as
4 * numberOfHits / numberOfTrials
MonteCarloSimulation
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Using break and continue
Examples for using the break and continue keywords:
• TestBreak.java
TestBreak
• TestContinue.java
TestContinue
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
break
public class TestBreak {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
sum += number;
if (sum >= 100)
break;
}
System.out.println("The number is " + number);
System.out.println("The sum is " + sum);
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
continue
public class TestContinue {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
if (number == 10 || number == 11)
continue;
sum += number;
}
System.out.println("The sum is " + sum);
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Guessing Number Problem Revisited
Here is a program for guessing a number. You can rewrite
it using a break statement.
GuessNumberUsingBreak
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Checking Palindrome
A string is a palindrome if it reads the same forward and backward. The
words “mom,” “dad,” and “noon,” for instance, are all palindromes.
The problem is to write a program that prompts the user to enter a string
and reports whether the string is a palindrome. One solution is to check
whether the first character in the string is the same as the last character.
If so, check whether the second character is the same as the second-to-
last character. This process continues until a mismatch is found or all the
characters in the string are checked, except for the middle character if
the string has an odd number of characters.
String s
low high
a b c d e f g n h g f e d c b a
Palindrome
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Displaying Prime Numbers
Problem: Write a program that displays the first 50 prime
numbers in five lines, each of which contains 10 numbers. An
integer greater than 1 is prime if its only positive divisor is 1 or
itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8,
and 9 are not.
Solution: The problem can be broken into the following tasks:
• For number = 2, 3, 4, 5, 6, ..., test whether the number is
prime.
• Determine whether a given number is prime.
• Count the prime numbers.
• Print each prime number, and print 10 numbers per line.
PrimeNumber
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Debugging Loops in IDE Tools
Supplements II.C, II.E, and II.G.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 6
Methods
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Opening Problem
Find the sum of integers from 1 to 10, from 20 to 30, and
from 35 to 45, respectively.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem (1 of 2)
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);
sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
System.out.println("Sum from 20 to 30 is " + sum);
sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
System.out.println("Sum from 35 to 45 is " + sum);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem (2 of 2)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Solution
MethodDemo
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives
6.1 To define methods with formal parameters (§6.2).
6.2 To invoke methods with actual parameters (i.e., arguments) (§6.2).
6.3 To define methods with a return value (§6.3).
6.4 To define methods without a return value (§6.4).
6.5 To pass arguments by value (§6.5).
6.6 To develop reusable code that is modular, easy to read, easy to debug, and
easy to maintain (§6.6).
6.7 To write a method that converts hexadecimals to decimals (§6.7).
6.8 To use method overloading and understand ambiguous overloading (§6.8).
6.9 To determine the scope of variables (§6.9).
6.10 To apply the concept of method abstraction in software development
(§6.10).
6.11 To design and implement methods using stepwise refinement (§6.11).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Defining Methods (1 of 2)
A method is a collection of statements that are grouped
together to perform an operation.
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Define a method Invoke a method
int z = max(x, y);
actual parameters
(arguments)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Defining Methods (2 of 2)
A method is a collection of statements that are grouped
together to perform an operation.
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
modifier
return value
type
method
name
formal
parameters
return value
method
body
method
header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters
(arguments)
method
signature
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Method Signature
Method signature is the combination of the method name
and the parameter list.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Formal Parameters
The variables defined in the method header are known as
formal parameters.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Actual Parameters
When a method is invoked, you pass a value to the parameter.
This value is referred to as actual parameter or argument.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Return Value Type
A method may return a value. The returnValueType is the data type of
the value the method returns. If the method does not return a value, the
returnValueType is the keyword void. For example, the
returnValueType in the main method is void.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Calling Methods (1 of 2)
Testing the max method
This program demonstrates calling a method max to return
the largest of the int values
TestMax
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Calling Methods (2 of 2)
pass the value of i
pass the value of j
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (1 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (2 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (3 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (4 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (5 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (6 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (7 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (8 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (9 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (10 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
CAUTION
A return statement is required for a value-returning method.
The method shown below in (a) is logically correct, but it
has a compilation error because the Java compiler thinks it
possible that this method does not return any value.
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else if (n < 0)
return –1;
}
(a)
Should be
(b)
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else
return –1;
}
To fix this problem, delete if (n < 0) in (a), so that the
compiler will see a return statement to be reached
regardless of how the if statement is evaluated.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Reuse Methods from Other Classes
Note: One of the benefits of methods is for reuse. The max
method can be invoked from any class besides TestMax. If
you create a new class Test, you can invoke the max
method using ClassName.methodName (e.g.,
TestMax.max).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Call Stacks
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (1 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (2 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (3 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (4 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (5 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (6 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (7 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (8 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (9 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (10 of 10)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
void Method Example
This type of method does not return a value. The method
performs some actions.
TestVoidMethod
TestReturnGradeMethod
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Passing Parameters
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
Suppose you invoke the method using
nPrintln(“Welcome to Java”, 5);
What is the output?
Suppose you invoke the method using
nPrintln(“Computer Science”, 15);
What is the output?
Can you invoke the method using
nPrintln(15, “Computer Science”);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Pass by Value (1 of 3)
This program demonstrates passing values to the methods.
Increment
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Pass by Value (2 of 3)
Testing Pass by value
This program demonstrates passing values to the methods.
TestPassByValue
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Pass by Value (3 of 3)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Modularizing Code
Methods can be used to reduce redundant coding and
enable code reuse. Methods can also be used to
modularize code and improve the quality of the program.
GreatestCommonDivisorMethod
PrimeNumberMethod
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Converting Hexadecimals to
Decimals
Write a method that converts a hexadecimal number into a
decimal number.
 
 
 
 
ABCD
A *16 ^3 B *16 ^ 2 C *16 ^1 D *16 ^0
A *16 B *16 C *16 D
10 *16 11 *16 12 *16 13 ?

  
   
    
Hex2Dec
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Overloading Methods
Overloading the max Method
public static double max(double num1, double
num2) {
if (num1 > num2)
return num1;
else
return num2;
}
TestMethodOverloading
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Ambiguous Invocation (1 of 2)
Sometimes there may be two or more possible matches for
an invocation of a method, but the compiler cannot
determine the most specific match. This is referred to as
ambiguous invocation. Ambiguous invocation is a
compile error.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Ambiguous Invocation (2 of 2)
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1, 2));
}
public static double max(int num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Scope of Local Variables (1 of 6)
A local variable: a variable defined inside a method.
Scope: the part of the program where the variable can be
referenced.
The scope of a local variable starts from its declaration and
continues to the end of the block that contains the variable.
A local variable must be declared before it can be used.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Scope of Local Variables (2 of 6)
You can declare a local variable with the same name
multiple times in different non-nesting blocks in a method,
but you cannot declare a local variable twice in nested
blocks.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Scope of Local Variables (3 of 6)
A variable declared in the initial action part of a for loop
header has its scope in the entire loop. But a variable
declared inside a for loop body has its scope limited in the
loop body from its declaration and to the end of the block
that contains the variable.
public static void method1() {
.
.
for (int i = 1; i < 10; i++) {
.
.
int j;
.
.
.
}
}
The scope of j
The scope of i
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Scope of Local Variables (4 of 6)
public static void method1() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
x += i;
}
for (int i = 1; i < 10; i++) {
y += i;
}
}
It is fine to declare i in two
non-nesting blocks
public static void method2() {
int i = 1;
int sum = 0;
for (int i = 1; i < 10; i++) {
sum += i;
}
}
It is wrong to declare i in
two nesting blocks
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Scope of Local Variables (5 of 6)
// Fine with no errors
public static void correctMethod() {
int x = 1;
int y = 1;
// i is declared
for (int i = 1; i < 10; i++) {
x += i;
}
// i is declared again
for (int i = 1; i < 10; i++) {
y += i;
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Scope of Local Variables (6 of 6)
// With errors
public static void incorrectMethod() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
int x = 0;
x += i;
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Method Abstraction
You can think of the method body as a black box that
contains the detailed implementation for the method.
Method Header
Method body
Black Box
Optional arguments
for Input
Optional return
value
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Benefits of Methods
• Write a method once and reuse it anywhere.
• Information hiding. Hide the implementation from the
user.
• Reduce complexity.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Generating Random
Characters (1 of 4)
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.
As introduced in Section 4.3, each character has a unique
Unicode between 0 and FFFF in hexadecimal (65535 in
decimal). To generate a random character is to generate a
random integer between 0 and 65535 using the following
expression: (note that since 0 <= Math.random() < 1.0, you
have to add 1 to 65535.)
(int)(Math.random() * (65535 + 1))
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Generating Random
Characters (2 of 4)
Now let us consider how to generate a random lowercase
letter. The Unicode for lowercase letters are consecutive
integers starting from the Unicode for 'a', then for 'b', 'c', ...,
and 'z'. The Unicode for 'a' is
(int)'a'
So, a random integer between (int)'a' and (int)'z' is
(int)((int)'a' + Math.random() * ((int)'z' - (int)'a' + 1)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Generating Random
Characters (3 of 4)
As discussed in Chapter 2, all numeric operators can be
applied to the char operands. The char operand is cast into
a number if the other operand is a number or a character.
So, the preceding expression can be simplified as follows:
'a' + Math.random() * ('z' - 'a' + 1)
So a random lowercase letter is
(char)('a' + Math.random() * ('z' - 'a' + 1))
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Generating Random
Characters (4 of 4)
To generalize the foregoing discussion, a random
character between any two characters ch1 and ch2 with
ch1 < ch2 can be generated as follows:
(char)(ch1 + Math.random() * (ch2 – ch1 + 1))
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The RandomCharacter Class (1 of 2)
// RandomCharacter.java: Generate random
characters
public class RandomCharacter {
/** Generate a random character between ch1
and ch2 */
public static char getRandomCharacter(char
ch1, char ch2) {
return (char)(ch1 + Math.random() *
(ch2 - ch1 + 1));
}
/** Generate a random lowercase letter */
public static char
getRandomLowerCaseLetter() {
return getRandomCharacter('a', 'z');
}
/** Generate a random uppercase letter */
public static char
getRandomUpperCaseLetter() {
return getRandomCharacter('A', 'Z');
}
RandomCharacter
TestRandomCharacter
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The RandomCharacter Class (2 of 2)
/** Generate a random digit character */
public static char
getRandomDigitCharacter() {
return getRandomCharacter('0', '9');
}
/** Generate a random character */
public static char getRandomCharacter() {
return getRandomCharacter('u0000',
'uFFFF');
}
}
RandomCharacter
TestRandomCharacter
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Stepwise Refinement (Optional)
The concept of method abstraction can be applied to the
process of developing programs. When writing a large
program, you can use the “divide and conquer” strategy,
also known as stepwise refinement, to decompose it into
subproblems. The subproblems can be further
decomposed into smaller, more manageable problems.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
PrintCalender Case Study
Let us use the PrintCalendar example to demonstrate the
stepwise refinement approach.
PrintCalendar
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Design Diagram (1 of 7)
printCalendar
(main)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Design Diagram (2 of 7)
printCalendar
(main)
readInput printMonth
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Design Diagram (3 of 7)
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Design Diagram (4 of 7)
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Design Diagram (5 of 7)
printCalendar
(main)
readInput printMonth
getStartDay
printMonthTitle printMonthBody
getNumOfDaysInMonth
getMonthName
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Design Diagram (6 of 7)
printCalendar
(main)
readInput printMonth
getStartDay
printMonthTitle printMonthBody
getTotalNumOfDays
getNumOfDaysInMonth
getMonthName
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Design Diagram (7 of 7)
printCalendar
(main)
readInput printMonth
getStartDay
printMonthTitle printMonthBody
getTotalNumOfDays
getNumOfDaysInMonth
getMonthName
isLeapYear
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Implementation: Top-Down
Top-down approach is to implement one method in the
structure chart at a time from the top to the bottom. Stubs
can be used for the methods waiting to be implemented. A
stub is a simple but incomplete version of a method. The
use of stubs enables you to test invoking the method from a
caller. Implement the main method first and then use a stub
for the printMonth method. For example, let printMonth
display the year and the month in the stub. Thus, your
program may begin like this:
A Skeleton for printCalendar
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Implementation: Bottom-Up
Bottom-up approach is to implement one method in the
structure chart at a time from the bottom to the top. For
each method implemented, write a test program to test it.
Both top-down and bottom-up methods are fine. Both
approaches implement the methods incrementally and help
to isolate programming errors and makes debugging easy.
Sometimes, they can be used together.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Benefits of Stepwise Refinement
Simpler Program
Reusing Methods
Easier Developing, Debugging, and Testing
Better Facilitating Teamwork
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 7
Single-Dimensional Arrays
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Opening Problem
Read one hundred numbers, compute their average, and
find out how many numbers are above the average.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (1 of 2)
7.1 To describe why arrays are necessary in programming (§7.1).
7.2 To declare array reference variables and create arrays (§§7.2.1–
7.2.2).
7.3 To obtain array size using arrayRefVar.length and know default
values in an array (§7.2.3).
7.4 To access array elements using indexes (§7.2.4).
7.5 To declare, create, and initialize an array using an array initializer
(§7.2.5).
7.6 To program common array operations (displaying arrays, summing
all elements, finding the minimum and maximum elements, random
shuffling, and shifting elements) (§7.2.6).
7.7 To simplify programming using the foreach loops (§7.2.7).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (2 of 2)
7.8 To apply arrays in application development (AnalyzeNumbers,
DeckOfCards) (§§7.3–7.4).
7.9 To copy contents from one array to another (§7.5).
7.10 To develop and invoke methods with array arguments and return
values (§§7.6–7.8).
7.11 To define a method with a variable-length argument list (§7.9).
7.12 To search elements using the linear (§7.10.1) or binary (§7.10.2)
search algorithm.
7.13 To sort an array using the selection sort approach (§7.11).
7.14 To use the methods in the java.util.Arrays class (§7.12).
7.15 To pass arguments to the main method from the command line
(§7.13).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Declaring Array Variables
• datatype[] arrayRefVar;
Example:
double[] myList;
• datatype arrayRefVar[]; // This style is allowed,
but not preferred
Example:
double myList[];
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Creating Arrays
arrayRefVar = new datatype[arraySize];
Example:
myList = new double[10];
myList[0] references the first element in the array.
myList[9] references the last element in the array.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Declaring and Creating in One Step
• datatype[] arrayRefVar = new
datatype[arraySize];
double[] myList = new double[10];
• datatype arrayRefVar[] = new
datatype[arraySize];
double myList[] = new double[10];
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Length of an Array
Once an array is created, its size is fixed. It cannot be
changed. You can find its size using
arrayRefVar.length
For example,
myList.length returns 10
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Default Values
When an array is created, its elements are assigned the
default value of
0 for the numeric primitive data types,
'u0000' for char types, and
false for boolean types.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Indexed Variables
The array elements are accessed through the index. The
array indices are 0-based, i.e., it starts from 0 to
arrayRefVar.length-1. In the example in Figure 6.1, myList
holds ten double values and the indices are from 0 to 9.
Each element in the array is represented using the
following syntax, known as an indexed variable:
arrayRefVar[index];
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Using Indexed Variables
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 value in myList[0] and myList[1] to
myList[2].
myList[2] = myList[0] + myList[1];
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Array Initializers
• Declaring, creating, initializing in one step:
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand syntax must be in one statement.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Declaring, Creating, Initializing Using the
Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the following
statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
CAUTION
Using the shorthand notation, you have to declare, create,
and initialize the array all in one statement. Splitting it
would cause a syntax error. For example, the following is
wrong:
double[] myList;
myList = {1.9, 2.9, 3.4, 3.5};
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Program with Arrays (1 of 16)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Program with Arrays (2 of 16)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Program with Arrays (3 of 16)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Program with Arrays (4 of 16)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Program with Arrays (5 of 16)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Program with Arrays (6 of 16)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Program with Arrays (7 of 16)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Program with Arrays (8 of 16)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Program with Arrays (9 of 16)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Program with Arrays (10 of 16)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Program with Arrays (11 of 16)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Program with Arrays (12 of 16)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Program with Arrays (13 of 16)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Program with Arrays (14 of 16)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Program with Arrays (15 of 16)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Program with Arrays (16 of 16)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Processing Arrays
See the examples in the text.
1. (Initializing arrays with input values)
2. (Initializing arrays with random values)
3. (Printing arrays)
4. (Summing all elements)
5. (Finding the largest element)
6. (Finding the smallest index of the largest element)
7. (Random shuffling)
8. (Shifting elements)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Initializing Arrays With Input Values
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + myList.length + " values: ");
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble();
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Initializing Arrays With Random Values
for (int i = 0; i < myList.length; i++) {
myList[i] = Math.random() * 100;
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Printing Arrays
for (int i = 0; i < myList.length; i++) {
System.out.print(myList[i] + " ");
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Summing All Elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Finding the Largest Element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Random Shuffling
for (int i = 0; i < myList.length - 1; i++) {
// Generate an index j randomly
int j = (int)(Math.random()
* myList.length);
// Swap myList[i] with myList[j]
double temp = myList[i];
myList[i] = myList[j];
myList[j] = temp;
}
myList
[0]
[1]
.
.
.
A random index
i
swap
.
.
.
[i]
[j]
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Shifting Elements
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Enhanced for Loop (for-each loop)
JDK 1.5 introduced a new for loop that enables you to traverse the
complete array sequentially without using an index variable. For
example, the following code displays all elements in the array myList:
for (double value: myList)
System.out.println(value);
In general, the syntax is
for (elementType value: arrayRefVar) {
// Process the value
}
You still have to use an index variable if you wish to traverse the array
in a different order or change the elements in the array.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Analyze Numbers
Read one hundred numbers, compute their average, and
find out how many numbers are above the average.
AnalyzeNumbers
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Deck of Cards (1 of 4)
The problem is to write a program that picks four cards
randomly from a deck of 52 cards. All the cards can be
represented using an array named deck, filled with initial
values 0 to 51, as follows:
int[] deck = new int[52];
// Initialize cards
for (int i = 0; i < deck.length; i++)
deck[i] = i;
DeckOfCards
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Deck of Cards (2 of 4)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Deck of Cards (3 of 4)
DeckOfCards
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Deck of Cards (4 of 4)
This problem builds a foundation for future more interesting and
realistic applications:
See Exercise 20.15.
https://liveexample.pearsonc
mg.com/dsanimation/24Point
.html
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copying Arrays (1 of 2)
Often, in a program, you need to duplicate an array or a part
of an array. In such cases you could attempt to use the
assignment statement (=), as follows:
list2 = list1;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copying Arrays (2 of 2)
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new
int[sourceArray.length];
for (int i = 0; i < sourceArrays.length;
i++)
targetArray[i] = sourceArray[i];
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The arraycopy Utility
arraycopy(sourceArray, src_pos, targetArray,
tar_pos, length);
Example:
System.arraycopy(sourceArray, 0,
targetArray, 0, sourceArray.length);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Passing Arrays to Methods
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Anonymous Array
The statement
printArray(new int[]{3, 1, 2, 6, 4, 2});
creates an array using the following syntax:
new dataType[]{literal0, literal1, ..., literalk};
There is no explicit reference variable for the array. Such
array is called an anonymous array.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Pass By Value
Java uses pass by value to pass arguments to a method. There
are important differences between passing a value of variables of
primitive data types and passing arrays.
• For a parameter of a primitive type value, the actual value is
passed. Changing the value of the local parameter inside the
method does not affect the value of the variable outside the
method.
• For a parameter of an array type, the value of the parameter
contains a reference to an array; this reference is passed to the
method. Any changes to the array that occur inside the method
body will affect the original array that was passed as the
argument.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Simple Example
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Call Stack (1 of 2)
When invoking m(x, y), the values of x and y are passed to
number and numbers. Since y contains the reference value
to the array, numbers now contains the same reference
value to the same array.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Call Stack (2 of 2)
When invoking m(x, y), the values of x and y are passed to
number and numbers. Since y contains the reference value
to the array, numbers now contains the same reference
value to the same array.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Heap
Space required for the
main method
int[] y:
int x: 1
reference
The arrays are
stored in a
heap.
Heap
5555
0
0
The JVM stores the array in an area of memory, called
heap, which is used for dynamic memory allocation where
blocks of memory are allocated and freed in an arbitrary
order.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Passing Arrays as Arguments
• Objective: Demonstrate differences of passing primitive
data type variables and array variables.
TestPassArray
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example
Invoke swap(int n1, int n2).
The primitive type values in
a[0] and a[1] are passed to the
swap method.
Space required for the
main method
int[] a
Stack
Space required for the
swap method
n2: 2
n1: 1
reference
a[1]: 2
a[0]: 1
The arrays are
stored in a
heap.
Invoke swapFirstTwoInArray(int[] array).
The reference value in a is passed to the
swapFirstTwoInArray method.
Heap
Space required for the
main method
int[] a
Stack
Space required for the
swapFirstTwoInArray
method
int[] array
reference
reference
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Returning an Array from a Method
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (1 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (2 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (3 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (4 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (5 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (6 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (7 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (8 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (9 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (10 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (11 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (12 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (13 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (14 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (15 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (16 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (17 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (18 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (19 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (20 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (21 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace the Reverse Method (22 of 22)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Counting Occurrence of Each
Letter
• Generate 100 lowercase letters randomly and assign to
an array of characters.
• Count the occurrence of each letter in the array.
CountLettersInArray
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Variable-Length Arguments
You can pass a variable number of arguments of the same
type to a method.
VarArgsDemo
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Searching Arrays
Searching is the process of looking for a specific element in an
array; for example, discovering whether a certain score is
included in a list of scores. Searching is a common task in
computer programming. There are many algorithms and data
structures devoted to searching. In this section, two commonly
used approaches are discussed, linear search and binary
search.
public class LinearSearch {
/** The method for finding a key in the list */
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < list.length; i++)
if (key == list[i])
return i;
return -1;
}
}
list
key Compare key with list[i] for i = 0, 1, …
[0] [1] [2] …
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Linear Search
The linear search approach compares the key element,
key, sequentially with each element in the array list. The
method continues to do so until the key matches an
element in the list or the list is exhausted without a match
being found. If a match is made, the linear search returns
the index of the element in the array that matches the key.
If no match is found, the search returns 1.

Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Linear Search Animation (1 of 2)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Linear Search Animation (2 of 2)
https://liveexample.pearsoncmg.com/dsanimation/LinearSe
archeBook.html
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
From Idea to Solution (1 of 6)
Trace the method
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Binary Search (1 of 6)
For binary search to work, the elements in the array must
already be ordered. Without loss of generality, assume that
the array is in ascending order.
e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79
The binary search first compares the key with the element
in the middle of the array.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Binary Search (2 of 6)
Consider the following three cases:
• If the key is less than the middle element, you only need
to search the key 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 only
need to search the key in the second half of the array.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Binary Search (3 of 6)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Binary Search Animation
https://liveexample.pearsoncmg.com/dsanimation/BinarySe
archeBook.html
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Binary Search (4 of 6)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Binary Search (5 of 6)
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
2 4 7 10 11 45 50 59 60 66 69 70 79
key is 54
key > 50
list
mid
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
key < 66
key < 59
high
low
mid high
low
list
[7] [8]
mid high
low
list
59 60 66 69 70 79
59 60
[6] [7] [8]
high
low
59 60
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Binary Search (6 of 6)
The binarySearch method returns the index of the element
in the list that matches the search key if it is contained in
the list. Otherwise, it returns
-insertion point - 1.
The insertion point is the point at which the key would be
inserted into the list.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
From Idea to Solution (2 of 6)
/** Use binary search to find the key in the list */
public static int binarySearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;
while (high >= low) {
int mid = (low + high) / 2;
if (key < list[mid])
high = mid - 1;
else if (key == list[mid])
return mid;
else
low = mid + 1;
}
return -1 - low;
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Arrays.binarySearch Method
Since binary search is frequently used in programming, Java provides
several overloaded binarySearch methods for searching a key in an
array of int, double, char, short, long, and float in the java.util.Arrays
class. For example, the following code searches the keys in an array of
numbers and an array of characters.
For the binarySearch method to work, the array must be pre-sorted in
increasing order.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Sorting Arrays
Sorting, like searching, is also a common task in computer
programming. Many different algorithms have been
developed for sorting. This section introduces a simple,
intuitive sorting algorithms: selection sort.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Selection Sort
Selection sort finds
the smallest number
in the list and places it
first. It then finds the
smallest number
remaining and places
it second, and so on
until the list contains
only a single number.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Selection Sort Animation
https://liveexample.pearsoncmg.com/dsanimation/Selection
SortNew.html
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
From Idea to Solution (3 of 6)
for (int i = 0; i < list.length; i++) {
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i+1..listSize-1]
}
list [0] list [1] list [2] list [3] ... list [10]
list [0] list [1] list [2] list [3] ... list [10]
list [0] list [1] list [2] list [3] ... list [10]
list [0] list [1] list [2] list [3] ... list [10]
list [0] list [1] list [2] list [3] ... list [10]
...
list [0] list [1] list [2] list [3] ... list [10]
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
From Idea to Solution (4 of 6)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
From Idea to Solution (5 of 6)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
From Idea to Solution (6 of 6)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Wrap it in a Method
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Arrays.sort Method
Since sorting is frequently used in programming, Java provides
several overloaded sort methods for sorting an array of int,
double, char, short, long, and float in the java.util.Arrays class.
For example, the following code sorts an array of numbers and
an array of characters.
double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5};
java.util.Arrays.sort(numbers);
char[] chars = {'a', 'A', '4', 'F', 'D', 'P'};
java.util.Arrays.sort(chars);
Java 8 now provides Arrays.parallelSort(list) that utilizes the
multicore for fast sorting.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Arrays.toString(list) Method
The Arrays.toString(list) method can be used to return a
string representation for the list.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Main Method Is Just a Regular Method
You can call a regular method by passing actual
parameters. Can you pass arguments to main? Of course,
yes. For example, the main method in class B is invoked by
a method in A, as shown below:
public class A {
public static void main(String[] args) {
String[] strings = {"New York",
"Boston", "Atlanta"};
B.main(strings);
}
}
class B {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++)
System.out.println(args[i]);
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Command-Line Parameters
class TestMain {
public static void main(String[] args) {
...
}
}
java TestMain arg0 arg1 arg2 ... argn
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Processing Command-Line Parameters
In the main method, get the arguments from args[0],
args[1], ..., args[n], which corresponds to arg0,
arg1, ..., argn in the command line.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Calculator
• Objective: Write a program that will perform binary
operations on integers. The program receives three
parameters: an operator and two integers.
java Calculator 2 + 3
java Calculator 2 3

java Calculator 2 / 3
java Calculator 2.3
Calculator
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 8
Multidimensional Arrays
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations (1 of 2)
Thus far, you have used one-dimensional arrays to model linear collections of
elements. You can use a two-dimensional array to represent a matrix or a
table. For example, the following table that describes the distances between
the cities can be represented using a two-dimensional array.
Distance Table (in miles)
Blank
Chicago Boston New York Atlanta Miami Dallas Houston
Chicago 0 983 787 714 1375 967 1087
Boston 983 0 214 1102 1763 1723 1842
New York 787 214 0 888 1549 1548 1627
Atlanta 714 1102 888 0 661 781 810
Miami 1375 1763 1549 661 0 1426 1187
Dallas 967 1723 1548 781 1426 0 239
Houston 1087 1842 1627 810 1187 239 0
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations (2 of 2)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (1 of 2)
8.1 To give examples of representing data using two-
dimensional arrays (§8.1).
8.2 To declare variables for two-dimensional arrays, create
arrays, and access array elements in a two-dimensional
array using row and column indexes (§8.2).
8.3 To program common operations for two-dimensional
arrays (displaying arrays, summing all elements, finding the
minimum and maximum elements, and random shuffling)
(§8.3).
8.4 To pass two-dimensional arrays to methods (§8.4).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (2 of 2)
8.5 To write a program for grading multiple-choice
questions using two-dimensional arrays (§8.5).
8.6 To solve the closest-pair problem using two-
dimensional arrays (§8.6).
8.7 To check a Sudoku solution using two-dimensional
arrays (§8.7).
8.8 To use multidimensional arrays (§8.8).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Declare/Create Two-dimensional Arrays
// Declare array ref var
dataType[][] refVar;
// Create array and assign its reference to
variable
refVar = new dataType[10][10];
// Combine declaration and creation in one
statement
dataType[][] refVar = new dataType[10][10];
// Alternative syntax
dataType refVar[][] = new dataType[10][10];
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Declaring Variables of Two-dimensional Arrays
and Creating Two-dimensional Arrays
int[][] matrix = new int[10][10];
or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = (int)(Math.random() *
1000);
double[][] x;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Two-dimensional Array Illustration
matrix.length? 5
matrix[0].length? 5
array.length? 4
array[0].length? 3
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Declaring, Creating, and Initializing Using
Shorthand Notations
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Lengths of Two-dimensional Arrays (1 of 2)
int[][] x = new int[3][4];
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Lengths of Two-dimensional Arrays (2 of 2)
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
array.length
array[0].length
array[1].length
array[2].length
array[3].length
array[4].length ArrayIndexOutOfBoundsException
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Ragged Arrays (1 of 2)
Each row in a two-dimensional array is
itself an array. So, the rows can have
different lengths. Such an array is
known as a ragged array. For example,
int[][] matrix = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5},
{3, 4, 5},
{4, 5},
{5}
};
matrix.length is 5
matrix[0].length is 5
matrix[1].length is 4
matrix[2].length is 3
matrix[3].length is 2
matrix[4].length is 1
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Ragged Arrays (2 of 2)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Processing Two-Dimensional Arrays
See the examples in the text.
1. (Initializing arrays with input values)
2. (Printing arrays)
3. (Summing all elements)
4. (Summing all elements by column)
5. (Which row has the largest sum)
6. (Finding the smallest index of the largest element)
7. (Random shuffling)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Initializing Arrays With Input Values
java.util.Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix.length + " rows and " +
matrix[0].length + " columns: ");
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length;
column++) {
matrix[row][column] = input.nextInt();
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Initializing Arrays With Random Values
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length;
column++) {
matrix[row][column] = (int)(Math.random() * 100);
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Printing Arrays
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length;
column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Summing All Elements
int total = 0;
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length;
column++) {
total += matrix[row][column];
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Summing Elements by Column
for (int column = 0; column < matrix[0].length; column++) {
int total = 0;
for (int row = 0; row < matrix.length; row++)
total += matrix[row][column];
System.out.println("Sum for column " + column + " is "
+ total);
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Random Shuffling
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
int i1 = (int)(Math.random() * matrix.length);
int j1 = (int)(Math.random() * matrix[i].length);
// Swap matrix[i][j] with matrix[i1][j1]
int temp = matrix[i][j];
matrix[i][j] = matrix[i1][j1];
matrix[i1][j1] = temp;
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Passing Tow-Dimensional Arrays to
Methods
PassTwoDimensionalArray
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Grading Multiple-Choice Test
Students’ answer Objective: write a program
that grades multiple-choice
test.
PassTwoDimensionalArray
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Finding Two Points Nearest to
Each Other
https://liveexample.pearsoncmg.com/dsanimation/ClosestP
aireBook.html
PassTwoDimensionalArray
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
What is Sudoku?
5 3 7
6 1 9 5
9 8 6
8 6 3
4 8 3 1
7 2 6
6
4 1 9 5
8 7 9
https://liveexample.pearsoncmg.
com/dsanimation/Sudoku.html
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Every Row Contains the Numbers 1 to 9
5 3 7
6 1 9 5
9 8 6
8 6 3
4 8 3 1
7 2 6
6
4 1 9 5
8 7 9
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Every Column Contains the Numbers 1 to 9
5 3 7
6 1 9 5
9 8 6
8 6 3
4 8 3 1
7 2 6
6
4 1 9 5
8 7 9
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Every 3 by 3 Box Contains the Numbers 1 to 9
5 3 7
6 1 9 5
9 8 6
8 6 3
4 8 3 1
7 2 6
6
4 1 9 5
8 7 9
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Checking Whether a Solution Is Correct
5 3 7
6 1 9 5
9 8 6
8 6 3
4 8 3 1
7 2 6
6
4 1 9 5
8 7 9
5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9
CheckSudokuSolution
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Multidimensional Arrays (1 of 2)
Occasionally, you will need to represent n-dimensional
data structures. In Java, you can create n-dimensional
arrays for any integer n.
The way to declare two-dimensional array variables and
create two-dimensional arrays can be generalized to
declare n-dimensional array variables and create n-
dimensional arrays for n >= 3.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Multidimensional Arrays (2 of 2)
double[][][] scores = {
{{7.5, 20.5}, {9.0, 22.5}, {15, 33.5}, {13, 21.5}, {15, 2.5}},
{{4.5, 21.5}, {9.0, 22.5}, {15, 34.5}, {12, 20.5}, {14, 9.5}},
{{6.5, 30.5}, {9.4, 10.5}, {11, 33.5}, {11, 23.5}, {10, 2.5}},
{{6.5, 23.5}, {9.4, 32.5}, {13, 34.5}, {11, 20.5}, {16, 7.5}},
{{8.5, 26.5}, {9.4, 52.5}, {13, 36.5}, {13, 24.5}, {16, 2.5}},
{{9.5, 20.5}, {9.4, 42.5}, {13, 31.5}, {12, 20.5}, {16, 6.5}}
};
scores[ i ] [ j ] [ k ]
Which student Which exam Multiple-choice or essay
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Calculating Total Scores
Objective: write a program that calculates the total score for
students in a class. Suppose the scores are stored in a
three-dimensional array named scores. The first index in
scores refers to a student, the second refers to an exam,
and the third refers to the part of the exam. Suppose there
are 7 students, 5 exams, and each exam has two parts--the
multiple-choice part and the programming part. So,
scores[i][j][0] represents the score on the multiple-choice
part for the i’s student on the j’s exam. Your program
displays the total score for each student.
TotalScore
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Weather Information
Suppose a meteorology station records the temperature
and humidity at each hour of every day and stores the data
for the past ten days in a text file named weather.txt. Each
line of the file consists of four numbers that indicate the
day, hour, temperature, and humidity. Your task is to write
a program that calculates the average daily temperature
and humidity for the 10 days.
1 1 76.4 0.92
1 2 77.7 0.93
...
10 23 97.7 0.71
10 24 98.7 0.74
(a)
10 24 98.7 0.74
1 2 77.7 0.93
...
10 23 97.7 0.71
1 1 76.4 0.92
(b)
Weather
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Guessing Birthday
Listing 4.3, GuessBirthday.java, gives a program that
guesses a birthday. The program can be simplified by
storing the numbers in five sets in a three-dimensional
array, and it prompts the user for the answers using a loop.
GuessBirthdayUsingArray
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 9
Objects and Classes
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations
After learning the preceding chapters, you are capable of
solving many programming problems using selections,
loops, methods, and arrays. However, these Java features
are not sufficient for developing graphical user interfaces
and large scale software systems. Suppose you want to
develop a graphical user interface as shown below. How do
you program it?
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (1 of 2)
9.1 To describe objects and classes, and use classes to model objects
(§9.2).
9.2 To use UML graphical notation to describe classes and objects (§9.2).
9.3 To demonstrate how to define classes and create objects (§9.3).
9.4 To create objects using constructors (§9.4).
9.5 To define a reference variable using a reference type and access
objects via object reference variables (§9.5).
9.6 To access an object’s data and methods using the object member
access operator (.) (§9.5.1).
9.7 To define data fields of reference types and assign default values for
an object’s data fields (§9.5.2).
9.8 To distinguish between object reference variables and primitive data
type variables (§9.5.3).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (2 of 2)
9.9 To use the Java library classes Date, Random, and Point2D (§9.6).
9.10 To distinguish between instance and static variables and methods (§9.7).
9.11 To define private data fields with appropriate get and set methods (§9.8).
9.12 To encapsulate data fields to make classes easy to maintain (§9.9).
9.13 To develop methods with object arguments and differentiate between
primitive-type arguments and object-type arguments (§9.10).
9.14 To store and process objects in arrays (§9.11).
9.15 To create immutable objects from immutable classes to protect the
contents of objects (§9.12).
9.16 To determine the scope of variables in the context of a class (§9.13).
9.17 To use the keyword this to refer to the calling object itself (§9.14).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
OO Programming Concepts
Object-oriented programming (OOP) involves programming
using objects. An object represents an entity in the real
world that can be distinctly identified. For example, a
student, a desk, a circle, a button, and even a loan can all
be viewed as objects. An object has a unique identity,
state, and behaviors. The state of an object consists of a
set of data fields (also known as properties) with their
current values. The behavior of an object is defined by a
set of methods.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objects
Class Name: Circle
Data Fields:
radius is _______
Methods:
getArea
Circle Object 1
Data Fields:
radius is 10
Circle Object 2
Data Fields:
radius is 25
Circle Object 3
Data Fields:
radius is 125
A class template
Three objects of
the Circle class
An object has both a state and behavior. The state defines
the object, and the behavior defines what the object does.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Classes (1 of 2)
Classes are constructs that define objects of the same
type. A Java class uses variables to define data fields and
methods to define behaviors. Additionally, a class provides
a special type of methods, known as constructors, which
are invoked to construct objects from the class.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Classes (2 of 2)
class Circle {
/** The radius of this circle */
double radius = 1.0;
/** Construct a circle object */
Circle() {
}
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}
/** Return the area of this circle */
double getArea() {
return radius * radius * 3.14159;
}
}
Data field
Method
Constructors
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
UML Class Diagram
Circle
radius: double
Circle()
Circle(newRadius: double)
getArea(): double
getPerimeter(): double
setRadius(newRadius:
double): void
circle1: Circle
radius = 1.0
Class name
Data fields
Constructors
and methods
circle2: Circle
radius = 25
circle3: Circle
radius = 125
UML Class Diagram
UML notation
for objects
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example: Defining Classes and Creating
Objects (1 of 2)
Objective: Demonstrate creating objects, accessing data,
and using methods.
TestSimpleCircle
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example: Defining Classes and Creating
Objects (2 of 2)
TV
TestTV
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Constructors (1 of 2)
Circle() {
}
Circle(double newRadius) {
radius = newRadius;
}
Constructors are a special kind of methods that are
invoked to construct objects.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Constructors (2 of 2)
A constructor with no parameters is referred to as a no-arg
constructor.
• Constructors must have the same name as the class
itself.
• Constructors do not have a return type—not even void.
• Constructors are invoked using the new operator when
an object is created. Constructors play the role of
initializing objects.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Creating Objects Using Constructors
new ClassName();
Example:
new Circle();
new Circle(5.0);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Default Constructor
A class may be defined without constructors. In this case,
a no-arg constructor with an empty body is implicitly
defined in the class. This constructor, called a default
constructor, is provided automatically only if no
constructors are explicitly defined in the class.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Declaring Object Reference Variables
To reference an object, assign the object to a reference
variable.
To declare a reference variable, use the syntax:
ClassName objectRefVar;
Example:
Circle myCircle;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Declaring/Creating Objects in a Single
Step
ClassName objectRefVar = new ClassName();
Example:
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Accessing Object’s Members
• Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius
• Invoking the object’s method:
objectRefVar.methodName(arguments)
e.g., myCircle.getArea()
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Code (1 of 7)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Code (2 of 7)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Code (3 of 7)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Code (4 of 7)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Code (5 of 7)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Code (6 of 7)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Code (7 of 7)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Caution
Recall that you use
Math.methodName(arguments) (e.g., Math.pow(3, 2.5))
to invoke a method in the Math class. Can you invoke getArea()
using SimpleCircle.getArea()? The answer is no. All the methods
used before this chapter are static methods, which are defined
using the static keyword. However, getArea() is non-static. It
must be invoked from an object using
objectRefVar.methodName(arguments) (e.g.,
myCircle.getArea()).
More explanations will be given in the section on “Static
Variables, Constants, and Methods.”
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Reference Data Fields
The data fields can be of reference types. For example, the
following Student class contains a data field name of the
String type.
public class Student {
String name; // name has default value null
int age; // age has default value 0
boolean isScienceMajor; // isScienceMajor
has default value false
char gender; // c has default value
'u0000’
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Null Value
If a data field of a reference type does not reference any
object, the data field holds a special literal value, null.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Default Value for a Data Field
The default value of a data field is null for a reference type, 0 for a
numeric type, false for a boolean type, and 'u0000' for a char type.
However, Java assigns no default value to a local variable inside a
method.
public class Test {
public static void main(String[] args) {
Student student = new Student();
System.out.println("name? " + student.name);
System.out.println("age? " + student.age);
System.out.println("isScienceMajor? " +
student.isScienceMajor);
System.out.println("gender? " + student.gender);
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example (1 of 3)
Java assigns no default value to a local variable inside a
method.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Differences between Variables of
Primitive Data Types and Object Types
1
Primitive type int i = 1 i
Object type Circle c c reference
Created using new Circle()
c: Circle
radius = 1
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copying Variables of Primitive Data
Types and Object Types
i
Primitive type assignment i = j
Before:
1
j 2
i
After:
2
j 2
c1
Object type assignment c1 = c2
Before:
c2
c1
After:
c2
c1: Circle
radius = 5
c2: Circle
radius = 9
c1: Circle
radius = 5
c2: Circle
radius = 9
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Garbage Collection (1 of 2)
As shown in the previous figure, after the assignment
statement c1 = c2, c1 points to the same object referenced
by c2. The object previously referenced by c1 is no longer
referenced. This object is known as garbage. Garbage is
automatically collected by JVM.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Garbage Collection (2 of 2)
TIP: If you know that an object is no longer needed, you
can explicitly assign null to a reference variable for the
object. The JVM will automatically collect the space if the
object is not referenced by any variable.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Date Class
Java provides a system-independent encapsulation of date
and time in the java.util.Date class. You can use the Date
class to create an instance for the current date and time
and use its toString method to return the date and time as a
string.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Date Class Example
For example, the following code
java.util.Date date = new java.util.Date();
System.out.println(date.toString());
displays a string like Sun Mar 09 13:50:19 EST 2003.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Random Class
You have used Math.random() to obtain a random double
value between 0.0 and 1.0 (excluding 1.0). A more useful
random number generator is provided in the
java.util.Random class.
java.util.Random
+Random()
+Random(seed: long)
+nextInt(): int
+nextInt(n: int): int
+nextLong(): long
+nextDouble(): double
+nextFloat(): float
+nextBoolean(): boolean
Constructs a Random object with the current time as its seed.
Constructs a Random object with a specified seed.
Returns a random int value.
Returns a random int value between 0 and n (exclusive).
Returns a random long value.
Returns a random double value between 0.0 and 1.0 (exclusive).
Returns a random float value between 0.0F and 1.0F (exclusive).
Returns a random boolean value.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Random Class Example
If two Random objects have the same seed, they will generate identical
sequences of numbers. For example, the following code creates two
Random objects with the same seed 3.
Random random1 = new Random(3);
System.out.print("From random1: ");
for (int i = 0; i < 10; i++)
System.out.print(random1.nextInt(1000) + " ");
Random random2 = new Random(3);
System.out.print("nFrom random2: ");
for (int i = 0; i < 10; i++)
System.out.print(random2.nextInt(1000) + " ");
From random1: 734 660 210 581 128 202 549 564 459 961
From random2: 734 660 210 581 128 202 549 564 459 961
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Point2D Class
Java API has a conveninent Point2D class in the
javafx.geometry package for representing a point in a
two-dimensional plane.
TestPoint2D
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Instance Variables, and Methods
Instance variables belong to a specific instance.
Instance methods are invoked by an instance of the class.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Static Variables, Constants, and
Methods (1 of 3)
Static variables are shared by all the instances of the class.
Static methods are not tied to a specific object.
Static constants are final variables shared by all the
instances of the class.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Static Variables, Constants, and
Methods (2 of 3)
To declare static variables, constants, and methods, use
the static modifier.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Static Variables, Constants, and
Methods (3 of 3)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example of Using Instance and Class
Variables and Method
Objective: Demonstrate the roles of instance and class
variables and their uses. This example adds a class
variable numberOfObjects to track the number of Circle
objects created.
CircleWithStaticMembers
TestCircleWithStaticMembers
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Visibility Modifiers and Accessor/Mutator
Methods (1 of 3)
By default, the class, variable, or method can be accessed
by any class in the same package.
• public
The class, data, or method is visible to any class in any
package.
• private
The data or methods can be accessed only by the
declaring class.
The get and set methods are used to read and modify
private properties.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Visibility Modifiers and Accessor/Mutator
Methods (2 of 3)
The private modifier restricts access to within a class, the
default modifier restricts access to within a package, and
the public modifier enables unrestricted access.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Visibility Modifiers and Accessor/Mutator
Methods (3 of 3)
The default modifier on a class restricts access to within a
package, and the public modifier enables unrestricted
access.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Note
An object cannot access its private members, as shown in
(b). It is OK, however, if the object is declared in its own
class, as shown in (a).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Why Data Fields Should Be Private?
To protect data.
To make code easy to maintain.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example of Data Field Encapsulation
Circle
-radius: double
-numberOfObjects: int
+Circle()
+Circle(radius: double)
+getRadius(): double
+setRadius(radius: double): void
+getNumberOfObjects(): int
+getArea(): double
The radius of this circle (default: 1.0).
The number of circle objects created.
Constructs a default circle object.
Constructs a circle object with the specified radius.
Returns the radius of this circle.
Sets a new radius for this circle.
Returns the number of circle objects created.
Returns the area of this circle.
The - sign indicates
private modifier
CircleWithPrivateDataFields
TestCircleWithPrivateDataFields
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Passing Objects to Methods (1 of 2)
• Passing by value for primitive type value (the value is
passed to the parameter)
• Passing by value for reference type value (the value is
the reference to the object)
TestPassObject
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Passing Objects to Methods (2 of 2)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Array of Objects (1 of 3)
Circle[] circleArray = new Circle[10];
An array of objects is actually an array of reference
variables. So invoking circleArray[1].getArea() involves two
levels of referencing as shown in the next figure.
circleArray references to the entire array. circleArray[1]
references to a Circle object.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Array of Objects (2 of 3)
Circle[] circleArray = new Circle[10];
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Array of Objects (3 of 3)
Summarizing the areas of the circles
TotalArea
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Immutable Objects and Classes
If the contents of an object cannot be changed once the
object is created, the object is called an immutable object
and its class is called an immutable class. If you delete the
set method in the Circle class in Listing 8.10, the class
would be immutable because radius is private and cannot
be changed without a set method.
A class with all private data fields and without mutators is
not necessarily immutable. For example, the following class
Student has all private data fields and no mutators, but it is
mutable.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example (2 of 3)
public class Student {
private int id;
private BirthDate birthDate;
public Student(int ssn,
int year, int month, int
day) {
id = ssn;
birthDate = new
BirthDate(year, month, day);
}
public int getId() {
return id;
}
public BirthDate getBirthDate() {
return birthDate;
}
}
public class BirthDate {
private int year;
private int month;
private int day;
public BirthDate(int newYear,
int newMonth, int newDay)
{
year = newYear;
month = newMonth;
day = newDay;
}
public void setYear(int
newYear) {
year = newYear;
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example (3 of 3)
public class Test {
public static void main(String[] args) {
Student student = new Student(111223333,
1970, 5, 3);
BirthDate date = student.getBirthDate();
date.setYear(2010); // Now the student
birth year is changed!
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
What Class is Immutable?
For a class to be immutable, it must mark all data fields
private and provide no mutator methods and no accessor
methods that would return a reference to a mutable data
field object.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Scope of Variables
• The scope of instance and static variables is the entire
class. They can be declared anywhere inside a class.
• The scope of a local variable starts from its declaration
and continues to the end of the block that contains the
variable. A local variable must be initialized explicitly
before it can be used.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The this Keyword
• The this keyword is the name of a reference that refers to
an object itself. One common use of the this keyword is
reference a class’s hidden data fields.
• Another common use of the this keyword to enable a
constructor to invoke another constructor of the same
class.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Reference the Hidden Data Fields
public class F {
private int i = 5;
private static double k = 0;
void setI(int i) {
this.i = i;
}
static void setK(double k) {
F.k = k;
}
}
Suppose that f1 and f2 are two objects of F.
F f1 = new F(); F f2 = new F();
Invoking f1.setI(10) is to execute
this.i = 10, where this refers f1
Invoking f2.setI(45) is to execute
this.i = 45, where this refers f2
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Calling Overloaded Constructor
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 10
Thinking in Objects
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations
You see the advantages of object-oriented programming
from the preceding chapter. This chapter will demonstrate
how to solve problems using the object-oriented paradigm.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives
10.1 To apply class abstraction to develop software (§10.2).
10.2 To explore the differences between the procedural paradigm and object-
oriented paradigm (§10.3).
10.3 To discover the relationships between classes (§10.4).
10.4 To design programs using the object-oriented paradigm (§§10.5–10.6).
10.5 To create objects for primitive values using the wrapper classes (Byte,
Short, Integer, Long, Float, Double, Character, and Boolean) (§10.7).
10.6 To simplify programming using automatic conversion between primitive
types and wrapper class types (§10.8).
10.7 To use the BigInteger and BigDecimal classes for computing very large
numbers with arbitrary precisions (§10.9).
10.8 To use the String class to process immutable strings (§10.10).
10.9 To use the StringBuilder and StringBuffer classes to process mutable
strings (§10.11).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Class Abstraction and Encapsulation
Class abstraction means to separate class implementation
from the use of the class. The creator of the class provides
a description of the class and let the user know how the
class can be used. The user of the class does not need to
know how the class is implemented. The detail of
implementation is encapsulated and hidden from the user.
Class Contract
(Signatures of
public methods
and
public constants)
Class
Class implementation
is like a black box
hidden from the clients
Clients use the
class through the
contract of the
class
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Designing the Loan Class
Loan
-annualInterestRate: double
-numberOfYears: int
-loanAmount: double
-loanDate: Date
+Loan()
+Loan(annualInterestRate:
double, numberOfYears: int,
loanAmount: double)
+getAnnualInterestRate(): double
+getNumberOfYears(): int
+getLoanAmount(): double
+getLoanDate(): Date
+setAnnualInterestRate(
annualInterestRate: double): void
+setNumberOfYears(
numberOfYears: int): void
+setLoanAmount(
loanAmount: double): void
+getMonthlyPayment(): double
+getTotalPayment(): double
The annual interest rate of the loan (default: 2.5).
The number of years for the loan (default: 1)
The loan amount (default: 1000).
The date this loan was created.
Constructs a default Loan object.
Constructs a loan with specified interest rate, years,
and loan amount.
Returns the annual interest rate of this loan.
Returns the number of the years of this loan.
Returns the amount of this loan.
Returns the date of the creation of this loan.
Sets a new annual interest rate to this loan.
Sets a new number of years to this loan.
Sets a new amount to this loan.
Returns the monthly payment of this loan.
Returns the total payment of this loan.
Loan TestLoanClass
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Object-Oriented Thinking
Chapters 1-8 introduced fundamental programming
techniques for problem solving using loops, methods, and
arrays. The studies of these techniques lay a solid
foundation for object-oriented programming. Classes
provide more flexibility and modularity for building reusable
software. This section improves the solution for a problem
introduced in Chapter 3 using the object-oriented approach.
From the improvements, you will gain the insight on the
differences between the procedural programming and
object-oriented programming and see the benefits of
developing reusable code using objects and classes.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The BMI Class
BMI UseBMIClass
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Class Relationships
Association
Aggregation
Composition
Inheritance (Chapter 13)
Association: is a general binary relationship that describes an activity
between two classes.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Object Composition
Composition is actually a special case of the aggregation
relationship. Aggregation models has-a relationships and
represents an ownership relationship between two objects.
The owner object is called an aggregating object and its
class an aggregating class. The subject object is called
an aggregated object and its class an aggregated class.
Name Address
Student
Composition Aggregation
1..3 1
1
1
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Class Representation
An aggregation relationship is usually represented as a
data field in the aggregating class. For example, the
relationship in Figure 10.6 can be represented as follows:
public class Name {
...
}
public class Student {
private Name name;
private Address address;
...
}
public class Address {
...
}
Aggregated class Aggregating class Aggregated class
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Aggregation or Composition
Since aggregation and composition relationships are
represented using classes in similar ways, many texts don’t
differentiate them and call both compositions.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Aggregation Between Same Class (1 of 2)
Aggregation may exist between objects of the same class. For
example, a person may have a supervisor.
Person
Supervisor
1
1
public class Person {
// The type for the data is the class itself
private Person supervisor;
...
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Aggregation Between Same Class (2 of 2)
What happens if a person has several supervisors?
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example: The Course Class
Course
-courseName: String
-students: String[]
-numberOfStudents: int
+Course(courseName: String)
+getCourseName(): String
+addStudent(student: String): void
+dropStudent(student: String): void
+getStudents(): String[]
+getNumberOfStudents(): int
The name of the course.
An array to store the students for the course.
The number of students (default: 0).
Creates a course with the specified name.
Returns the course name.
Adds a new student to the course.
Drops a student from the course.
Returns the students in the course.
Returns the number of students in the course.
Course TestCourse
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example: The StackOfIntegers Class
StackOfIntegers
-elements: int[]
-size: int
+StackOfIntegers()
+StackOfIntegers(capacity: int)
+empty(): boolean
+peek(): int
+push(value: int): int
+pop(): int
+getSize(): int
An array to store integers in the stack.
The number of integers in the stack.
Constructs an empty stack with a default capacity of 16.
Constructs an empty stack with a specified capacity.
Returns true if the stack is empty.
Returns the integer at the top of the stack without
removing it from the stack.
Stores an integer into the top of the stack.
Removes the integer at the top of the stack and returns it.
Returns the number of elements in the stack.
TestStackOfIntegers
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Designing the StackOfIntegers Class
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Implementing StackOfIntegers Class
StackOfIntegers
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Wrapper Classes
• Boolean
• Character
• Short
• Byte
• Integer
• Long
• Float
• Double
Note: (1) The wrapper
classes do not have no-arg
constructors. (2) The
instances of all wrapper
classes are immutable, i.e.,
their internal values cannot
be changed once the
objects are created.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Integer and Double Classes
java.lang.Integer
-value: int
+MAX_VALUE: int
+MIN_VALUE: int
+Integer(value: int)
+Integer(s: String)
+byteValue(): byte
+shortValue(): short
+intValue(): int
+longVlaue(): long
+floatValue(): float
+doubleValue():double
+compareTo(o: Integer): int
+toString(): String
+valueOf(s: String): Integer
+valueOf(s: String, radix: int): Integer
+parseInt(s: String): int
+parseInt(s: String, radix: int): int
java.lang.Double
-value: double
+MAX_VALUE: double
+MIN_VALUE: double
+Double(value: double)
+Double(s: String)
+byteValue(): byte
+shortValue(): short
+intValue(): int
+longVlaue(): long
+floatValue(): float
+doubleValue():double
+compareTo(o: Double): int
+toString(): String
+valueOf(s: String): Double
+valueOf(s: String, radix: int): Double
+parseDouble(s: String): double
+parseDouble(s: String, radix: int): double
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Integer Class and the Double
Class
• Constructors
• Class Constants MAX_VALUE, MIN_VALUE
• Conversion Methods
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Numeric Wrapper Class Constructors
You can construct a wrapper object either from a
primitive data type value or from a string representing
the numeric value. The constructors for Integer and
Double are:
public Integer(int value)
public Integer(String s)
public Double(double value)
public Double(String s)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Numeric Wrapper Class Constants
Each numerical wrapper class has the constants
MAX_VALUE and MIN_VALUE. MAX_VALUE represents
the maximum value of the corresponding primitive data
type. For Byte, Short, Integer, and Long, MIN_VALUE
represents the minimum byte, short, int, and long values.
For Float and Double, MIN_VALUE represents the
minimum positive float and double values. The following
statements display the maximum integer (2,147,483,647),
the minimum positive float (1.4E-45), and the maximum
double floating-point number
(1.79769313486231570e+308d).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Conversion Methods
Each numeric wrapper class implements the abstract
methods doubleValue, floatValue, intValue, longValue, and
shortValue, which are defined in the Number class. These
methods “convert” objects into primitive type values.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Static valueOf Methods
The numeric wrapper classes have a useful class method,
valueOf(String s). This method creates a new object
initialized to the value represented by the specified string.
For example:
Double doubleObject = Double.valueOf("12.4");
Integer integerObject = Integer.valueOf("12");
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Methods for Parsing Strings into
Numbers
You have used the parseInt method in the Integer class to
parse a numeric string into an int value and the
parseDouble method in the Double class to parse a
numeric string into a double value. Each numeric wrapper
class has two overloaded parsing methods to parse a
numeric string into an appropriate numeric value.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Automatic Conversion Between Primitive
Types and Wrapper Class Types
JDK 1.5 allows primitive type and wrapper classes to be
converted automatically. For example, the following
statement in (a) can be simplified as in (b):
Integer[] intArray = {new Integer(2),
new Integer(4), new Integer(3)};
(a)
Equivalent
(b)
Integer[] intArray = {2, 4, 3};
New JDK 1.5 boxing
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
BigInteger and BigDecimal (1 of 2)
If you need to compute with very large integers or high
precision floating-point values, you can use the BigInteger
and BigDecimal classes in the java.math package. Both are
immutable. Both extend the Number class and implement
the Comparable interface.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
BigInteger and BigDecimal (2 of 2)
BigInteger a = new BigInteger("9223372036854775807");
BigInteger b = new BigInteger("2");
BigInteger c = a.multiply(b); // 9223372036854775807 * 2
System.out.println(c);
BigDecimal a = new BigDecimal(1.0);
BigDecimal b = new BigDecimal(3);
BigDecimal c = a.divide(b, 20, BigDecimal.ROUND_UP);
System.out.println(c);
LargeFactorial
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The String Class
• Constructing a String:
String message = "Welcome to Java“;
String message = new String("Welcome to Java“);
String s = new String();
• Obtaining String length and Retrieving Individual Characters in a string
• String Concatenation (concat)
• Substrings (substring(index), substring(start, end))
• Comparisons (equals, compareTo)
• String Conversions
• Finding a Character or a Substring in a String
• Conversions between Strings and Arrays
• Converting Characters and Numeric Values to Strings
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Constructing Strings
String newString = new String(stringLiteral);
String message = new String("Welcome to Java");
Since strings are used frequently, Java provides a
shorthand initializer for creating a string:
String message = "Welcome to Java";
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Strings Are Immutable
A String object is immutable; its contents cannot be
changed. Does the following code change the contents of
the string?
String s = "Java";
s = "HTML";
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Code (1 of 5)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Code (2 of 5)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Interned Strings
Since strings are immutable and are frequently used, to
improve efficiency and save memory, the JVM uses a
unique instance for string literals with the same character
sequence. Such an instance is called interned. For
example, the following statements:
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Examples (1 of 4)
String s1 = "Welcome to Java";
String s2 = new String("Welcome to Java");
String s3 = "Welcome to Java";
System.out.println("s1 == s2 is " + (s1 == s2));
System.out.println("s1 == s3 is " + (s1 == s3));
: String
Interned string object
for "Welcome to Java"
: String
A string object for
"Welcome to Java"
s1
s2
s3
display
s1 == s is false
s1 == s3 is true
A new object is created if you use
the new operator.
If you use the string initializer, no
new object is created if the
interned object is already created.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Code (3 of 5)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Code (4 of 5)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Code (5 of 5)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Replacing and Splitting Strings (1 of 2)
java.lang.String
+replace(oldChar: char,
newChar: char): String
+replaceFirst(oldString:
String, newString: String):
String
+replaceAll(oldString: String,
newString: String): String
+split(delimiter: String):
String[]
Returns a new string that replaces all matching character in
this string with the new character.
Returns a new string that replaces the first matching
substring in this string with the new substring.
Returns a new string that replace all matching substrings in
this string with the new substring.
Returns an array of strings consisting of the substrings split
by the delimiter.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Examples (2 of 4)
"Welcome".replace('e', 'A') returns a new string, WAlcomA.
"Welcome".replaceFirst("e", "AB") returns a new string,
WABlcome.
"Welcome".replace("e", "AB") returns a new string,
WABlcomAB.
"Welcome".replace("el", "AB") returns a new string,
WABcome.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Splitting a String
String[] tokens =
"Java#HTML#Perl".split("#", 0);
for (int i = 0; i < tokens.length; i++)
System.out.print(tokens[i] + " ");
displays
Java HTML Perl
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Matching, Replacing and Splitting by
Patterns (1 of 3)
You can match, replace, or split a string by specifying a
pattern. This is an extremely useful and powerful feature,
commonly known as regular expression. Regular
expression is complex to beginning students. For this
reason, two simple patterns are used in this section. Please
refer to Supplement III.F, “Regular Expressions,” for further
studies.
"Java".matches("Java");
"Java".equals("Java");
"Java is fun".matches("Java.*");
"Java is cool".matches("Java.*");
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Matching, Replacing and Splitting by
Patterns (2 of 3)
The replaceAll, replaceFirst, and split methods can be used
with a regular expression. For example, the following
statement returns a new string that replaces $, +, or # in
"a+b$#c" by the string NNN.
String s = "a+b$#c".replaceAll("[$+#]", "NNN");
System.out.println(s);
Here the regular expression [$+#] specifies a pattern that
matches $, +, or #. So, the output is aNNNbNNNNNNc.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Matching, Replacing and Splitting by
Patterns (3 of 3)
The following statement splits the string into an array of
strings delimited by some punctuation marks.
String[] tokens = "Java,C?C#,C++".split("[.,:;?]");
for (int i = 0; i < tokens.length; i++)
System.out.println(tokens[i]);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Convert Character and Numbers to
Strings
The String class provides several static valueOf methods
for converting a character, an array of characters, and
numeric values to strings. These methods have the same
name valueOf with different argument types char, char[],
double, long, int, and float. For example, to convert a
double value to a string, use String.valueOf(5.44). The
return value is string consists of characters ‘5’, ‘.’, ‘4’, and
‘4’.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
StringBuilder and StringBuffer
The StringBuilder/StringBuffer class is an
alternative to the String class. In general, a
StringBuilder/StringBuffer can be used wherever a string is
used. StringBuilder/StringBuffer is more flexible than String.
You can add, insert, or append new contents into a string
buffer, whereas the value of a String object is fixed once the
string is created.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
StringBuilder Constructors
java.lang.StringBuilder
+StringBuilder()
+StringBuilder(capacity: int)
+StringBuilder(s: String)
Constructs an empty string builder with capacity 16.
Constructs a string builder with the specified capacity.
Constructs a string builder with the specified string.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Modifying Strings in the Builder
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Examples (3 of 4)
stringBuilder.append("Java");
stringBuilder.insert(11, "HTML and ");
stringBuilder.delete(8, 11) changes the builder to Welcome
Java.
stringBuilder.deleteCharAt(8) changes the builder to
Welcome o Java.
stringBuilder.reverse() changes the builder to avaJ ot
emocleW.
stringBuilder.replace(11, 15, "HTML")
changes the builder to Welcome to HTML.
stringBuilder.setCharAt(0, 'w') sets the builder to welcome
to Java.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The toString, capacity, length, setLength,
and charAt Methods
java.lang.StringBuilder
+toString(): String
+capacity(): int
+charAt(index: int): char
+length(): int
+setLength(newLength: int): void
+substring(startIndex: int): String
+substring(startIndex: int, endIndex:
int): String
+trimToSize(): void
Returns a string object from the string builder.
Returns the capacity of this string builder.
Returns the character at the specified index.
Returns the number of characters in this builder.
Sets a new length in this builder.
Returns a substring starting at startIndex.
Returns a substring from startIndex to endIndex-1.
Reduces the storage size used for the string builder.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Checking Palindromes Ignoring
Non-alphanumeric Characters
This example gives a program that counts the number of
occurrence of each letter in a string. Assume the letters are
not case-sensitive.
PalindromeIgnoreNonAlphanumeric
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Regular Expressions
A regular expression (abbreviated regex) is a string that
describes a pattern for matching a set of strings. Regular
expression is a powerful tool for string manipulations. You
can use regular expressions for matching, replacing, and
splitting strings.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Matching Strings
"Java".matches("Java");
"Java".equals("Java");
"Java is fun".matches("Java.*")
"Java is cool".matches("Java.*")
"Java is powerful".matches("Java.*")
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Regular Expression Syntax
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Replacing and Splitting Strings (2 of 2)
java.lang.String
+matches(regex: String): boolean
+replaceAll(regex: String,
replacement: String): String
+replaceFirst(regex: String,
replacement: String): String
+split(regex: String): String[]
Returns true if this string matches the
pattern.
Returns a new string that replaces all
matching substrings with the replacement.
Returns a new string that replaces the first
matching substring with the replacement.
Returns an array of strings consisting of the
substrings split by the matches.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Examples (4 of 4)
String s = "Java Java Java".replaceAll("vw", "wi") ;
String s = "Java Java Java".replaceFirst("vw", "wi") ;
String[] s = "Java1HTML2Perl".split("d");
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 11
Inheritance and
Polymorphism
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations
Suppose you will 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? The answer is to use
inheritance.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (1 of 2)
11.1 To define a subclass from a superclass through inheritance
(§11.2).
11.2 To invoke the superclass’s constructors and methods using the
super keyword (§11.3).
11.3 To override instance methods in the subclass (§11.4).
11.4 To distinguish differences between overriding and overloading
(§11.5).
11.5 To explore the toString() method in the Object class (§11.6).
11.6 To discover polymorphism and dynamic binding (§§11.7–11.8).
11.7 To describe casting and explain why explicit downcasting is
necessary (§11.9).
11.8 To explore the equals method in the Object class (§11.10).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (2 of 2)
11.9 To store, retrieve, and manipulate objects in an ArrayList (§11.11).
11.10 To construct an array list from an array, to sort and shuffle a list,
and to obtain max and min element from a list (§11.12).
11.11 To implement a Stack class using ArrayList (§11.13).
11.12 To enable data and methods in a superclass accessible from
subclasses using the protected visibility modifier (§11.14).
11.13 To prevent class extending and method overriding using the final
modifier (§11.14).
11.14 To automatically generate boilerplate code using Lombok
(§11.16).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Superclasses and Subclasses
GeometricObject
-color: String
-filled: boolean
-dateCreated: java.util.Date
+GeometricObject()
+GeometricObject(color: String,
filled: boolean)
+getColor(): String
+setColor(color: String): void
+isFilled(): boolean
+setFilled(filled: boolean): void
+getDateCreated(): java.util.Date
+toString(): String
The color of the object (default: white).
Indicates whether the object is filled with a color (default: false).
The date when the object was created.
Creates a GeometricObject.
Creates a GeometricObject with the specified color and filled
values.
Returns the color.
Sets a new color.
Returns the filled property.
Sets a new filled property.
Returns the dateCreated.
Returns a string representation of this object.
Circle
-radius: double
+Circle()
+Circle(radius: double)
+Circle(radius: double, color: String,
filled: boolean)
+getRadius(): double
+setRadius(radius: double): void
+getArea(): double
+getPerimeter(): double
+getDiameter(): double
+printCircle(): void
Rectangle
-width: double
-height: double
+Rectangle()
+Rectangle(width: double, height: double)
+Rectangle(width: double, height: double
color: String, filled: boolean)
+getWidth(): double
+setWidth(width: double): void
+getHeight(): double
+setHeight(height: double): void
+getArea(): double
+getPerimeter(): double
GeometricObject
Circle
Rectangle
TestCircleRectangle
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Are Superclass’s Constructor Inherited?
No. They are not inherited.
They are invoked explicitly or implicitly.
Explicitly using the super keyword.
A constructor is used to construct an instance of a class. Unlike
properties and methods, a superclass's constructors are not
inherited in the subclass. They can only be invoked from the
subclasses' constructors, using the keyword super. If the
keyword super is not explicitly used, the superclass's no-
arg constructor is automatically invoked.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Superclass’s Constructor Is Always
Invoked
A constructor may invoke an overloaded constructor or its
superclass’s constructor. If none of them is invoked
explicitly, the compiler puts super() as the first statement in
the constructor. For example,
public A() {
}
is equivalent to
public A() {
super();
}
public A(double d) {
// some statements
}
is equivalent to
public A(double d) {
super();
// some statements
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Using the Keyword super
The keyword super refers to the superclass of the class in
which super appears. This keyword can be used in two
ways:
• To call a superclass constructor
• To call a superclass method
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Caution
You must use the keyword super to call the superclass
constructor. Invoking a superclass constructor’s name in a
subclass causes a syntax error. Java requires that the
statement that uses the keyword super appear first in the
constructor.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Constructor Chaining (1 of 2)
Constructing an instance of a class invokes all the superclasses’
constructors along the inheritance chain. This is known as
constructor chaining.
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is
invoked");
}
}
class Employee extends Person {
public Employee() {
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Constructor Chaining (2 of 2)
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is
invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is
invoked");
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Execution (1 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Execution (2 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Execution (3 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Execution (4 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Execution (5 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Execution (6 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Execution (7 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Execution (8 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Execution (9 of 9)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example on the Impact of a Superclass
Without no-arg Constructor
Find out the errors in the program:
public class Apple extends Fruit {
}
class Fruit {
public Fruit(String name) {
System.out.println("Fruit's constructor is
invoked");
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Defining a Subclass
A subclass inherits from a superclass. You can also:
• Add new properties
• Add new methods
• Override the methods of the superclass
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Calling Superclass Methods
You could rewrite the printCircle() method in the Circle
class as follows:
public void printCircle() {
System.out.println("The circle is created " +
super.getDateCreated() + " and the radius is " + radius);
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Overriding Methods in the Superclass
A subclass inherits methods from a superclass. Sometimes it is
necessary for the subclass to modify the implementation of a method
defined in the superclass. This is referred to as method overriding.
public class Circle extends GeometricObject {
// Other methods are omitted
/** Override the toString method defined in
GeometricObject */
public String toString() {
return super.toString() + "nradius is " + radius;
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Note (1 of 4)
An instance method can be overridden only if it is
accessible. Thus a private method cannot be overridden,
because it is not accessible outside its own class. If a
method defined in a subclass is private in its superclass,
the two methods are completely unrelated.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Note (2 of 4)
Like an instance method, a static method can be inherited.
However, a static method cannot be overridden. If a static
method defined in the superclass is redefined in a
subclass, the method defined in the superclass is hidden.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Overriding versus Overloading
public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
a.p(10.0);
}
}
class B {
public void p(double i) {
System.out.println(i * 2);
}
}
class A extends B {
// This method overrides the method in B
public void p(double i) {
System.out.println(i);
}
}
public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
a.p(10.0);
}
}
class B {
public void p(double i) {
System.out.println(i * 2);
}
}
class A extends B {
// This method overloads the method in B
public void p(int i) {
System.out.println(i);
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Object Class and Its Methods
Every class in Java is descended from the java.lang.Object
class. If no inheritance is specified when a class is defined,
the superclass of the class is Object.
public class Circle {
...
}
Equivalent
public class Circle extends Object {
...
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The toString() Method in Object
The toString() method returns a string representation of the object.
The default implementation returns a string consisting of a class name
of which the object is an instance, the at sign (@), and a number
representing this object.
Loan loan = new Loan();
System.out.println(loan.toString());
The code displays something like Loan@15037e5 . This message is
not very helpful or informative. Usually you should override the toString
method so that it returns a digestible string representation of the object.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Polymorphism
Polymorphism means that a variable of a supertype can
refer to a subtype object.
A class defines a type. A type defined by a subclass is
called a subtype, and a type defined by its superclass is
called a supertype. Therefore, you can say that Circle is a
subtype of GeometricObject and GeometricObject is a
supertype for Circle.
PolymorphismDemo
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Polymorphism, Dynamic Binding and
Generic Programming (1 of 2)
DynamicBindingDemo
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Polymorphism, Dynamic Binding and
Generic Programming (2 of 2)
An object of a subtype can be used wherever its supertype
value is required. This feature is known as polymorphism.
When the method m(Object x) is executed, the argument
x’s toString method is invoked. x may be an instance of
GraduateStudent, Student, Person, or Object. Classes
GraduateStudent, Student, Person, and Object have their
own implementation of the toString method. Which
implementation is used will be determined dynamically by
the Java Virtual Machine at runtime. This capability is
known as dynamic binding.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Dynamic Binding
Dynamic binding works as follows: Suppose an object o is an instance of
classes 1 2 n-1 n
C , C , , C , and C , where 1
C is a subclass of 2 2
C , C
is a subclass of 3 n-1
C , , and C is a subclass of n
C . That is, n
C
is the most general class, and 1
C is the most specific class. In Java, n
C
is the Object class. If o invokes a method p, the JVM searches the
implementation for the method p in 1 2 n-1 n
C , C , , C and C , in this order,
until it is found. Once an implementation is found, the search stops and
the first-found implementation is invoked.
Cn Cn-1 . . . . . C2 C1
Object
Since o is an instance of C1, o is also an
instance of C2, C3, …, Cn-1, and Cn
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Method Matching versus Binding
Matching a method signature and binding a method
implementation are two issues. The compiler finds a
matching method according to parameter type, number of
parameters, and order of the parameters at compilation
time. A method may be implemented in several subclasses.
The Java Virtual Machine dynamically binds the
implementation of the method at runtime.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Generic Programming (1 of 2)
public class
PolymorphismDemo {
public static void
main(String[] args) {
m(new GraduateStudent());
m(new Student());
m(new Person());
m(new Object());
}
public static void
m(Object x) {
System.out.println(x.toSt
ring());
}
}
class GraduateStudent extends
Student {
}
class Student extends Person {
public String toString() {
return "Student";
}
}
class Person extends Object {
public String toString() {
return "Person";
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Generic Programming (2 of 2)
Polymorphism allows methods to be used generically for a wide
range of object arguments. This is known as generic
programming. If a method’s parameter type is a superclass (e.g.,
Object), you may pass an object to this method of any of the
parameter’s subclasses (e.g., Student or String). When an object
(e.g., a Student object or a String object) is used in the method,
the particular implementation of the method of the object that is
invoked (e.g., toString) is determined dynamically.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Casting Objects
You have already used the casting operator to convert variables of one
primitive type to another. Casting can also be used to convert an
object of one class type to another within an inheritance hierarchy. In
the preceding section, the statement
m(new Student());
assigns the object new Student() to a parameter of the Object type.
This statement is equivalent to:
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Why Casting Is Necessary?
Suppose you want to assign the object reference o to a variable of the
Student type using the following statement:
Student b = o;
A compile error would occur. Why does the statement Object o = new
Student() work and the statement Student b = o doesn’t? This is
because a Student object is always an instance of Object, but an Object
is not necessarily an instance of Student. Even though you can see that
o is really a Student object, the compiler is not so clever to know it. To
tell the compiler that o is a Student object, use an explicit casting. The
syntax is similar to the one used for casting among primitive data types.
Enclose the target object type in parentheses and place it before the
object to be cast, as follows:
Student b = (Student)o; // Explicit casting
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Casting From Superclass to Subclass
Explicit casting must be used when casting an object from
a superclass to a subclass. This type of casting may not
always succeed.
Apple x = (Apple)fruit;
Orange x = (Orange)fruit;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The instanceof Operator
Use the instanceof operator to test whether an object is
an instance of a class:
Object myObject = new Circle();
... // Some lines of code
/** Perform casting if myObject is an instance of
Circle */
if (myObject instanceof Circle) {
System.out.println("The circle diameter is " +
((Circle)myObject).getDiameter());
...
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
621
Java 16 instanceof Pattern Matching
When using the if statement to test if an object is an
instance of a class, you can specify a binding variable. If
the result of the instanceof operator is true, then the
object being tested is assigned to the binding variable.
This new syntax, known as instanceof pattern matching,
became a standard feature since Java 16. You can simplify
the code in lines 15-24 using this new feature as follows:
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
622
Java 16 New Features on instanceof
if (myObject instanceof Circle circle) {
System.out.println("The circle area is " +
circle.getArea());
System.out.println("The circle diameter is " +
circle.getDiameter());
}
else if (myObject instanceof Rectangle rectangle) {
System.out.println("The rectangle area is " +
rectangle.getArea());
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
TIP
To help understand casting, you may also consider the
analogy of fruit, apple, and orange with the Fruit class as
the superclass for Apple and Orange. An apple is a fruit, so
you can always safely assign an instance of Apple to a
variable for Fruit. However, a fruit is not necessarily an
apple, so you have to use explicit casting to assign an
instance of Fruit to a variable of Apple.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example: Demonstrating Polymorphism
and Casting
This example creates two geometric objects: a circle, and a
rectangle, invokes the displayGeometricObject method to
display the objects. The displayGeometricObject displays
the area and diameter if the object is a circle, and displays
area if the object is a rectangle.
CastingDemo
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The equals Method
The equals() method compares the contents of two objects. The default
implementation of the equals method in the Object class is as follows:
public boolean equals(Object obj){
return this == obj;
}
For example,
the equals
method is
overridden in
the Circle
class.
public boolean equals(Object o) {
if (o instanceof Circle) {
return radius ==((Circle)o).radius;
}
else
return false;
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Note (3 of 4)
The == comparison operator is used for comparing two
primitive data type values or for determining whether two
objects have the same references. The equals method is
intended to test whether two objects have the same
contents, provided that the method is modified in the
defining class of the objects. The == operator is stronger
than the equals method, in that the == operator checks
whether the two reference variables refer to the same
object.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The ArrayList Class
You can create an array to store objects. But the array’s size is fixed
once the array is created. Java provides the ArrayList class that can be
used to store an unlimited number of objects.
java.util.ArrayList<E>
+ArrayList()
+add(o: E) : void
+add(index: int, o: E) : void
+clear(): void
+contains(o: Object): boolean
+get(index: int) : E
+indexOf(o: Object) : int
+isEmpty(): boolean
+lastIndexOf(o: Object) : int
+remove(o: Object): boolean
+size(): int
+remove(index: int) : boolean
+set(index: int, o: E) : E
Creates an empty list.
Appends a new element o at the end of this list.
Adds a new element o at the specified index in this list.
Removes all the elements from this list.
Returns true if this list contains the element o.
Returns the element from this list at the specified index.
Returns the index of the first matching element in this list.
Returns true if this list contains no elements.
Returns the index of the last matching element in this list.
Removes the element o from this list.
Returns the number of elements in this list.
Removes the element at the specified index.
Sets the element at the specified index.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Generic Type
ArrayList is known as a generic class with a generic type E.
You can specify a concrete type to replace E when creating
an ArrayList. For example, the following statement creates
an ArrayList and assigns its reference to variable cities.
This ArrayList object can be used to store strings.
ArrayList<String> cities = new ArrayList<String>();
ArrayList<String> cities = new ArrayList<>();
TestArrayList
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Differences and Similarities Between
Arrays and ArrayList
Operation Array ArrayList
Creating an array/ArrayList String[] a = new
String[10]
ArrayList<String> list =
new ArrayList<>();
Accessing an element a[index] list.get(index);
Updating an element a[index] = "London"; list.set(index,
"London");
Returning size a.length list.size();
Adding a new element Blank
list.add("London");
Inserting a new element Blank
list.add(index,
"London");
Removing an element Blank
list.remove(index);
Removing an element Blank
list.remove(Object);
Removing all elements Blank
list.clear();
DistinctNumbers
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Array Lists from/to Arrays
Creating an ArrayList from an array of objects:
String[] array = {"red", "green", "blue"};
ArrayList<String> list = new
ArrayList<>(Arrays.asList(array));
Creating an array of objects from an ArrayList:
String[] array1 = new String[list.size()];
list.toArray(array1);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
max and min in an Array List
String[] array = {"red", "green", "blue"};
System.out.pritnln(java.util.Collections.max(
new ArrayList<String>(Arrays.asList(array)));
String[] array = {"red", "green", "blue"};
System.out.pritnln(java.util.Collections.min(
new ArrayList<String>(Arrays.asList(array)));
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Shuffling an Array List
Integer[] array = {3, 5, 95, 4, 15, 34, 3, 6, 5};
ArrayList<Integer> list = new
ArrayList<>(Arrays.asList(array));
java.util.Collections.shuffle(list);
System.out.println(list);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Stack Animation
https://liveexample.pearsoncmg.com/dsanimation/StackeBook.html
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The MyStack Classes
A stack to hold objects.
MyStack
MyStack
-list: ArrayList
+isEmpty(): boolean
+getSize(): int
+peek(): Object
+pop(): Object
+push(o: Object): void
+search(o: Object): int
Returns true if this stack is empty.
Returns the number of elements in this stack.
Returns the top element in this stack.
Returns and removes the top element in this stack.
Adds a new element to the top of this stack.
Returns the position of the first element in the stack from
the top that matches the specified element.
A list to store elements.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The protected Modifier
• The protected modifier can be applied on data and
methods in a class. A protected data or a protected
method in a public class can be accessed by any class in
the same package or its subclasses, even if the
subclasses are in a different package.
• private, default, protected, public
private, none (if no modifier is used), protected, public
Visibility increases
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Accessibility Summary
Modifier on
members in
a class
Accessed
from the
same class
Accessed
from the
same
package
Accessed
from a
subclass
Accessed
from a
different
package
public sign sign sign sign
protected sign sign sign Blank
default sign sign Blank Blank
private sign Blank Blank Blank
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Visibility Modifiers
public class C1 {
public int x;
protected int y;
int z;
private int u;
protected void m() {
}
}
public class C2 {
C1 o = new C1();
can access o.x;
can access o.y;
can access o.z;
cannot access o.u;
can invoke o.m();
}
public class C3
extends C1 {
can access x;
can access y;
can access z;
cannot access u;
can invoke m();
}
package p1;
public class C4
extends C1 {
can access x;
can access y;
cannot access z;
cannot access u;
can invoke m();
}
package p2;
public class C5 {
C1 o = new C1();
can access o.x;
cannot access o.y;
cannot access o.z;
cannot access o.u;
cannot invoke o.m();
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
A Subclass Cannot Weaken the
Accessibility
A subclass may override a protected method in its
superclass and change its visibility to public. However, a
subclass cannot weaken the accessibility of a method
defined in the superclass. For example, if a method is
defined as public in the superclass, it must be defined as
public in the subclass.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Note (4 of 4)
The modifiers are used on classes and class members
(data and methods), except that the final modifier can also
be used on local variables in a method. A final local
variable is a constant inside a method.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The final Modifier
• The final class cannot be extended:
final class Math {
...
}
• The final variable is a constant:
final static double PI = 3.14159;
• The final method cannot be overridden by its
subclasses.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
642
Lombok: Generating Boilerplate Code
Using Annotations
When you write Java code, there are lot of getter and
setter methods. It is tedious to write all these
boilerplate code. Project Lombok comes to rescue.
Project Lombok is a Java library that provides
annotations to tell the Java compiler to automatically
generate boilerplate code such as getter and setter
methods for data fields. To use Lombok, you need
download a jar file named lombok.jar from
https://projectlombok.org/download.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 12
Exception Handling and
Text IO
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations
When a program runs into a runtime error, the program
terminates abnormally. How can you handle the runtime
error so that the program can continue to run or terminate
gracefully? This is the subject we will introduce in this
chapter.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (1 of 2)
12.1 To get an overview of exceptions and exception handling (§12.2).
12.2 To explore the advantages of using exception handling (§12.2).
12.3 To distinguish exception types: Error (fatal) vs. Exception (nonfatal) and checked
versus unchecked (§12.3).
12.4 To declare exceptions in a method header (§12.4.1).
12.5 To throw exceptions in a method (§12.4.2).
12.6 To write a try-catch block to handle exceptions (§12.4.3).
12.7 To explain how an exception is propagated (§12.4.3).
12.8 To obtain information from an exception object (§12.4.4).
12.9 To develop applications with exception handling (§12.4.5).
12.10 To use the finally clause in a try-catch block (§12.5).
12.11 To use exceptions only for unexpected errors (§12.6).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (2 of 2)
12.12 To rethrow exceptions in a catch block (§12.7).
12.13 To create chained exceptions (§12.8).
12.14 To define custom exception classes (§12.9).
12.15 To discover file/directory properties, to delete and rename files/directories, and to
create directories using the File class (§12.10).
12.16 To write data to a file using the PrintWriter class (§12.11.1).
12.17 To use try-with-resources to ensure that the resources are closed automatically
(§12.11.2).
12.18 To read data from a file using the Scanner class (§12.11.3).
12.19 To understand how data is read using a Scanner (§12.11.4).
12.20 To develop a program that replaces text in a file (§12.11.5).
12.21 To read data from the Web (§12.12).
12.22 To develop a Web crawler (§12.13).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Exception-Handling Overview
Show runtime error
Quotient
Fix it using an if statement
QuotientWithIf
With a method
QuotientWithMethod
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Exception Advantages
QuotientWithException
Now you see the advantages of using exception
handling. It enables a method to throw an exception to
its caller. Without this capability, a method must handle
the exception or terminate the program.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Handling InputMismatchException
InputMismatchExceptionDemo
By handling InputMismatchException, your program will
continuously read an input until it is correct.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Exception Types
LinkageError
Error
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Many more classes
Many more classes
Many more classes
IllegalArgumentException
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
System Errors
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Exceptions
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Runtime Exceptions
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Checked Exceptions versus Unchecked
Exceptions
RuntimeException, Error and their subclasses are known
as unchecked exceptions. All other exceptions are known
as checked exceptions, meaning that the compiler forces
the programmer to check and deal with the exceptions.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Unchecked Exceptions (1 of 2)
In most cases, unchecked exceptions reflect programming
logic errors that are not recoverable. For example, a
NullPointerException is thrown if you access an object
through a reference variable before an object is assigned
to it; an IndexOutOfBoundsException is thrown if you
access an element in an array outside the bounds of the
array. These are the logic errors that should be corrected
in the program. Unchecked exceptions can occur
anywhere in the program. To avoid cumbersome overuse
of try-catch blocks, Java does not mandate you to write
code to catch unchecked exceptions.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Unchecked Exceptions (2 of 2)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Declaring, Throwing, and Catching
Exceptions
method1() {
try {
invoke method2;
}
catch (Exception ex) {
Process exception;
}
}
method2() throws Exception {
if (an error occurs) {
throw new Exception();
}
}
catch exception throw exception
declare exception
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Declaring Exceptions
Every method must state the types of checked exceptions
it might throw. This is known as declaring exceptions.
public void myMethod()
throws IOException
public void myMethod()
throws IOException, OtherException
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Throwing Exceptions
When the program detects an error, the program can
create an instance of an appropriate exception type and
throw it. This is known as throwing an exception. Here is
an example,
throw new TheException();
TheException ex = new TheException();
throw ex;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Throwing Exceptions Example
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Catching Exceptions (1 of 2)
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Catching Exceptions (2 of 2)
try
catch
try
catch
try
catch
An exception
is thrown in
method3
Call Stack
main method main method
method1
main method
method1
main method
method1
method2 method2
method3
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Catch or Declare Checked Exceptions (1 of 2)
Suppose p2 is defined as follows:
void p2() throws IOException {
if (a file does not exist) {
throw new IOException("File does not exist");
}
...
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Catch or Declare Checked Exceptions (2 of 2)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example: Declaring, Throwing, and
Catching Exceptions
• Objective: This example demonstrates declaring,
throwing, and catching exceptions by modifying the
setRadius method in the Circle class defined in Chapter
9. The new setRadius method throws an exception if
radius is negative.
CircleWithException
TestCircleWithException
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Rethrowing Exceptions
try {
statements;
}
catch(TheException ex) {
perform operations before exits;
throw ex;
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The finally Clause
try {
statements;
}
catch(TheException ex){
handling ex;
}
finally {
finalStatements;
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (1 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (2 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (3 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (4 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (5 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (6 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (7 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (8 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (9 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (10 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (11 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Cautions When Using Exceptions
• 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, and
propagating the errors to the calling methods.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
When to Throw Exceptions
• An exception occurs in a method. If you want the
exception to be processed by its caller, you should
create an exception object and throw it. If you can
handle the exception in the method where it occurs,
there is no need to throw it.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
When to Use Exceptions (1 of 2)
When should you use the try-catch block in the code? You should use it to
deal with unexpected error conditions. Do not use it to deal with simple,
expected situations. For example, the following code
try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
When to Use Exceptions (2 of 2)
is better to be replaced by
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Defining Custom Exception Classes
• Use the exception classes in the API whenever possible.
• Define custom exception classes if the predefined
classes are not sufficient.
• Define custom exception classes by extending Exception
or a subclass of Exception.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Custom Exception Class Example
In Listing 13.8, the setRadius method throws an exception
if the radius is negative. Suppose you wish to pass the
radius to the handler, you have to create a custom
exception class.
InvalidRadiusException
CircleWithRadiusException
TestCircleWithRadiusException
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Assertions
An assertion is a Java statement that enables you to assert
an assumption about your program. An assertion contains
a Boolean expression that should be true during program
execution. Assertions can be used to assure program
correctness and avoid logic errors.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Declaring Assertions
An assertion is declared using the new Java keyword
assert in JDK 1.4 as follows:
assert assertion; or
assert assertion : detailMessage;
where assertion is a Boolean expression and
detailMessage is a primitive-type or an Object value.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Executing Assertions
When an assertion statement is executed, Java evaluates the
assertion. If it is false, an AssertionError will be thrown. The
AssertionError class has a no-arg constructor and seven
overloaded single-argument constructors of type int, long, float,
double, boolean, char, and Object.
For the first assert statement with no detail message, the no-arg
constructor of AssertionError is used. For the second assert
statement with a detail message, an appropriate AssertionError
constructor is used to match the data type of the message. Since
AssertionError is a subclass of Error, when an assertion becomes
false, the program displays a message on the console and exits.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Executing Assertions Example
public class AssertionDemo {
public static void main(String[] args) {
int i; int sum = 0;
for (i = 0; i < 10; i++) {
sum += i;
}
assert i == 10;
assert sum > 10 && sum < 5 * 10 : "sum is
" + sum;
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Compiling Programs With Assertions
Since assert is a new Java keyword introduced in JDK 1.4,
you have to compile the program using a JDK 1.4 compiler.
Furthermore, you need to include the switch –source 1.4 in
the compiler command as follows:
javac –source 1.4 AssertionDemo.java
NOTE: If you use JDK 1.5, there is no need to use the –
source 1.4 option in the command.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Running Programs With Assertions
By default, the assertions are disabled at runtime. To enable
it, use the switch –enableassertions, or –ea for short, as
follows:
java –ea AssertionDemo
Assertions can be selectively enabled or disabled at class
level or package level. The disable switch is –
disableassertions or –da for short. For example, the
following command enables assertions in package
package1 and disables assertions in class Class1.
java –ea:package1 –da:Class1 AssertionDemo
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Using Exception Handling or Assertions (1 of 4)
Assertion should not be used to replace exception
handling. Exception handling deals with unusual
circumstances during program execution. Assertions are to
assure the correctness of the program. Exception handling
addresses robustness and assertion addresses
correctness. Like exception handling, assertions are not
used for normal tests, but for internal consistency and
validity checks. Assertions are checked at runtime and can
be turned on or off at startup time.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Using Exception Handling or Assertions (2 of 4)
Do not use assertions for argument checking in public
methods. Valid arguments that may be passed to a public
method are considered to be part of the method’s contract.
The contract must always be obeyed whether assertions
are enabled or disabled. For example, the following code in
the Circle class should be rewritten using exception
handling.
public void setRadius(double newRadius) {
assert newRadius >= 0;
radius = newRadius;
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Using Exception Handling or Assertions (3 of 4)
Use assertions to reaffirm assumptions. This gives you
more confidence to assure correctness of the program. A
common use of assertions is to replace assumptions with
assertions in the code.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Using Exception Handling or Assertions (4 of 4)
Another good use of assertions is place assertions in a
switch statement without a default case. For example,
switch (month) {
case 1: ... ; break;
case 2: ... ; break;
...
case 12: ... ; break;
default: assert false : "Invalid month: "
+ month
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The File Class
The File class is intended to provide an abstraction that
deals with most of the machine-dependent complexities of
files and path names in a machine-independent fashion.
The filename is a string. The File class is a wrapper class
for the file name and its directory path.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Obtaining File Properties and
Manipulating File
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Explore File Properties
Objective: Write a program that demonstrates how to
create files in a platform-independent way and use the
methods in the File class to obtain their properties. The
following figures show a sample run of the program on
Windows and on Unix.
TestFileClass
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Text I/O
A File object encapsulates the properties of a file or a path,
but does not contain the methods for reading/writing data
from/to a file. In order to perform I/O, you need to create
objects using appropriate Java I/O classes. The objects
contain the methods for reading/writing data from/to a file.
This section introduces how to read/write strings and
numeric values from/to a text file using the Scanner and
PrintWriter classes.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Writing Data Using PrintWriter
java.io.PrintWriter
+PrintWriter(filename: String)
+print(s: String): void
+print(c: char): void
+print(cArray: char[]): void
+print(i: int): void
+print(l: long): void
+print(f: float): void
+print(d: double): void
+print(b: boolean): void
Also contains the overloaded
println methods.
Also contains the overloaded
printf methods.
.
Creates a PrintWriter for the specified file.
Writes a string.
Writes a character.
Writes an array of character.
Writes an int value.
Writes a long value.
Writes a float value.
Writes a double value.
Writes a boolean value.
A println method acts like a print method; additionally it
prints a line separator. The line separator string is defined
by the system. It is rn on Windows and n on Unix.
The printf method was introduced in §4.6, “Formatting
Console Output and Strings.”
WriteData
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Try-with-resources
Programmers often forget to close the file. JDK 7 provides
the followings new try-with-resources syntax that
automatically closes the files.
try (declare and create resources) {
Use the resource to process the file;
}
WriteDataWithAutoClose
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Reading Data Using Scanner
java.util.Scanner
+Scanner(source: File)
+Scanner(source: String)
+close()
+hasNext(): boolean
+next(): String
+nextByte(): byte
+nextShort(): short
+nextInt(): int
+nextLong(): long
+nextFloat(): float
+nextDouble(): double
+useDelimiter(pattern: String):
Scanner
Creates a Scanner object to read data from the specified file.
Creates a Scanner object to read data from the specified string.
Closes this scanner.
Returns true if this scanner has another token in its input.
Returns next token as a string.
Returns next token as a byte.
Returns next token as a short.
Returns next token as an int.
Returns next token as a long.
Returns next token as a float.
Returns next token as a double.
Sets this scanner’s delimiting pattern.
ReadData
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Replacing Text
Write a class named ReplaceText that replaces a string in a text
file with a new string. The filename and strings are passed as
command-line arguments as follows:
java ReplaceText sourceFile targetFile oldString newString
For example, invoking
java ReplaceText FormatString.java t.txt StringBuilder
StringBuffer
replaces all the occurrences of StringBuilder by StringBuffer in
FormatString.java and saves the new file in t.txt.
ReplaceText
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Reading Data From the Web (1 of 2)
Just like you can read data from a file on your computer,
you can read data from a file on the Web.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Reading Data From the Web (2 of 2)
URL url = new URL("www.google.com/index.html");
After a URL object is created, you can use the
openStream() method defined in the URL class to open an
input stream and use this stream to create a Scanner
object as follows:
Scanner input = new Scanner(url.openStream());
ReadFileFromURL
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Web Crawler (1 of 3)
This case study develops a program that travels the Web
by following hyperlinks.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Web Crawler (2 of 3)
The program follows the URLs to traverse the Web. To
avoid that each URL is traversed only once, the program
maintains two lists of URLs. One list stores the URLs
pending for traversing and the other stores the URLs that
have already been traversed. The algorithm for this
program can be described as follows:
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Web Crawler (3 of 3)
Add the starting URL to a list named listOfPendingURLs;
while listOfPendingURLs is not empty {
Remove a URL from listOfPendingURLs;
if this URL is not in listOfTraversedURLs {
Add it to listOfTraversedURLs;
Display this URL;
Exit the while loop when the size of S is equal to 100.
Read the page from this URL and for each URL contained in the page {
Add it to listOfPendingURLs if it is not is listOfTraversedURLs;
}
}
}
WebCrawler
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 13
Abstract Classes and
Interfaces
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations
• 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 to
perform an action?
• In order to write such code, you have to know about
interfaces. An interface is for defining common behavior
for classes (including unrelated classes). Before
discussing interfaces, we introduce a closely related
subject: abstract classes.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives
13.1 To design and use abstract classes (§13.2).
13.2 To generalize numeric wrapper classes, BigInteger, and BigDecimal using the
abstract Number class (§13.3).
13.3 To process a calendar using the Calendar and GregorianCalendar classes (§13.4).
13.4 To specify common behavior for objects using interfaces (§13.5).
13.5 To define interfaces and define classes that implement interfaces (§13.5).
13.6 To define a natural order using the Comparable interface (§13.6).
13.7 To make objects cloneable using the Cloneable interface (§13.7).
13.8 To explore the similarities and differences among concrete classes, abstract classes,
and interfaces (§13.8).
13.9 To design the Rational class for processing rational numbers (§13.9).
13.10 To design classes that follow the class-design guidelines (§13.10).
13.11 To use a simple one-line code to define a record (§13.11).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Abstract Classes and Abstract Methods
GeometricObject
Circle
Rectangle
TestGeometricObject
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Abstract Method in Abstract Class
An abstract method cannot be contained in a nonabstract
class. If a subclass of an abstract superclass does not
implement all the abstract methods, the subclass must be
defined abstract. In other words, in a nonabstract subclass
extended from an abstract class, all the abstract methods
must be implemented, even if they are not used in the
subclass.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Object Cannot be Created From Abstract
Class
An abstract class cannot be instantiated using the new
operator, but you can still define its constructors, which are
invoked in the constructors of its subclasses. For instance,
the constructors of GeometricObject are invoked in the
Circle class and the Rectangle class.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Abstract Class Without Abstract Method
A class that contains abstract methods must be abstract.
However, it is possible to define an abstract class that
contains no abstract methods. In this case, you cannot
create instances of the class using the new operator. This
class is used as a base class for defining a new subclass.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Superclass of Abstract Class May Be
Concrete
A subclass can be abstract even if its superclass is
concrete. For example, the Object class is concrete, but its
subclasses, such as GeometricObject, may be abstract.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Concrete Method Overridden to Be
Abstract
A subclass can override a method from its superclass to
define it abstract. This is rare, but useful when the
implementation of the method in the superclass becomes
invalid in the subclass. In this case, the subclass must be
defined abstract.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Abstract Class as Type
You cannot create an instance from an abstract class using
the new operator, but an abstract class can be used as a
data type. Therefore, the following statement, which
creates an array whose elements are of GeometricObject
type, is correct.
GeometricObject[] geo = new GeometricObject[10];
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: The Abstract Number Class
LargestNumbers
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Abstract Calendar Class and Its
GregorianCalendar Subclass (1 of 2)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Abstract Calendar Class and Its
GregorianCalendar Subclass (2 of 2)
An instance of java.util.Date represents a specific instant in
time with millisecond precision. java.util.Calendar is an
abstract base class for extracting detailed information such
as year, month, date, hour, minute and second from a Date
object. Subclasses of Calendar can implement specific
calendar systems such as Gregorian calendar, Lunar
Calendar and Jewish calendar. Currently,
java.util.GregorianCalendar for the Gregorian calendar is
supported in the Java API.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The GregorianCalendar Class
You can use new GregorianCalendar() to construct a
default GregorianCalendar with the current time and use
new GregorianCalendar(year, month, date) to construct a
GregorianCalendar with the specified year, month, and
date. The month parameter is 0-based, i.e., 0 is for
January.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The get Method in Calendar Class
The get(int field) method defined in the Calendar class is useful to
extract the date and time information from a Calendar object. The fields
are defined as constants, as shown in the following.
Constant Description
YEAR The year of the calendar.
MONTH The month of the calendar, with 0 for January.
DATE The day of the calendar.
HOUR The hour of the calendar (12-hour notation).
HOUR_OF_DAY The hour of the calendar (24-hour notation).
MINUTE The minute of the calendar.
SECOND The second of the calendar.
DAY_OF_WEEK The day number within the week, with 1 for Sunday.
DAY_OF_MONTH Same as DATE.
DAY_OF_YEAR The day number in the year, with I for the first day of the year.
WEEK_OF_MONTH The week number within the month, with I for the first week.
WEEK_OF_YEAR The week number within the year, with 1 for the first week.
AM_PM Indicator for AM or PM (0 for AM and I for PM).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Getting Date/Time Information From
Calendar
TestCalendar
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Interfaces
What is an interface?
Why is an interface useful?
How do you define an interface?
How do you use an interface?
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
What Is an Interface? Why Is an Interface
Useful?
An interface is a classlike construct that contains only
constants and abstract methods. In many ways, an
interface is similar to an abstract class, but the intent of an
interface is to specify common behavior for objects. For
example, you can specify that the objects are comparable,
edible, cloneable using appropriate interfaces.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Define an Interface
To distinguish an interface from a class, Java uses the following
syntax to define an interface:
public interface InterfaceName {
constant declarations;
abstract method signatures;
}
Example:
public interface Edible {
/** Describe how to eat */
public abstract String howToEat();
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Interface Is a Special Class
An interface is treated like a special class in Java. Each
interface is compiled into a separate bytecode file, just
like a regular class. Like an abstract class, you cannot
create an instance from an interface using the new
operator, but in most cases you can use an interface
more or less the same way you use an abstract class.
For example, you can use an interface as a data type for
a variable, as the result of casting, and so on.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example (1 of 2)
You can now use the Edible interface to specify whether an object is
edible. This is accomplished by letting the class for the object implement
this interface using the implements keyword. For example, the classes
Chicken and Fruit implement the Edible interface (See TestEdible).
Edible TestEdible
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Omitting Modifiers in Interfaces
All data fields are public final static and all methods are
public abstract in an interface. For this reason, these
modifiers can be omitted, as shown below:
public interface T1 {
public static final int K = 1;
public abstract void p();
}
Equivalent
public interface T1 {
int K = 1;
void p();
}
A constant defined in an interface can be accessed using
syntax InterfaceName.CONSTANT_NAME (e.g., T1.K).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example: The Comparable Interface
// This interface is defined in
// java.lang package
package java.lang;
public interface Comparable<E> {
public int compareTo(E o);
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The toString, equals, and hashCode
Methods
Each wrapper class overrides the toString, equals, and
hashCode methods defined in the Object class. Since all
the numeric wrapper classes and the Character class
implement the Comparable interface, the compareTo
method is implemented in these classes.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Integer and BigInteger Classes
public class Integer extends Number
implements Comparable<Integer> {
// class body omitted
@Override
public int compareTo(Integer o) {
// Implementation omitted
}
}
public class BigInteger extends Number
implements Comparable<BigInteger> {
// class body omitted
@Override
public int compareTo(BigInteger o) {
// Implementation omitted
}
}
String and Date Classes
public class String extends Object
implements Comparable<String> {
// class body omitted
@Override
public int compareTo(String o) {
// Implementation omitted
}
}
public class Date extends Object
implements Comparable<Date> {
// class body omitted
@Override
public int compareTo(Date o) {
// Implementation omitted
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example (2 of 2)
1. System.out.println(new Integer(3).compareTo(new
Integer(5)));
2. System.out.println("ABC".compareTo("ABE"));
3. java.util.Date date1 = new java.util.Date(2013, 1, 1);
4. java.util.Date date2 = new java.util.Date(2012, 1, 1);
5. System.out.println(date1.compareTo(date2));
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Generic sort Method
Let n be an Integer object, s be a String object, and d be a
Date object. All the following expressions are true.
s instanceof String
s instanceof Object
s instanceof Comparable
d instanceof java.util.Date
d instanceof Object
d instanceof Comparable
n instanceof Integer
n instanceof Object
n instanceof Comparable
The java.util.Arrays.sort(array) method requires that the
elements in an array are instances of Comparable<E>.
SortComparableObjects
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Defining Classes to Implement
Comparable
ComparableRectangle SortRectangles
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Cloneable Interfaces
Marker Interface: An empty interface.
A marker interface does not contain constants or
methods. It is used to denote that a class possesses
certain desirable properties. A class that implements the
Cloneable interface is marked cloneable, and its objects
can be cloned using the clone() method defined in the
Object class.
package java.lang;
public interface Cloneable {
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Examples
Many classes (e.g., Date and Calendar) in the Java library implement
Cloneable. Thus, the instances of these classes can be cloned. For
example, the following code
Calendar calendar = new GregorianCalendar(2003, 2, 1);
Calendar calendarCopy = (Calendar)calendar.clone();
System.out.println("calendar == calendarCopy is " +
(calendar == calendarCopy));
System.out.println("calendar.equals(calendarCopy) is " +
calendar.equals(calendarCopy));
displays
calendar == calendarCopy is false
calendar.equals(calendarCopy) is true
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Implementing Cloneable Interface
To define a custom class that implements the Cloneable
interface, the class must override the clone() method in the
Object class. The following code defines a class named
House that implements Cloneable and Comparable.
House
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Shallow versus Deep Copy (1 of 2)
House house1 = new House(1, 1750.50);
House house2 = (House)house1.clone();
Shallow
Copy
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Shallow versus Deep Copy (2 of 2)
House house1 = new House(1, 1750.50);
House house2 = (House)house1.clone();
Deep Copy
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Interfaces versus Abstract Classes (1 of 2)
In an interface, the data must be constants; an abstract
class can have all types of data.
Each method in an interface has only a signature without
implementation; an abstract class can have concrete
methods.
Blank
Variables Constructors Methods
Abstract
class
No restrictions. Constructors are invoked by
subclasses through constructor
chaining. An abstract class cannot be
instantiated using the new operator.
No restrictions.
Interface All variables must be
public static final
No constructors. An interface cannot
be instantiated using the new
operator.
All methods must be
public abstract
instance methods
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Interfaces versus Abstract Classes (2 of 2)
All classes share a single root, the Object class, but there is no single root for interfaces.
Like a class, an interface also defines a type. A variable of an interface type can
reference any instance of the class that implements the interface. If a class extends an
interface, this interface plays the same role as a superclass. You can use an interface as
a data type and cast a variable of an interface type to its subclass, and vice versa.
Suppose that c is an instance of Class2. c is also an instance of Object, Class1,
Interface1, Interface1_1, Interface1_2, Interface2_1, and Interface2_2.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Caution: Conflict Interfaces
In rare occasions, a class may implement two interfaces
with conflict information (e.g., two same constants with
different values or two methods with same signature but
different return type). This type of errors will be detected by
the compiler.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Whether to Use an Interface or a Class?
Abstract classes and interfaces can both be used to model
common features. How do you decide whether to use an
interface or a class? In general, a strong is-a relationship that
clearly describes a parent-child relationship should be modeled
using classes. For example, a staff member is a person. A weak
is-a relationship, also 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 String class implements the
Comparable interface. You can also use interfaces to circumvent
single inheritance restriction if multiple inheritance is desired. In
the case of multiple inheritance, you have to design one as a
superclass, and others as interface.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Rational Class
Rational TestRationalClass
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Designing a Class (1 of 5)
(Coherence) A class should describe a single entity, and all
the class operations should logically fit together to support
a coherent purpose. You can use a class for students, for
example, but you should not combine students and staff in
the same class, because students and staff have different
entities.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Designing a Class (2 of 5)
(Separating responsibilities) A single entity with too many
responsibilities can be broken into several classes to
separate responsibilities. The classes String, StringBuilder,
and StringBuffer all deal with strings, for example, but have
different responsibilities. The String class deals with
immutable strings, the StringBuilder class is for creating
mutable strings, and the StringBuffer class is similar to
StringBuilder except that StringBuffer contains
synchronized methods for updating strings.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Designing a Class (3 of 5)
Classes are designed for reuse. Users can incorporate
classes in many different combinations, orders, and
environments. Therefore, you should design a class that
imposes no restrictions on what or when the user can do
with it, design the properties to ensure that the user can
set properties in any order, with any combination of
values, and design methods to function independently of
their order of occurrence.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Designing a Class (4 of 5)
Provide a public no-arg constructor and override the
equals method and the toString method defined in the
Object class whenever possible.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Designing a Class (5 of 5)
Follow standard Java programming style and naming
conventions. Choose informative names for classes, data
fields, and methods. Always place the data declaration
before the constructor, and place constructors before
methods. Always provide a constructor and initialize
variables to avoid programming errors.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Using Visibility Modifiers (1 of 2)
Each class can present two contracts – one for the users of
the class and one for the extenders of the class. Make the
fields private and accessor methods public if they are
intended for the users of the class. Make the fields or
method protected if they are intended for extenders of the
class. The contract for the extenders encompasses the
contract for the users. The extended class may increase
the visibility of an instance method from protected to public,
or change its implementation, but you should never change
the implementation in a way that violates that contract.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Using Visibility Modifiers (2 of 2)
A class should use the private modifier to hide its data from
direct access by clients. You can use get methods and set
methods to provide users with access to the private data,
but only to private data you want the user to see or to
modify. A class should also hide methods not intended for
client use. The gcd method in the Rational class is private,
for example, because it is only for internal use within the
class.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Using the Static Modifier
A property that is shared by all the instances of the class
should be declared as a static property.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
755
Records
Often you need to create a simple object to hold data.
Before Java 16, you have to define a class and write a lot of
boilerplate code. This is tedious, however. Since Java 14, you
can define a record to simplify coding. For example, the
following code defines a record for Teachers.
public record Teacher(String name, java.util.Date date) {}
This simple one-line code is roughly equivalent to the
following class definition in LiveExample 13.14.
Teacher
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and Data
Structures
Thirteenth Edition
Chapter 18
Recursion
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations (1 of 2)
Suppose you want to find all the files under a directory that
contains a particular word. How do you solve this problem?
There are several ways to solve this problem. An intuitive
solution is to use recursion by searching the files in the
subdirectories recursively.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations (2 of 2)
H-trees, depicted in Figure 18.1, are used in a very large-
scale integration (VLSI) design as a clock distribution
network for routing timing signals to all parts of a chip with
equal propagation delays. How do you write a program to
display H-trees? A good approach is to use recursion.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (1 of 2)
18.1 To describe what a recursive method is and the benefits of
using recursion (§18.1).
18.2 To develop recursive methods for recursive mathematical
functions (§§18.2–18.3).
18.3 To explain how recursive method calls are handled in a call
stack (§§18.2–18.3).
18.4 To solve problems using recursion (§18.4).
18.5 To use an overloaded helper method to derive a recursive
method (§18.5).
18.6 To implement a selection sort using recursion (§18.5.1).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (2 of 2)
18.7 To implement a binary search using recursion (§18.5.2).
18.8 To get the directory size using recursion (§18.6).
18.9 To solve the Tower of Hanoi problem using recursion
(§18.7).
18.10 To draw fractals using recursion (§18.8).
18.11 To discover the relationship and difference between
recursion and iteration (§18.9).
18.12 To know tail-recursive methods and why they are
desirable (§18.10).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Computing Factorial (1 of 11)
Mathematic notation:
n! = n * (n-1)!, n > 0
0! = 1
Function:
factorial(0) = 1;
factorial(n) = n*factorial(n-1); n > 0
ComputeFactorial
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Computing Factorial (2 of 11)
factorial(0) 1
;

factorial(n) n*factorial(n 1);
 
factorial(4)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Computing Factorial (3 of 11)
factorial(0) 1;

factorial(n) n*factorial(n 1);
 
factorial(4) 4 * factorial(3)

Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Computing Factorial (4 of 11)

factorial(0) 1;
factorial(n) n*factorial(n 1);
 
factorial(4) 4 * factorial(3)

4 * 3 * factorial(2))

Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Computing Factorial (5 of 11)
factorial(0) 1;

factorial(n) n*factorial(n 1);
 
factorial(4) 4 * factorial(3)

4 * 3 * factorial(2)

4 * 3 * (2 * factorial(1))

Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Computing Factorial (6 of 11)
factorial(0) 1;

factorial(n) n*factorial(n 1);
 
factorial(4) 4 * factorial(3)

4 * 3 * factorial(2)

4 * 3 * (2 * factorial(1))

4 * 3 * (2 * (1* factorial(0)))

Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Computing Factorial (7 of 11)
factorial(0) 1;

factorial(n) n*factorial(n 1);
 
factorial(4) 4 * factorial(3)

4 * 3 * factorial(2)

4 * 3 * (2 * factorial(1))

4 * 3 * (2 * (1* factorial(0)))

4 * 3 * (2 * (1*1)))

Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Computing Factorial (8 of 11)
factorial(0) 1;

factorial(n) n*factorial(n 1);
 
factorial(4) 4 * factorial(3)

4 * 3 * factorial(2)

4 * 3 * (2 * factorial(1))

4 * 3 * (2 * (1* factorial(0)))

4 * 3 * (2 * (1*1)))

4 * 3 * (2 *1)

Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Computing Factorial (9 of 11)
factorial(0) 1;

factorial(n) n*factorial(n 1);
 
factorial(4) 4 * factorial(3)

4 * 3 * factorial(2)

4 * 3 * (2 * factorial(1))

4 * 3 * (2 * (1* factorial(0)))

4 * 3 * (2 * (1*1)))

4 * 3 * (2 *1)

4 * 3 * 2

Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Computing Factorial (10 of 11)
factorial(0) 1;

factorial(n) n*factorial(n 1);
 
factorial(4) 4 * factorial(3)

4 * (3 * factorial(2))

4 * (3 * (2 * factorial(1)))

4 * (3 * (2 * (1* factorial(0))))

4 * (3 * (2 * (1*1))))

4 * (3 * (2 *1))

4 * (3 * 2)

4 * (6)

Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Computing Factorial (11 of 11)
factorial(0) 1;

factorial(n) n*factorial(n 1);
 
factorial(4) 4 * factorial(3)

4 * (3 * factorial(2))

4 * (3 * (2 * factorial(1)))

4 * (3 * (2 * (1* factorial(0))))

4 * (3 * (2 * (1*1))))

4 * (3 * (2 *1))

4 * (3 * 2)

4 * (6)

24

Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Recursive Factorial (1 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Recursive Factorial (2 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Recursive Factorial (3 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Recursive Factorial (4 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Recursive Factorial (5 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Recursive Factorial (6 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Recursive Factorial (7 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Recursive Factorial (8 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Recursive Factorial (9 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Recursive Factorial (10 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Recursive Factorial (11 of 11)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
factorial(4) Stack Trace
Space Required
for factorial(4)
1 Space Required
for factorial(4)
2 Space Required
for factorial(3)
Space Required
for factorial(4)
3
Space Required
for factorial(3)
Space Required
for factorial(2)
Space Required
for factorial(4)
4
Space Required
for factorial(3)
Space Required
for factorial(2)
Space Required
for factorial(1)
Space Required
for factorial(4)
5
Space Required
for factorial(3)
Space Required
for factorial(2)
Space Required
for factorial(1)
Space Required
for factorial(0)
Space Required
for factorial(4)
6
Space Required
for factorial(3)
Space Required
for factorial(2)
Space Required
for factorial(1)
Space Required
for factorial(4)
7
Space Required
for factorial(3)
Space Required
for factorial(2)
Space Required
for factorial(4)
8 Space Required
for factorial(3)
Space Required
for factorial(4)
9
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Other Examples

f(0) 0;
  
f n n
( f(n
) 1);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Fibonacci Numbers (1 of 2)
Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55
89…
indices: 0 1 2 3 4 5 6 7 8 9 10 11

( )
fib 0 0;

fib 1
( ) 1;
fib(index) fib(index 1) fib(index 2); index 2
    
      
     
fib(3) fib 2 fib 1 fib(1) fib 0 fib 1 1 0
fib 1 1
( ) ( ) ( ( )) ( ) ( )
( ) (
fib 1 1 1
) 2
ComputeFibonacci
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Fibonacci Numbers (2 of 2)
return fib(3) + fib(2)
return fib(2) + fib(1)
return fib(1) + fib(0)
return 1
return fib(1) + fib(0)
return 0
return 1 return 1 return 0
1: call fib(3)
2: call fib(2)
3: call fib(1)
4: return fib(1)
7: return fib(2)
5: call fib(0)
6: return fib(0)
8: call fib(1)
9: return fib(1)
10: return fib(3)
11: call fib(2)
16: return fib(2)
12: call fib(1)
13: return fib(1)
14: return fib(0)
15: return fib(0)
fib(4)
0: call fib(4)
17: return fib(4)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem Solving Using Recursion (1 of 2)
In general, to solve a problem using recursion, you break it
into subproblems. If a subproblem resembles the original
problem, you can apply the same approach to solve the
subproblems recursively. A subproblem is almost the same
as the original problem in nature with a smaller size.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Characteristics of Recursion
• All recursive methods have the following characteristics:
– The method is implemented using a conditional
statement that leads to different cases.
– One or more base cases (the simplest case) are used
to stop recursion.
– Every recursive call reduces the original problem,
bringing it increasingly closer to a base case until it
becomes that case.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem Solving Using Recursion (2 of 2)
nPrintln(“Welcome”, n);
1. one is to print the message one time and the other is to print the
message for n-1 times.
2. The second problem is the same as the original problem with a
smaller size.
3. The base case for the problem is n==0. You can solve this problem
using recursion as follows:
public static void nPrintln(String message, int n) {
if (n >= 1) {
System.out.println(message);
nPrintln(message, n - 1);
} // The base case is n < 1
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Think Recursively
Many of the problems presented in the early chapters can be
solved using recursion if you think recursively. For example,
the palindrome problem can be solved recursively as follows:
public static boolean isPalindrome(String s) {
if (s.length() <= 1) // Base case
return true;
else if (s.charAt(0) != s.charAt(s.length() - 1)) // Base case
return false;
else
return isPalindrome(s.substring(1, s.length() - 1));
}
RecursivePalindromeUsingSubstring
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Recursive Helper Methods (1 of 2)
Sometimes you can find a solution by defining a recursive
method to a problem similar to the original problem. This
new method is called a recursive helper method. The
original method can be solved by invoking the recursive
helper method.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Recursive Helper Methods (2 of 2)
The preceding recursive isPalindrome method is not efficient, because it
creates a new string for every recursive call. To avoid creating new strings, use
a helper method:
public static boolean isPalindrome(String s) {
return isPalindrome(s, 0, s.length() - 1);
}
public static boolean isPalindrome(String s, int low, int high) {
if (high <= low) // Base case
return true;
else if (s.charAt(low) != s.charAt(high)) // Base case
return false;
else
return isPalindrome(s, low + 1, high - 1);
}
RecursivePalindrome
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Recursive Selection Sort
1. Find the smallest number in the list and swaps it with
the first number.
2. Ignore the first number and sort the remaining smaller
list recursively.
RecursiveSelectionSort
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Recursive Binary Search
1. Case 1: If the key is less than the middle element,
recursively search the key in the first half of the array.
2. Case 2: If the key is equal to the middle element, the
search ends with a match.
3. Case 3: If the key is greater than the middle element,
recursively search the key in the second half of the
array.
RecursiveBinarySearch
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Recursive Implementation
/** Use binary search to find the key in the list */
public static int recursiveBinarySearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;
return recursiveBinarySearch(list, key, low, high);
}
/** Use binary search to find the key in the list between
list[low] list[high] */
public static int recursiveBinarySearch(int[] list, int key,
int low, int high) {
if (low > high) // The list has been exhausted without a match
return -low - 1;
int mid = (low + high) / 2;
if (key < list[mid])
return recursiveBinarySearch(list, key, low, mid - 1);
else if (key == list[mid])
return mid;
else
return recursiveBinarySearch(list, key, mid + 1, high);
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Directory Size (1 of 2)
The preceding examples can easily be solved without using
recursion. This section presents a problem that is difficult to
solve without using recursion. The problem is to find the size
of a directory. The size of a directory is the sum of the sizes
of all files in the directory. A directory may contain
subdirectories. Suppose a directory contains files , , …, , and
subdirectories , , …, , as shown below.
directory
...
1
f
1
2
f
1
m
f
1
1
d
1
2
d
1
n
d
1
...
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Directory Size (2 of 2)
The size of the directory can be defined recursively as
follows:
1 2 1 2
( ) ( ) ( ) ... ( ) ( ) ( ) ... ( )
m n
size d size f size f size f size d size d size d
       
DirectorySize
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Tower of Hanoi (1 of 2)
• There are n disks labeled 1, 2, 3, …, n, and three towers
labeled A, B, and C.
• No disk can be on top of a smaller disk at any time.
• All the disks are initially placed on tower A.
• Only one disk can be moved at a time, and it must be the
top disk on the tower.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Tower of Hanoi Animation
https://liveexample.pearsoncmg.com/dsanimation/TowerOf
Hanoi.html
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Tower of Hanoi (2 of 2)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Solution to Tower of Hanoi (1 of 2)
The Tower of Hanoi problem can be decomposed into
three subproblems.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Solution to Tower of Hanoi (2 of 2)
• Move the first 
n 1 disks from A to C with the assistance
of tower B.
• Move disk n from A to B.
• Move 
n 1 disks from C to B with the assistance
of tower A.
TowerOfHanoi
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Exercise 18.3 GCD
gcd(2, 3) = 1
gcd(2, 10) = 2
gcd(25, 35) = 5
gcd(205, 301) = 5
gcd(m, n)
Approach 1: Brute-force, start from min(n, m) down to 1, to
check if a number is common divisor for both m and n, if
so, it is the greatest common divisor.
Approach 2: Euclid’s algorithm
Approach 3: Recursive method
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Approach 2: Euclid’s Algorithm
// Get absolute value of m and n;
t1 = Math.abs(m); t2 = Math.abs(n);
// r is the remainder of t1 divided by t2;
r = t1 % t2;
while (r != 0) {
t1 = t2;
t2 = r;
r = t1 % t2;
}
// When r is 0, t2 is the greatest common
// divisor between t1 and t2
return t2;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Approach 3: Recursive Method
gcd(m, n) = n if m % n = 0;
gcd(m, n) = gcd(n, m % n); otherwise;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Fractals
A fractal is a geometrical figure just like triangles, circles,
and rectangles, but fractals can be divided into parts, each
of which is a reduced-size copy of the whole. There are
many interesting examples of fractals. This section
introduces a simple fractal, called Sierpinski triangle,
named after a famous Polish mathematician.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Sierpinski Triangle
1. It begins with an equilateral triangle, which is considered to be the Sierpinski fractal
of order (or level) 0, as shown in Figure (a).
2. Connect the midpoints of the sides of the triangle of order 0 to create a Sierpinski
triangle of order 1, as shown in Figure (b).
3. Leave the center triangle intact. Connect the midpoints of the sides of the three
other triangles to create a Sierpinski of order 2, as shown in Figure (c).
4. You can repeat the same process recursively to create a Sierpinski triangle of order
3, 4, …, and so on, as shown in Figure (d).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Sierpinski Triangle Solution
SierpinskiTriangle
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Recursion versus Iteration
Recursion is an alternative form of program control. It is
essentially repetition without a loop.
Recursion bears substantial overhead. Each time the
program calls a method, the system must assign space for
all of the method’s local variables and parameters. This
can consume considerable memory and requires extra
time to manage the additional space.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Advantages of Using Recursion
Recursion is good for solving the problems that are
inherently recursive.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Tail Recursion
A recursive method is said to be tail recursive if there are
no pending operations to be performed on return from a
recursive call.
Non-tail recursive
Tail recursive
ComputeFactorial
ComputeFactorialTailRecursion
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 20
Lists, Stacks, Queues, and
Priority Queues
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (1 of 2)
20.1 To explore the relationship between interfaces and classes in the Java
Collections Framework hierarchy (§20.2).
20.2 To use the common methods defined in the Collection interface for
operating collections (§20.2).
20.3 To use the Iterator interface to traverse the elements in a collection
(§20.3).
20.4 To use a foreach loop to traverse the elements in a collection (§20.3).
20.5 To use a forEach method to perform an action on each element in a
collection (§20.4).
20.6 To explore how and when to use ArrayList or LinkedList to store a list
of elements (§20.5).
20.7 To compare elements using the Comparable interface and the
Comparator interface (§20.6).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (2 of 2)
20.8 To use the static utility methods in the Collections class for
sorting, searching, shuffling lists, and finding the largest and smallest
element in collections (§20.7).
20.9 To develop a multiple bouncing balls application using ArrayList
(§20.8).
20.10 To distinguish between Vector and ArrayList and to use the
Stack class for creating stacks (§20.9).
20.11 To explore the relationships among Collection, Queue,
LinkedList, and PriorityQueue and to create priority queues using the
PriorityQueue class (§20.10).
20.12 To use stacks to write a program to evaluate expressions
(§20.11).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
What Is Data Structure?
A data structure is a collection of data organized in some
fashion. The structure not only stores data, but also
supports operations for accessing and manipulating the
data.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Java Collection Framework hierarchy (1 of 2)
A collection is a container object that holds a group of
objects, often referred to as elements. The Java
Collections Framework supports two types of collections:
• One, for storing a collection , is simply called collection.
• The other, for storing key/value pairs, is called a map.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Java Collection Framework hierarchy (2 of 2)
Set and List are subinterfaces of Collection.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Collection Interface
UML Diagram
TestCollection
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Iterators
Iterator is a classic design pattern for walking through a
data structure without having to expose the details of how
data is stored in the data structure.
TestIterator
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Using the forEach Method
Java 8 added a new forEach method in the Iterable
interface. It functions like a foreach loop.
TestForEach
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The List Interface (1 of 2)
A list stores elements in a sequential order, and allows the
user to specify where the element is stored. The user can
access the elements by index.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The List Interface (2 of 2)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The List Iterator
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
ArrayList and LinkedList
The ArrayList class and the LinkedList class are concrete
implementations of the List interface. Which of the two
classes you use depends on your specific needs. If you
need to support random access through an index without
inserting or removing elements from any place other than
the end, ArrayList offers the most efficient collection. If,
however, your application requires the insertion or deletion
of elements from the beginning of the list, you should
choose LinkedList. A list can grow or shrink dynamically.
An array is fixed once it is created. If your application does
not require insertion or deletion of elements, the most
efficient data structure is the array.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
java.util.ArrayList
«interface»
java.util.List<E>
Creates an empty list with the default initial capacity.
Creates an array list from an existing collection.
Creates an empty list with the specified initial
capacity.
Trims the capacity of this ArrayList instance to be the
list's current size.
+ArrayList()
+ArrayList(c:Collection<?extendsE>)
+ArrayList(initialCapacity: int)
+trimToSize(): void
«interface»
java.util.Collection<E>
java.util.ArrayList<E>
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
java.util.LinkedList
«interface»
java.util.List<E>
Creates a default empty linked list.
Creates a linked list from an existing collection.
Adds the object to the head of this list.
Adds the object to the tail of this list.
Returns the first element from this list.
Returns the last element from this list.
Returns and removes the first element from this
list.
Returns and removes the last element from this
list.
+LinkedList()
+LinkedList(c: Collection<? extends
E>)
+addFirst(o: E): void
+addLast(o: E): void
+getFirst(): E
+getLast(): E
+removeFirst(): E
+removeLast(): E
«interface»
java.util.Collection<E>
java.util.LinkedList<E>
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example: Using ArrayList and LinkedList
This example creates an array list filled with numbers, and
inserts new elements into the specified location in the list.
The example also creates a linked list from the array list,
inserts and removes the elements from the list. Finally, the
example traverses the list forward and backward.
TestArrayAndLinkedList
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Comparator Interface
You have learned to compare objects using the
Comparable interface. What happens if the objects are not
instances of Comparable. You can define a comparator to
compare these elements.
The Comparator interface has the compare method for
comparing two objects.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Comparator<T> Interface
public int compare(T element1, T element2)
Returns a negative value if element1 is less than element2,
a positive value if element1 is greater than element2, and
zero if they are equal.
GeometricObjectComparator
TestCollection
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Using Lambda Expression in Comparator
Comparator is a functional interface. It has just a single
method, compare. We can use lambda expression to
simplify coding.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Other Comparator Examples
SortStringByLength
SortStringIgnoreCase
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Method Reference
String::compareToIgnoreCase
is known as method reference, which is equivalent to the
lambda expression:
(s1, s2) -> s1.compareToIgnoreCase(s2)
The compiler automatically translates a method reference
to an equivalent lambda expression.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The comparing Method
You can use the static comparing method in the
Comparator interface to create a comparator.
For example, the following code sorts a list of loans based
on their loan amount property.
Loan[] list = {new Loan(5.5, 10, 2323), new Loan(5, 10,
1000)};
Arrays.sort(list,
Comparator.comparing(Loan::getLoanAmount));
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Add Additional Sort Criteria
You can sort using a primary criteria, second, third, and so
on using the Comparator’s default thenComparing
method.
Loan[] list = {new Loan(5.5, 10, 100), new Loan(5, 10,
1000)};
Arrays.sort(list,
Comparator.comparing(Loan::getLoanAmount)
.thenComparing(Loan::getAnnualInterestRate));
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Collections Class
The Collections class contains various static methods for
performing common operations in a collection and a list.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Collections Class UML Diagram
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Multiple Bouncing Balls
MultipleBounceBall
javafx.application.Application
-char token
+getToken
+setToken
+paintComponet
+mouseClicked
MultipleBallPane
-animation: Timeline
+MultipleBallPane()
+play(): void
+pause(): void
+increaseSpeed(): void
+decreaseSpeed(): void
+rateProperty(): DoubleProperty
+moveBall(): void
javafx.scene.layout.Pane
1
1
Ball
dx: double
dy: double
+Ball(x: double, y: double,
radius: double, color: Color)
javafx.scene.shape.Circle
1
m
MultipleBounceBall
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Vector and Stack Classes
The Java Collections Framework was introduced with Java
2. Several data structures were supported prior to Java 2.
Among them are the Vector class and the Stack class.
These classes were redesigned to fit into the Java
Collections Framework, but their old-style methods are
retained for compatibility. This section introduces the
Vector class and the Stack class.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Vector Class (1 of 2)
The Vector class is replaced by the ArrayList.
Vector contains the synchronized methods for accessing
and modifying the vector. It is not efficient for most of the
applications.
You may encounter Vector in the legacy Java code.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Vector Class (2 of 2)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Stack Class
The Stack class represents a last-in-first-out stack of
objects. The elements are accessed only from the top of
the stack. You can retrieve, insert, or remove an element
from the top of the stack.
java.util.Stack<E>
+Stack()
+empty(): boolean
+peek(): E
+pop(): E
+push(o: E) : E
+search(o: Object) : int
java.util.Vector<E>
Creates an empty stack.
Returns true if this stack is empty.
Returns the top element in this stack.
Returns and removes the top element in this stack.
Adds a new element to the top of this stack.
Returns the position of the specified element in this
stack.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Queues and Priority Queues
A queue is a first-in/first-out data structure. Elements are
appended to the end of the queue and are removed from
the beginning of the queue. In a priority queue, elements
are assigned priorities. When accessing elements, the
element with the highest priority is removed first.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Queue Interface
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Using LinkedList for Queue
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The PriorityQueue Class
PriorityQueueDemo
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Evaluating Expressions
Stacks can be used to evaluate expressions.
Evaluate Expression
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Algorithm
Phase 1: Scanning the expression
The program scans the expression from left to right to extract operands,
operators, and the parentheses.
1.1. If the extracted item is an operand, push it to operandStack.
1.2. If the extracted item is a + or - operator, process all the operators at the top
of operatorStack and push the extracted operator to operatorStack.
1.3. If the extracted item is a * or / operator, process the * or / operators at the
top of operatorStack and push the extracted operator to operatorStack.
1.4. If the extracted item is a ( symbol, push it to operatorStack.
1.5. If the extracted item is a ) symbol, repeatedly process the operators from
the top of operatorStack until seeing the ( symbol on the stack.
Phase 2: Clearing the stack
Repeatedly process the operators from the top of operatorStack until
operatorStack is empty.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and Data
Structures
Thirteenth Edition
Chapter 23
Sorting
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives
23.1 To study and analyze time complexity of various sorting
algorithms (§§23.2–23.7).
23.2 To design, implement, and analyze insertion sort (§23.2).
23.3 To design, implement, and analyze bubble sort (§23.3).
23.4 To design, implement, and analyze merge sort (§23.4).
23.5 To design, implement, and analyze quick sort (§23.5).
23.6 To design and implement a binary heap (§23.6).
23.7 To design, implement, and analyze heap sort (§23.7).
23.8 To design, implement, and analyze bucket sort and radix sort
(§23.8).
23.9 To design, implement, and analyze external sort for files that
have a large amount of data (§23.9).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Why Study Sorting?
• Sorting is a classic subject in computer science. There
are three reasons for studying sorting algorithms.
– First, sorting algorithms illustrate many creative
approaches to problem solving and these
approaches can be applied to solve other problems.
– Second, sorting algorithms are good for practicing
fundamental programming techniques using
selection statements, loops, methods, and arrays.
– Third, sorting algorithms are excellent examples to
demonstrate algorithm performance.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
What Data to Sort?
The data to be sorted might be integers, doubles, characters, or objects.
§7.8, “Sorting Arrays,” presented selection sort and insertion sort for
numeric values. The selection sort algorithm was extended to sort an
array of objects in §11.5.7, “Example: Sorting an Array of Objects.” The
Java API contains several overloaded sort methods for sorting primitive
type values and objects in the java.util.Arrays and java.util.Collections
class. For simplicity, this section assumes:
• data to be sorted are integers,
• data are sorted in ascending order, and
• data are stored in an array. The programs can be easily modified to
sort other types of data, to sort in descending order, or to sort data in
an ArrayList or a LinkedList.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Insertion Sort (1 of 2)
The insertion sort
algorithm sorts a list
of values by
repeatedly inserting
an unsorted
element into a
sorted sublist until
the whole list is
sorted.
int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted
2 9 5 4 8 1 6
Step 1: Initially, the sorted sublist contains the
first element in the list. Insert 9 into the sublist.
2 9 5 4 8 1 6
Step2: The sorted sublist is {2, 9}. Insert 5 into
the sublist.
2 5 9 4 8 1 6
Step 3: The sorted sublist is {2, 5, 9}. Insert 4
into the sublist.
2 4 5 9 8 1 6
Step 4: The sorted sublist is {2, 4, 5, 9}. Insert 8
into the sublist.
2 4 5 8 9 1 6
Step 5: The sorted sublist is {2, 4, 5, 8, 9}. Insert
1 into the sublist.
1 2 4 5 8 9 6
Step 6: The sorted sublist is {1, 2, 4, 5, 8, 9}.
Insert 6 into the sublist.
1 2 4 5 6 8 9
Step 7: The entire list is now sorted.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Insertion Sort Animation
https://liveexample.pearsoncmg.com/dsanimation/Insertion
SortNeweBook.html
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Insertion Sort (2 of 2)
int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
How to Insert?
The insertion sort algorithm sorts a list of values by
repeatedly inserting an unsorted element into a sorted
sublist until the whole list is sorted.
[0] [1] [2] [3] [4] [5] [6]
2 5 9 4
list Step 1: Save 4 to a temporary variable currentElement
[0] [1] [2] [3] [4] [5] [6]
2 5 9
list Step 2: Move list[2] to list[3]
[0] [1] [2] [3] [4] [5] [6]
2 5 9
list Step 3: Move list[1] to list[2]
[0] [1] [2] [3] [4] [5] [6]
2 4 5 9
list Step 4: Assign currentElement to list[1]
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
From Idea to Solution (1 of 2)
for (int i = 1; i < list.length; i++) {
insert list[i] into a sorted sublist list[0..i-1]
so that
list[0..i] is sorted
}
list[0]
list[0] list[1]
list[0] list[1] list[2]
list[0] list[1] list[2] list[3]
list[0] list[1] list[2] list[3] …
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
From Idea to Solution (2 of 2)
InsertionSort
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Bubble Sort
2 5 9 4 8 1
2 5 4 9 8 1
2 5 4 8 9 1
2 5 4 8 1 9
(a) 1st pass
2 4 5 8 1 9
2 4 5 8 1 9
2 4 5 1 8 9
(b) 2nd pass
2 4 5 1 8 9
2 4 1 5 8 9
(c) 3rd pass
2 1 4 5 8 9
(d) 4th pass
2 9 5 4 8 1
(e) 5th pass
2 5 4 8 1 9 2 4 5 1 8 9 2 4 1 5 8 9 1 2 4 5 8 9
Bubble sort time:  
2
O n
   
2
1 2 2 1
2 2
n n
n n
       
BubbleSort
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Bubble Sort Animation
https://liveexample.pearsoncmg.com/dsanimation/BubbleS
ortNeweBook.html
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Merge Sort (1 of 2)
2 9 5 4 8 1 6 7
2 9 5 4 8 1 6 7
split
2 9
split
5 4
2
split
9 5 4
8 1 6 7
8 1 6 7
2 9
merge
4 5 1 8 6 7
2 4 5 9 1 6 7 8
1 2 4 5 6 7 8 9
merge
merge
divide
conquer
MergeSort
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Merge Sort (2 of 2)
mergeSort(list):
firstHalf = mergeSort(firstHalf);
secondHalf = mergeSort(secondHalf);
list = merge(firstHalf, secondHalf);
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Merge Two Sorted Lists
2 4 5 9
current1
1
1 6 7 8
current2
current3
(a) After moving 1 to temp (b) After moving all the
elements in list2 to temp
to temp
2 4 5 9
current1
1 2 4 5 6 7 8 9
1 6 7 8
current2
current3
(c) After moving 9 to
temp
2 4 5 9
current1
1 2 4 5 6 7 8
1 6 7 8
current2
current3
Animation for Merging Two Sorted Lists
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Merge Sort Time (1 of 2)
Let )
(
T n denote the time required for sorting an array of n
elements using merge sort. Without loss of generality,
assume n is a power of 2. The merge sort algorithm splits the
array into two subarrays, sorts the subarrays using the same
algorithm recursively, and then merges the subarrays. So,
 
2 2
n n
T n T T mergetime
   
  
   
   
 
( )
2 2
n n
T n T T O n
   
  
   
   
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Merge Sort Time (2 of 2)
The first 2
( )
/
T n is the time for sorting the first half of the array and the
second 2
( )
/
T n is the time for sorting the second half. To merge two
subarrays, it takes at most 1
n  comparisons to compare the elements
from the two subarrays and n moves to move elements to the temporary
array. So, the total time is 2 1.
n  Therefore,
 
2
2
1
log log 1
log
log
( ) 2 2 1 2 2 2 1 2 1 2 2 2 2 1
2 4 2 2
2 2 2 ... 2 2 2 1
2
2 2 2 ... 2 2 2 1
2
2 log 2 1 2 log 1 log
k k
k
n n
n
n
n n n n
T n T n T n T n n
n
T n n n
n
T n n n
n n n n n O n n


 
     
            
     
 
     
 
 
       
 
 
 
       
 
 
      
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Quick Sort (1 of 2)
Quick sort, developed by C. A. R. Hoare (1962), works as
follows: The algorithm selects an element, called the pivot,
in the array. Divide the array into two parts such that all the
elements in the first part are less than or equal to the pivot
and all the elements in the second part are greater than the
pivot. Recursively apply the quick sort algorithm to the first
part and then the second part.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Quick Sort (2 of 2)
5 2 9 3 8 4 0 1 6 7
pivot
(a) The original array
4 2 1 3 0 5 8 9 6 7
pivot
(b)The original array is partitioned
0 2 1 3 4
(c) The partial array (4 2 1 3 0) is
partitioned
0 2 1 3 (d) The partial array (0 2 1 3) is
partitioned
1 2 3
pivot
pivot
pivot
(e) The partial array (2 1 3) is
partitioned
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Partition
5 2 9 3 8 4 0 1 6 7
pivot low high
(a) Initialize pivot, low, and high
5 2 9 3 8 4 0 1 6 7
pivot low high
(b) Search forward and backward
5 2 1 3 8 4 0 9 6 7
pivot low high
(c) 9 is swapped with 1
5 2 1 3 8 4 0 9 6 7
pivot low high
(d) Continue search
5 2 1 3 0 4 8 9 6 7
pivot low high
(e) 8 is swapped with 0
5 2 1 3 0 4 8 9 6 7
pivot low high
(f) when high < low, search is over
4 2 1 3 0 5 8 9 6 7
pivot
(g) pivot is in the right place
The index of the pivot is returned
Animation for partition QuickSort
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Quick Sort Time
To partition an array of n elements, it takes 1
n  comparisons
and n moves in the worst case. So, the time required for
partition is ( ).
O n
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Worst-Case Time
In the worst case, each time the pivot divides the array into
one big subarray with the other empty. The size of the big
subarray is one less than the one before divided. The
algorithm requires 2
( )
O n time:
     
2
1 2 2 1
n n O n
      
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Best-Case Time
In the best case, each time the pivot divides the array into
two parts of about the same size. Let  
T n denote the time
required for sorting an array of elements using quick sort.
So,
   
   
   
   
   
log
2 2
n n
T n T T n O n n
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Average-Case Time
On the average, each time the pivot will not divide the array
into two parts of the same size nor one empty part.
Statistically, the sizes of the two parts are very close. So the
average time is  
log .
O n n The exact average-case analysis
is beyond the scope of this book.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Heap
Heap is a useful data structure for designing efficient
sorting algorithms and priority queues. A heap is a binary
tree with the following properties:
• It is a complete binary tree.
• Each node is greater than or equal to any of its children.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Complete Binary Tree
A binary tree is complete if every level of the tree is full except
that the last level may not be full and all the leaves on the last
level are placed left-most. For example, in the following figure,
the binary trees in (a) and (b) are complete, but the binary trees
in (c) and (d) are not complete. Further, the binary tree in (a) is a
heap, but the binary tree in (b) is not a heap, because the root
(39) is less than its right child (42).
22 29 14 33
32 39
42
22 29 14
32 42
39
22 14 33
32 39
42
22 29
32
42
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
See How a Heap Works
https://liveexample.pearsoncmg.com/dsanimation/HeapeBo
ok.html
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Representing a Heap
For a node at position i, its left child is at position 2i+1 and
its right child is at position 2i+2, and its parent is at index
 
1 / 2.
i  For example, the node for element 39 is at position
4, so its left child (element 14) is at 9 (2*4+1), its right child
(element 33) is at 10 (2*4+2), and its parent (element 42) is
at 1  
 
4 1 / 2 .

22 29 14 33 30 17 9
32 39 44 13
42 59
62
62 42 59 32 39 44 13 22 29 14 33 30 17 9
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10][11][12][13]
[10][11]
parent left
right
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Adding Elements to the Heap
Adding 3, 5, 1, 19, 11, and 22 to a heap, initially empty
3
(a) After adding 3 (b) After adding 5 (c) After adding 1
(d) After adding 19
3
19
5 1
(e) After adding 11
3 5
19
11 1
(f) After adding 22
3 5 1
22
11 19
5
3
5
3 1
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Rebuild the Heap After Adding a New Node
Adding 88 to the heap
(a) Add 88 to a heap
3 5 1 88
22
11 19
(b) After swapping 88 with 19
3 5 1 19
22
11 88
(b) After swapping 88 with 22
3 5 1 19
88
11 22
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Removing the Root and Rebuild the
Tree (1 of 5)
Removing root 62 from the heap
22 29 14 33 30 17 9
32 39 44 13
42 59
62
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Removing the Root and Rebuild the
Tree (2 of 5)
Move 9 to root
22 29 14 33 30 17
32 39 44 13
42 59
9
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Removing the Root and Rebuild the
Tree (3 of 5)
Swap 9 with 59
22 29 14 33 30 17
32 39 44 13
42 9
59
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Removing the Root and Rebuild the
Tree (4 of 5)
Swap 9 with 44
22 29 14 33 30 17
32 39 9 13
42 44
59
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Removing the Root and Rebuild the
Tree (5 of 5)
Swap 9 with 30
22 29 14 33 9 17
32 39 30 13
42 44
59
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Heap Class
Heap
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Heap Sort
HeapSort
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Heap Sort Time
Let h denote the height for a heap of n elements. Since a
heap is a complete binary tree, the first level has 1 node, the
second level has 2 nodes, the kth level has  
1
2
k 
nodes, the
 
 h
1 t
h level has  
2
2
h
nodes, and the hth level has at least
one node and at most  
1
2
h
nodes. Therefore,
2 2 1
1 2 2 1 2 ... 2 2
h h h
n
  
        
1
2 1 2 1
h h
n

    1
2 1 2
h h
n

    
1
log2 log 1 log2
h h
n

  
 
1 log 1
h n h
       
log 1 log 1 1
n h n
    
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Bucket Sort and Radix Sort
All sort algorithms discussed so far are general sorting
algorithms that work for any types of keys (e.g., integers,
strings, and any comparable objects). These algorithms sort
the elements by comparing their keys. The lower bound for
general sorting algorithms is  
log .
O n n So, no sorting
algorithms based on comparisons can perform better than
 
log .
O n n However, if the keys are small integers, you can
use bucket sort without having to compare the keys.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Bucket Sort
The bucket sort algorithm works as follows. Assume the
keys are in the range from 0 to N 1.
 We need N buckets
labeled 0, 1, , and N 1 .
 If an element’s key is i, the element
is put into the bucket i. Each bucket holds the elements with
the same key value. You can use an ArrayList to implement
a bucket.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Radix Sort
Sort 331, 454, 230, 34, 343, 45, 59, 453, 345, 231, 9
230, 331, 231, 343, 453, 454, 34, 45, 345, 59, 9
9, 230, 331, 231, 34, 343, 45, 345, 453, 454, 59
9, 34, 45, 59, 230, 231, 331, 343, 345, 453, 454
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Radix Sort Animation
https://liveexample.pearsoncmg.com/dsanimation/RadixSorteBook.html
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
External Sort
All the sort algorithms discussed in the preceding sections assume that
all data to be sorted is available at one time in internal memory such as
an array. To sort data stored in an external file, you may first bring data
to the memory, then sort it internally. However, if the file is too large, all
data in the file cannot be brought to memory at one time.
Program
Array
……
Original file
Temporary file
S1 S2 Sk
CreateLargeFile
SortLargeFile
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Phase One
I
Repeatedly bring data from the file to an array, sort the
array using an internal sorting algorithm, and output the
data from the array to a temporary file.
Program
Array
……
Original file
Temporary file
S1 S2 Sk
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Phase Two
II
Merge a pair of sorted segments (e.g., S1 with S2, S3 with S4, ,
and so on) into a larger sorted segment and save the new segment
into a new temporary file. Continue the same process until one
sorted segment results.
S1 S2 S3 S4 S5 S6 S7 S8
Sk
S1, S2 merged S3, S4 merged S5, S6 merged S7, S8 merged
S1, S2, S3, S4 merged S5, S6 , S7, S8 merged
S1, S2, S3, S4 , S5, S6 , S7, S8 merged
Merge
Merge
Merge
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Implementing Phase Two (1 of 2)
II
Each merge step merges two sorted segments to form a
new segment. The new segment doubles the number
elements. So the number of segments is reduced by half
after each merge step. A segment is too large to be
brought to an array in memory. To implement a merge
step, copy half number of segments from file f1.dat to a
temporary file f2.dat. Then merge the first remaining
segment in f1.dat with the first segment in f2.dat into a
temporary file named f3.dat.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Implementing Phase Two (2 of 2)
II
S1 S2 S3 S4 S5 S6 S7 S8
Sk
S1, S5 merged S2, S6 merged S3, S7 merged S4, S8 merged
f1.dat
S1 S2 S3 S4 f2.dat
Copy to f2.dat
f3.dat
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and Data
Structures
Thirteenth Edition
Chapter 24
Implementing Lists,
Stacks, Queues, and
Priority Queues
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives
24.1 To design common operations of lists in an interface and make the interface
a subtype of Collection (§24.2).
24.2 To design and implement an array list using an array (§24.3).
24.3 To create a linked list using a linked structure (§24.4).
24.4 To design MyLinkedList class (§24.5).
24.5 To implement MyLinkedList class (§24.6).
24.6 To compare the performance between MyArrayList and MyLinkedList
(§24.7).
24.7 To explore variations of linked lists (§24.8).
24.8 To design and implement a stack class using an array list and a queue class
using a linked list (§24.9).
24.9 To design and implement a priority queue using a heap (§24.10).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Lists
A list is a popular data structure to store data in sequential
order. For example, a list of students, a list of available rooms,
a list of cities, and a list of books, etc. can be stored using lists.
The common operations on a list are usually the following:
• Retrieve an element from this list.
• Insert a new element to this list.
• Delete an element from this list.
• Find how many elements are in this list.
• Find if an element is in this list.
• Find if this list is empty.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Two Ways to Implement Lists
There are two ways to implement a list.
Using arrays. One is to use an array to store the elements.
The array is dynamically created. If the capacity of the
array is exceeded, create a new larger array and copy all
the elements from the current array to the new array.
Using linked list. The other approach is to use a linked
structure. A linked structure consists of nodes. Each node
is dynamically created to hold an element. All the nodes
are linked together to form a list.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Design of ArrayList and LinkedList
For convenience, let’s name these two classes: MyArrayList and
MyLinkedList. These two classes have common operations, but
different data fields. The common operations can be generalized in an
interface or an abstract class. Prior to Java 8, a popular design strategy
is to define common operations in an interface and provide an abstract
class for partially implementing the interface. So, the concrete class
can simply extend the abstract class without implementing the full
interface. Java 8 enables you to define default methods. You can
provide default implementation for some of the methods in the interface
rather than in an abstract class.
MyList
MyArrayList
MyLinkedList
java.util.Collection
java.util.Iterable
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
MyList Interface
«interface»
MyList<E>
+add(index: int, e: E) : void
+get(index: int) : E
+indexOf(e: Object) : int
+lastIndexOf(e: E) : int
+remove(index: int) : E
+set(index: int, e: E) : E
Override the add, isEmpty, remove,
containsAll, addAll, removeAll, retainAll,
toArray(), and toArray(T[]) methods
defined in Collection using default
methods.
Inserts a new element at the specified index in this list.
Returns the element from this list at the specified index.
Returns the index of the first matching element in this list.
Returns the index of the last matching element in this list.
Removes the element at the specified index and returns the removed element.
Sets the element at the specified index and returns the element being replaced.
«interface»
java.util.Collection<E>
MyList
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Array Lists
Array is a fixed-size data structure. Once an array is created, its
size cannot be changed. Nevertheless, you can still use array to
implement dynamic data structures. The trick is to create a new
larger array to replace the current array if the current array
cannot hold new elements in the list.
Initially, an array, say data of Object[] type, is created with a
default size. When inserting a new element into the array, first
ensure there is enough room in the array. If not, create a new
array with the size as twice as the current one. Copy the
elements from the current array to the new array. The new array
now becomes the current array.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Array List Animation
https://liveexample.pearsoncmg.com/dsanimation/ArrayList
eBook.html
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Insertion
Before inserting a new element at a specified index, shift
all the elements after the index to the right and increase
the list size by 1.
e0
0 1 … i i+1 k-1
Before inserting
e at insertion point i
e1 … ei ei+1
…
… ek-1
data.length -1
Insertion point
e
e0
0 1 … i i+1
After inserting
e at insertion point i,
list size is
incremented by 1
e1 … e ei
…
… ek-1
data.length -1
e inserted here
ek
ek
k
ei-1
ei-1
k+1
k
ei+1
i+2
…shift…
Add Method Animation
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Deletion
To remove an element at a specified index, shift all the
elements after the index to the left by one position and
decrease the list size by 1.
e0
0 1 … i i+1 k-1
Before deleting the
element at index i
e1 … ei ei+1
…
… ek-1
data.length -1
Delete this element
e0
0 1 … i
After deleting the
element, list size is
decremented by 1
e1 …
…
… ek
data.length -1
ek
k
ei-1
ei-1
k-1
ei+1
k-2
ek-1
…shift…
Remove Method Animation
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Implementing MyArrayList
MyArrayList<E>
-data: E[]
-size: int
+MyArrayList()
+MyArrayList(objects: E[])
+trimToSize(): void
-ensureCapacity(): void
-checkIndex(index: int): void
«interface»
MyList<E>
Creates a default array list.
Creates an array list from an array of objects.
Trims the capacity of this array list to the list’s current
size.
Doubles the current array size if needed.
Throws an exception if the index is out of bounds in
the list.
Array for storing elements in this array list.
The number of elements in the array list.
MyArrayList TestMyArrayList
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Linked Lists
Since MyArrayList is implemented using an array, the
methods get(int index) and set(int index, Object o) for
accessing and modifying an element through an index and
the add(Object o) for adding an element at the end of the
list are efficient. However, the methods add(int index,
Object o) and remove(int index) are inefficient because it
requires shifting potentially a large number of elements.
You can use a linked structure to implement a list to
improve efficiency for adding and removing an element
anywhere in a list.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Linked List Animation
https://liveexample.pearsoncmg.com/dsanimation/LinkedLi
steBook.html
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Nodes in Linked Lists
A linked list consists of nodes. Each node contains an element, and each
node is linked to its next neighbor. Thus a node can be defined as a
class, as follows:
element
head
next
Node 1
element
next
Node 2
…
element
null
Node n
tail
class Node<E> {
E element;
Node<E> next;
public Node(E o) {
element = o;
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Adding Three Nodes (1 of 4)
The variable head refers to the first node in the list, and
the variable tail refers to the last node in the list. If the list
is empty, both are null. For example, you can create three
nodes to store three strings in a list, as follows:
Step 1: Declare head and tail:
The list is empty now
Node<String> head = null;
Node<String> tail = null;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Adding Three Nodes (2 of 4)
Step 2: Create the first node and insert it to the list:
head "Chicago"
next: null
tail
After the first node is inserted
inserted
head = new Node<>("Chicago");
tail = head;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Adding Three Nodes (3 of 4)
Step 3: Create the second node and insert it to the list:
tail.next = new Node<>("Denver");
head "Chicago"
next
"Denver"
next: null
tail
tail = tail.next; head "Chicago"
next
"Denver"
next: null
tail
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Adding Three Nodes (4 of 4)
Step 4: Create the third node and insert it to the list:
head "Chicago"
next
"Dallas"
next: null
tail
"Denver"
next
tail.next =
new Node<>("Dallas");
head "Chicago"
next
"Dallas"
next: null
tail
"Denver"
next
tail = tail.next;
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Traversing All Elements in the List
Each node contains the element and a data field named next
that points to the next node. If the node is the last in the list, its
pointer data field next contains the value null. You can use this
property to detect the last node. For example, you may write the
following loop to traverse all the nodes in the list.
Node<E> current = head;
while (current != null) {
System.out.println(current.element);
current = current.next;
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
MyLinkedList
MyLinkedList<E>
-head: Node<E>
-tail: Node<E>
-size: int
+MyLinkedList()
+MyLinkedList(elements: E[])
+addFirst(e: E): void
+addLast(e: E): void
+getFirst(): E
+getLast(): E
+removeFirst(): E
+removeLast(): E
1
m
Node<E>
element: E
next: Node<E>
Link
1
«interface»
MyList<E>
Creates a default linked list.
Creates a linked list from an array of elements.
Adds an element to the head of the list.
Adds an element to the tail of the list.
Returns the first element in the list.
Returns the last element in the list.
Removes the first element from the list.
Removes the last element from the list.
The head of the list.
The tail of the list.
The number of elements in the list.
MyLinkedList TestMyLinkedList
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Implementing addFirst(E e)
public void addFirst(E e) {
Node<E> newNode = new
Node<>(e);
newNode.next = head;
head = newNode;
size++;
if (tail == null)
tail = head;
}
addFirst Animation
head
e0
next
…
A new node
to be inserted
here
ei
next
ei+1
next
tail
… ek
null
e
next
New node inserted here
(a) Before a new node is inserted.
(b) After a new node is inserted.
e0
next
… ei
next
ei+1
next
tail
… ek
null
e
next
head
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Implementing addLast(E e)
public void addLast(E e) {
if (tail == null) {
head = tail = new Node<>(e);
}
else {
tail.next = new Node<>(e);
tail = tail.next;
}
size++;
}
addLast Animation
head
e0
next
… ei
next
ei+1
next
tail
… ek
null
e
null
New node inserted here
(a) Before a new node is inserted.
(b) After a new node is inserted.
head
e0
next
… ei
next
ei+1
next
tail
… ek
next
A new node
to be inserted
here
e
null
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Implementing add(int index, E e)
public void add(int index, E e) {
if (index == 0) addFirst(e);
else if (index >= size) addLast(e);
else {
Node<E> current = head;
for (int i = 1; i < index; i++)
current = current.next;
Node<E> temp = current.next;
current.next = new Node<>(e);
(current.next).next = temp;
size++;
}
}
Add(index, e) Animation
current
head
e0
next
…
A new node
to be inserted
here
ei
next
temp
ei+1
next
tail
… ek
null
e
null
(a) Before a new node is inserted.
current
head
e0
next
…
A new node
is inserted in
the list
ei
next
temp
ei+1
next
tail
… ek
null
e
next
(b) After a new node is inserted.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Implementing removeFirst()
public E removeFirst() {
if (size == 0) return null;
else {
Node<E> temp = head;
head = head.next;
size--;
if (head == null) tail = null;
return temp.element;
}
}
removeFirst Animation
head
e0
next
…
Delete this node
ei
next
ei+1
next
tail
… ek
null
(a) Before the node is deleted.
(b) After the first node is deleted
e1
next
… ei
next
ei+1
next
tail
… ek
null
e1
next
head
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Implementing removeLast()
public E removeLast() {
if (size == 0) return null;
else if (size == 1)
{
Node<E> temp = head;
head = tail = null;
size = 0;
return temp.element;
}
else
{
Node<E> current = head;
for (int i = 0; i < size - 2; i++)
current = current.next;
Node temp = tail;
tail = current;
tail.next = null;
size--;
return temp.element;
}
}
addLast Animation
head
e0
next
…
Delete this node
ek-2
next
ek-1
next
tail
ek
null
(a) Before the node is deleted.
(b) After the last node is deleted
e1
next
current
head
e0
next
… ek-2
next
ek-1
null
e1
next
tail
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Implementing remove(int index)
public E remove(int index) {
if (index < 0 || index >= size) return null;
else if (index == 0) return removeFirst();
else if (index == size - 1) return
removeLast();
else {
Node<E> previous = head;
for (int i = 1; i < index; i++) {
previous = previous.next;
}
Node<E> current = previous.next;
previous.next = current.next;
size--;
return current.element;
}
}
remove Animation
previous
head
element
next
…
Node to be deleted
element
next
element
next
tail
… element
null
element
next
(a) Before the node is deleted.
current
previous
head
element
next
… element
next
element
next
tail
… element
null
(b) After the node is deleted.
current.next
current.next
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Time Complexity for ArrayList and
LinkedList
Methods MyArrayList/ArrayList MyLinkedList/LinkedList
add(e: E) O of 1 O of 1
add(index: int, e: E) O of n O of n
clear() O of 1 O of 1
contains(e: E) O of n O of n
get(index: int) O of 1 O of n
indexOf(e: E) O of n O of n
isEmpty() O of 1 O of 1
lastIndexOf(e: E) O of n O of n
remove(e: E) O of n O of n
size() O of 1 O of 1
remove(index: int) O of n O of n
set(index: int, e: E) O of n O of n
addFirst(e: E) O of n O of 1
removeFirst() O of n O of 1
 
1
O  
1
O
 
O n  
O n
 
1
O  
1
O
 
O n  
O n
 
1
O  
O n
 
O n  
O n
 
1
O  
1
O
 
O n  
O n
 
O n  
O n
 
1
O  
1
O
 
O n  
O n
 
O n  
O n
 
O n  
1
O
 
O n  
1
O
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Circular Linked Lists
A circular, singly linked list is like a singly linked list,
except that the pointer of the last node points back to the
first node.
element
head
next
Node 1
element
next
Node 2
…
element
next
Node n
tail
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Doubly Linked Lists
A doubly linked list contains the nodes with two pointers.
One points to the next node and the other points to the
previous node. These two pointers are conveniently called
a forward pointer and a backward pointer. So, a doubly
linked list can be traversed forward and backward.
element
head
next
Node 1
element
next
Node 2
…
element
null
Node n
tail
null previous previous
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Circular Doubly Linked Lists
A circular, doubly linked list is doubly linked list, except
that the forward pointer of the last node points to the first
node and the backward pointer of the first pointer points to
the last node.
element
head
next
Node 1
element
next
Node 2
…
element
next
Node n
tail
previous previous previous
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Stacks
A stack can be viewed as a special type of list, where the
elements are accessed, inserted, and deleted only from the
end, called the top, of the stack.
Data1
Data2
Data1 Data1
Data2
Data3
Data1 Data2 Data3
Data1
Data2
Data3
Data1
Data2 Data1
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Queues
A queue represents a waiting list. A queue can be viewed
as a special type of list, where the elements are inserted
into the end (tail) of the queue, and are accessed and
deleted from the beginning (head) of the queue.
Data1
Data2
Data1 Data1
Data2
Data3
Data1 Data2 Data3
Data2
Data3
Data1
Data3
Data2 Data3
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Stack Animation
https://liveexample.pearsoncmg.com/dsanimation/StackeB
ook.html
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Queue Animation
https://liveexample.pearsoncmg.com/dsanimation/Queuee
Book.html
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Implementing Stacks and Queues
Using an array list to implement Stack
Use a linked list to implement Queue
Since the insertion and deletion operations on a stack are
made only at the end of the stack, using an array list to
implement a stack is more efficient than a linked list. Since
deletions are made at the beginning of the list, it is more
efficient to implement a queue using a linked list than an
array list. This section implements a stack class using an
array list and a queue using a linked list.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Design of the Stack and Queue Classes
• There are two ways to design the stack and queue classes:
– Using inheritance: You can define the stack class by extending
the array list class, and the queue class by extending the linked
list class.
– Using composition: You can define an array list as a data field
in the stack class, and a linked list as a data field in the queue
class.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Composition is Better
Both designs are fine, but using composition is better
because it enables you to define a complete new stack
class and queue class without inheriting the unnecessary
and inappropriate methods from the array list and linked
list.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
MyStack and MyQueue
GenericStack<E>
-list: java.util.ArrayList<E>
+GenericStack()
+getSize(): int
+peek(): E
+pop(): E
+push(o: E): void
+isEmpty(): boolean
Creates an empty stack.
Returns the number of elements in this stack.
Returns the top element in this stack.
Returns and removes the top element in this stack.
Adds a new element to the top of this stack.
Returns true if the stack is empty.
An array list to store elements.
GenericStack
GenericQueue<E>
-list: LinkedList<E>
+enqueue(e: E): void
+dequeue(): E
+getSize(): int
Adds an element to this queue.
Removes an element from this queue.
Returns the number of elements from this queue.
GenericQueue
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example: Using Stacks and Queues
Write a program that creates a stack using MyStack and a
queue using MyQueue. It then uses the push (enqueu)
method to add strings to the stack (queue) and the pop
(dequeue) method to remove strings from the stack
(queue).
TestStackQueue
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Priority Queue
A regular queue is a first-in and first-out data structure. Elements are
appended to the end of the queue and are removed from the beginning
of the queue. In a priority queue, elements are assigned with priorities.
When accessing elements, the element with the highest priority is
removed first. A priority queue has a largest-in, first-out behavior. For
example, the emergency room in a hospital assigns patients with
priority numbers; the patient with the highest priority is treated first.
MyPriorityQueue TestPriorityQueue
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 25
Binary Search Trees
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives
25.1 To become familiar with binary search trees (§25.2).
25.2 To represent binary trees using linked data structures (§25.3).
25.3 To search an element in binary search tree (§25.4).
25.4 To insert an element into a binary search tree (§25.5).
25.5 To traverse elements in a binary tree (§25.6).
25.6 To design and implement the Tree interface and the BST class (§25.7).
25.7 To delete elements from a binary search tree (§25.8).
25.8 To display binary tree graphically (§25.9).
25.9 To create iterators for traversing a binary tree (§25.10).
25.10 To implement Huffman coding for compressing data using a binary tree
(§25.11).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Binary Trees
A list, stack, or queue is a linear structure that consists of a
sequence of elements. A binary tree is a hierarchical
structure. It is either empty or consists of an element, called
the root, and two distinct binary trees, called the left
subtree and right subtree.
60
55 100
57 67 107
45
G
F R
M T
A
(A) (B)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
See How a Binary Search Tree Works
https://liveexample.pearsoncmg.com/dsanimation/BSTeBook.html
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Binary Tree Terms
The root of left (right) subtree of a node is called a left
(right) child of the node. A node without children is
called a leaf. A special type of binary tree called a
binary search tree is often useful. A binary search tree
(with no duplicate elements) has the property that for
every node in the tree the value of any node in its left
subtree is less than the value of the node and the value
of any node in its right subtree is greater than the value
of the node. The binary trees in Figure 25.1 are all binary
search trees. This section is concerned with binary
search trees.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Representing Binary Trees
A binary tree can be represented using a set of linked nodes. Each node
contains a value and two links named left and right that reference the
left child and right child, respectively, as shown in Figure 25.2.
class TreeNode<E> {
E element;
TreeNode<E> left;
TreeNode<E> right;
public TreeNode(E o) {
element = o;
}
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Searching an Element in a Binary Search
Tree
public boolean search(E element) {
TreeNode<E> current = root; // Start from the root
while (current != null)
if (element < current.element) {
current = current.left; // Go left
}
else if (element > current.element) {
current = current.right; // Go right
}
else // Element matches current.element
return true; // Element is found
return false; // Element is not in the tree
}
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Inserting an Element to a Binary Search
Tree
If a binary tree is empty, create a root node with the new
element. Otherwise, locate the parent node for the new
element node. If the new element is less than the parent
element, the node for the new element becomes the left
child of the parent. If the new element is greater than the
parent element, the node for the new element becomes the
right child of the parent. Here is the algorithm:
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Inserting an Element to a Binary Tree
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (1 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (2 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (3 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (4 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (5 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (6 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (7 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (8 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (9 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (10 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (11 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (12 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (13 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (14 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (15 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (16 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (17 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (18 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (19 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Inserting 101 into the following
tree (20 of 20)
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Inserting 59 into the Tree
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Tree Traversal (1 of 3)
Tree traversal is the process of visiting each node in the
tree exactly once. There are several ways to traverse a
tree. This section presents inorder, preorder, postorder,
depth-first, and breadth-first traversals.
The inorder traversal is to visit the left subtree of the
current node first recursively, then the current node itself,
and finally the right subtree of the current node
recursively.
The postorder traversal is to visit the left subtree of the
current node first, then the right subtree of the current
node, and finally the current node itself.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Tree Traversal (2 of 3)
The preorder traversal is to visit the current node first, then
the left subtree of the current node recursively, and finally
the right subtree of the current node recursively.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Tree Traversal (3 of 3)
The breadth-first traversal is to visit the nodes level by
level. First visit the root, then all children of the root from
left to right, then grandchildren of the root from left to right,
and so on.
For example, in the tree in Figure 25.2, the inorder is 45 55
57 59 60 67 100 101 107. The postorder is 45 59 57 55 67
101 107 100 60. The preorder is 60 55 45 57 59 100 67
107 101. The breadth-first traversal is 60 55 100 45 57 67
107 59 101.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Tree Interface
The Tree interface defines common operations for trees.
«interface»
Tree<E>
+search(e: E): boolean
+insert(e: E): boolean
+delete(e: E): boolean
+inorder(): void
+preorder(): void
+postorder(): void
+getSize(): int
+isEmpty(): boolean
+clear(): void
Override the add, isEmpty, remove,
containsAll, addAll, removeAll,
retainAll, toArray(), and toArray(T[])
methods defined in Collection using
default methods.
Returns true if the specified element is in the tree.
Returns true if the element is added successfully.
Returns true if the element is removed from the tree
successfully.
Prints the nodes in inorder traversal.
Prints the nodes in preorder traversal.
Prints the nodes in postorder traversal.
Returns the number of elements in the tree.
Returns true if the tree is empty.
Removes all elements from the tree.
«interface»
java.lang.Collection<E>
Tree
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The BST Class
Let’s define the binary tree class, named BST with A concrete
BST class can be defined to extend AbstractTree.
BST<E extends Comparable<E>>
#root: TreeNode<E>
#size: int
+BST()
+BST(objects: E[])
+path(e: E):
java.util.List<TreeNode<E>>
1
m
TreeNode<E>
Link
0
The root of the tree.
The number of nodes in the tree.
Creates a default BST.
Creates a BST from an array of elements.
Returns the path of nodes from the root leading to the
node for the specified element. The element may not be
in the tree.
«interface»
Tree<E>
BST
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example: Using Binary Trees
Write a program that creates a binary tree using BST. Add
strings into the binary tree and traverse the tree in inorder,
postorder, and preorder.
TestBST
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Tree After Insertions
George
Adam Michael
Daniel Jones Tom
root
Peter
Inorder: Adam, Daniel
George, Jones, Michael,
Peter, Tom
Postorder: Daniel Adam,
Jones, Peter, Tom,
Michael, George
Preorder: George, Adam,
Daniel, Michael, Jones,
Tom, Peter
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Deleting Elements in a Binary Search
Tree (1 of 6)
To delete an element from a binary tree, you need to first
locate the node that contains the element and also its
parent node. Let current point to the node that contains the
element in the binary tree and parent point to the parent of
the current node. The current node may be a left child or a
right child of the parent node. There are two cases to
consider:
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Deleting Elements in a Binary Search
Tree (2 of 6)
Case 1: The current node does not have a left child, as
shown in this figure (a). Simply connect the parent with the
right child of the current node, as shown in this figure (b).
parent
current
No left child
Subtree
parent
Subtree
current may be a left or
right child of parent
Subtree may be a left or
right subtree of parent
current points the node
to be deleted
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Deleting Elements in a Binary Search
Tree (3 of 6)
For example, to delete node 10 in Figure 25.9a. Connect
the parent of node 10 with the right child of node 10, as
shown in Figure 25.9b.
20
10 40
30 80
root
50
16
27
20
40
30 80
root
50
16
27
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Deleting Elements in a Binary Search
Tree (4 of 6)
Case 2: The current node has a left child. Let rightMost
point to the node that contains the largest element in the
left subtree of the current node and parentOfRightMost
point to the parent node of the rightMost node, as shown in
Figure 25.10a. Note that the rightMost node cannot have a
right child, but may have a left child. Replace the element
value in the current node with the one in the rightMost
node, connect the parentOfRightMost node with the left
child of the rightMost node, and delete the rightMost node,
as shown in Figure 25.10b.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Deleting Elements in a Binary Search
Tree (5 of 6)
Case 2 diagram
parent
current
.
.
.
rightMost
parentOfRightMost
parent
.
.
.
parentOfRightMost
Content copied to
current and the node
deleted
Right subtree Right subtree
current
current may be a left or
right child of parent
current points the node
to be deleted
The content of the current node is
replaced by content by the content of
the right-most node. The right-most
node is deleted.
leftChildOfRightMost leftChildOfRightMost
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Deleting Elements in a Binary Search
Tree (6 of 6)
Case 2 example, delete 20
rightMost
20
10 40
30 80
root
50
16
27
16
10 40
30 80
root
50
27
14 14
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Examples (1 of 3)
Delete this
node
George
Adam Michael
Daniel Jones Tom
Peter
Daniel
Adam Michael
Jones Tom
Peter
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Examples (2 of 3)
Daniel
Adam Michael
Jones Tom
Peter
Delete this
node
Daniel
Michael
Jones Tom
Peter
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Examples (3 of 3)
Daniel
Michael
Jones Tom
Peter
Delete this
node
Daniel
Jones
Tom
Peter
TestBSTDelete
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Binary Tree Time Complexity
It is obvious that the time complexity for the inorder, preorder,
and postorder is  
O n , since each node is traversed only
once. The time complexity for search, insertion and deletion
is the height of the tree. In the worst case, the height of the
tree is  
O n .
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Tree Visualization
BTView BSTAnimation
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Iterators
An iterator is an object that provides a uniform way for
traversing the elements in a container such as a set, list,
binary tree, etc.
TestBSTWithIterator
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Data Compression: Huffman Coding
In ASCII, every character is encoded in 8 bits. Huffman coding
compresses data by using fewer bits to encode more frequently
occurring characters. The codes for characters are constructed based
on the occurrence of characters in the text using a binary tree, called
the Huffman coding tree.
Mississippi
M p
1
0 s
0 i
0
1
1
Character Code Frequency
M 000 1
P 001 2
s 01 4
i 1 4
000101011010110010011 21 bits
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Constructing Huffman Tree (1 of 3)
To construct a Huffman coding tree, use a greedy
algorithm as follows:
• Begin with a forest of trees. Each tree contains a node
for a character. The weight of the node is the frequency
of the character in the text.
• Repeat this step until there is only one tree:
Choose two trees with the smallest weight and create a
new node as their parent. The weight of the new tree is
the sum of the weight of the subtrees.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Constructing Huffman Tree (2 of 3)
Mississippi
weight: 1
‘M’
weight: 4
‘s’
weight: 4
‘i’
weight: 2
‘p’
weight: 1
‘M’
weight: 4
‘s’
weight: 4
‘i’
weight: 2
‘p’
weight: 3
weight: 1
‘M’
weight: 4
‘s’
weight: 4
‘i’
weight: 2
‘p’
weight: 3
weight: 7
weight: 1
‘M’
weight: 4
‘s’
weight: 4
‘i’
weight: 2
‘p’
weight: 3
weight: 7
weight: 11
0 1
1
1
0
0
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Constructing Huffman Tree (3 of 3)
HuffmanCode
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 26
AVL Trees
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives
26.1 To know what an AVL tree is (§26.1).
26.2 To understand how to rebalance a tree using the LL rotation, LR
rotation, RR rotation, and RL rotation (§26.2).
26.3 To know how to design the AVLTree class (§26.3).
26.4 To insert elements into an AVL tree (§26.4).
26.5 To implement node rebalancing (§26.5).
26.6 To delete elements from an AVL tree (§26.6).
26.7 To implement the AVLTree class (§26.7).
26.8 To test the AVLTree class (§26.8).
26.9 To analyze the complexity of search, insert, and delete operations in
AVL trees (§26.9).
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Why AVL Tree?
The search, insertion, and deletion time for a binary tree is
dependent on the height of the tree. In the worst case, the
height is  
O n . If a tree is perfectly balanced, i.e., a
complete binary tree, its height is . Can we maintain a
perfectly balanced tree? Yes. But it will be costly to do so.
The compromise is to maintain a well-balanced tree, i.e., the
heights of two subtrees for every node are about the same.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
What Is an AVL Tree?
AVL trees are well-balanced. AVL trees were invented by two
Russian computer scientists G. M. Adelson-Velsky and E. M.
Landis in 1962. In an AVL tree, the difference between the
heights of two subtrees for every node is 0 or 1. It can be
shown that the maximum height of an AVL tree is  
O logn .
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
AVL Tree Animation
https://liveexample.pearsoncmg.com/dsanimation/AVLTree.html
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Balance Factor/Left-Heavy/Right-Heavy
The process for inserting or deleting an element in an AVL
tree is the same as in a regular binary search tree. The
difference is that you may have to rebalance the tree after an
insertion or deletion operation. The balance factor of a node
is the height of its right subtree minus the height of its left
subtree. A node is said to be balanced if its balance factor is
1, 0, or 1.
 A node is said to be left-heavy if its balance
factor is 1.
 A node is said to be right-heavy if its balance
factor is +1.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Balancing Trees
If a node is not balanced after an insertion or deletion
operation, you need to rebalance it. The process of
rebalancing a node is called a rotation. There are four
possible rotations.
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
LL Imbalance and LL Rotation
LL Rotation: An LL imbalance occurs at a node A such that
A has a balance factor 2
 and a left child B with a balance
factor 1 or 0.
 This type of imbalance can be fixed by
performing a single right rotation at A.
A -2
B
-1 or 0
T2
T3
T1
h+1 h
h
T2’s height is h or
h+1
A 0 or -1
B
0 or 1
T2 T3
T1
h+1
h h
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
RR Imbalance and RR Rotation
RR Rotation: An RR imbalance occurs at a node A such
that A has a balance factor +2 and a right child B with a
balance factor +1 or 0. This type of imbalance can be fixed
by performing a single left rotation at A.
A +2
B +1 or 0
T2
T3
T1
h+1
h
h
T2’s height is
h or h+1
A
0 or +1
B 0 or -1
T2
T3
T1
h+1
h
h
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
LR Imbalance and LR Rotation
LR Rotation: An LR imbalance occurs at a node A such 2

and a left child B with a balance factor +1. Assume B’s right
child is C. This type of imbalance can be fixed by performing
a double rotation (first a single left rotation at B and then a
single right rotation at A).
A -2
C
-1, 0, or 1
T3
T4
T2
h h
h
B
+1
T1
h
T2 and T3 may have
different height, but
at least one' must
have height of h.
C 0
A 0 or 1
T3 T4
T2
h h h
B
0 or -1
T1
h
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
RL Imbalance and RL Rotation
RL Rotation: An RL imbalance occurs at a node A such
that A has a balance factor +2 and a right child B with a
balance factor 1.
 Assume B’s left child is C. This type
of imbalance can be fixed by performing a double rotation
(first a single right rotation at B and then a single left
rotation at A).
A +2
C
0, -1,
or 1
T3
T4
T2
h h
h
B
-1
T1
h
T2 and T3 may have
different height, but
at least one' must
have height of h.
C 0
B 0 or 1
T3 T4
T2
h h h
A
0 or -1
T1
h
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Designing Classes for AVL Trees
An AVL tree is a binary tree. So you can define the AVL
Tree class to extend the BST class.
AVLTree
TestAVLTree
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.

02slide_accessible.pptx

  • 1.
    Introduction to JavaProgramming and Data Structures Thirteenth Edition Chapter 2 Elementary Programming Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 2.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical problems programmatically. Through these problems, you will learn Java primitive data types and related subjects, such as variables, constants, data types, operators, expressions, and input and output.
  • 3.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (1 of 2) 2.1 To write Java programs to perform simple computations (§2.2). 2.2 To obtain input from the console using the Scanner class (§2.3). 2.3 To use identifiers to name variables, constants, methods, and classes (§2.4). 2.4 To use variables to store data (§§2.5–2.6). 2.5 To program with assignment statements and assignment expressions (§2.6). 2.6 To use constants to store permanent data (§2.7). 2.7 To name classes, methods, variables, and constants by following their naming conventions (§2.8). 2.8 To explore Java numeric primitive data types: byte, short, int, long, float, and double (§2.9). 2.9 To read a byte, short, int, long, float, or double value from the keyboard (§2.9.1). 2.10 To perform operations using operators +, , , , and * / %  (§2.9.2). 2.11 To perform exponent operations using Math.pow(a, b) (§2.9.3). 2.12 To write integer literals, floating-point literals, and literals in scientific notation (§2.10). 2.13 To use JShell to quickly test Java code (§2.11).
  • 4.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (2 of 2) 2.14 To write and evaluate numeric expressions (§2.12). 2.15 To obtain the current system time using System.currentTimeMillis() (§2.13). 2.16 To use augmented assignment operators (§2.14). 2.17 To distinguish between postincrement and preincrement and between postdecrement and predecrement (§2.15). 2.18 To cast the value of one type to another type (§2.16). 2.19 To describe the software development process and apply it to develop the loan payment program (§2.17). 2.20 To write a program that converts a large amount of money into smaller units (§2.18). 2.21 To avoid common errors and pitfalls in elementary programming (§2.19).
  • 5.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introducing Programming With an Example Listing 2.1 Computing the Area of a Circle This program computes the area of the circle. ComputeArea Note: Clicking the green button displays the source code with interactive animation. You can also run the code in a browser. Internet connection is needed for this button.
  • 6.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace a Program Execution (1 of 5)
  • 7.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace a Program Execution (2 of 5)
  • 8.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace a Program Execution (3 of 5)
  • 9.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace a Program Execution (4 of 5)
  • 10.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace a Program Execution (5 of 5)
  • 11.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Reading Input From the Console 1. Create a Scanner object Scanner input = new Scanner(System.in); 2. Use the method nextDouble() to obtain to a double value. For example, System.out.print("Enter a double value: "); Scanner input = new Scanner(System.in); double d = input.nextDouble(); ComputeAreaWithConsoleInput ComputeAverage
  • 12.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Implicit Import and Explicit Import java.util.* ; // Implicit import java.util.Scanner; // Explicit Import No performance difference
  • 13.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Identifiers • An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). • An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit. • An identifier cannot be a reserved word. (See Appendix A, “Java Keywords,” for a list of reserved words). • An identifier cannot be true, false, or null. • An identifier can be of any length.
  • 14.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Variables // Compute the first area radius = 1.0; area = radius * radius * 3.14159; System.out.println("The area is “ + area + " for radius "+radius); // Compute the second area radius = 2.0; area = radius * radius * 3.14159; System.out.println("The area is “ + area + " for radius "+radius);
  • 15.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Declaring Variables int x; // Declare x to be an // integer variable; double radius; // Declare radius to // be a double variable; char a; // Declare a to be a // character variable;
  • 16.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a;
  • 17.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Declaring and Initializing in One Step • int x = 1; • double d = 1.4;
  • 18.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Named Constants final datatype CONSTANTNAME = VALUE; final double PI = 3.14159; final int SIZE = 3;
  • 19.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Naming Conventions (1 of 2) • Choose meaningful and descriptive names. • Variables and method names: – Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computeArea.
  • 20.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Naming Conventions (2 of 2) • Class names: – Capitalize the first letter of each word in the name. For example, the class name ComputeArea. • Constants: – Capitalize all letters in constants, and use underscores to connect words. For example, the constant PI and MAX_VALUE
  • 21.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Numerical Data Types Name Range Storage Size byte negative 2 to the power 7 to 2 to the power 7 minus 1 left parenthesis negative 128 to 127 right parenthesis. 8-bit signed short negative 2 to the power 15 to 2 to the power 15 minus 1 left parenthesis (negative 32768 to 32767 right parenthesis. 16-bit signed int negative 2 to the power 31 to 2 to the power 31 minus 1 left parenthesis negative 2147483648 to 2147483647 right parenthesis. 32-bit signed long negative 2 to the power 63 to 2 to the power 63 minus 1 left parenthesis that is, negative 9223372036854775808 to 9223372036854775807 right parenthesis. 64-bit signed float negative range, negative -3.4028235 E + 38 to negative 1.4 E minus 45, positive range, 1.4 E minus 45 to 3.4028235 E + 38. 32-bit IEEE 754 double negative range, negative 1.7976931348623157 E + 308 to negative 4.9 E minus 324, positive range, 4.9 E minus 324 to 1.7976931348623157 E + 308. 64-bit IEEE 754   7 7 2 to 2 1 128 to 127      15 15 2 to 2 1 32768 to 32767      31 31 2 to 2 1 2147483648 to 2147483647      63 63 2 to 2 1 i.e., 9223372036854775808 to 9223372036854775807    Negative range: 3.4028235E 38 to 1.4E 45 Positive range: 1.4E 45 to 3.4028235E 38       Negative range: 1.7976931348623157E 308 to 4.9E 324 Positive range: 4.9E 324 to 1.7976931348623157E 308      
  • 22.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Reading Numbers From the Keyboard Scanner input = new Scanner(System.in); int value = input.nextInt(); Method Description nextByte() reads an integer of the byte type. nextShort() reads an integer of the short type. nextInt() reads an integer of the int type. nextLong() reads an integer of the long type. nextFloat() reads a number of the float type. nextDouble() reads a number of the double type.
  • 23.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Numeric Operators Name Meaning Example Result + Addition 34 + 1 35 The symbol of minus Subtraction 34.0 minus 0.1 33.9 * Multiplication 300 times 30 9000 division slash Division 1.0 divided by 2.0. 0.5 symbol of modulo remainder Remainder 20 modulo remainder 3 2  34.0 0.1  300 * 30 / 1.0 / 2.0 % 20 % 3
  • 24.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Integer Division +, ,  *, /, and % 5 / 2 yields an integer 2. 5.0 / 2 yields a double value 2.5 5 % 2 yields 1 (the remainder of the division)
  • 25.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Remainder Operator Remainder is very useful in programming. For example, an even number % 2 is always 0 and an odd number % 2 is always 1. So you can use this property to determine whether a number is even or odd. Suppose today is Saturday and you and your friends are going to meet in 10 days. What day is in 10 days? You can find that day is Tuesday using the following expression:
  • 26.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Displaying Time Write a program that obtains minutes and remaining seconds from seconds. DisplayTime
  • 27.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Note Calculations involving floating-point numbers are approximated because these numbers are not stored with complete accuracy. For example, System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1); displays 0.5000000000000001, not 0.5, and System.out.println(1.0 - 0.9); displays 0.09999999999999998, not 0.1. Integers are stored precisely. Therefore, calculations with integers yield a precise integer result.
  • 28.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Exponent Operations System.out.println(Math.pow(2, 3)); // Displays 8.0 System.out.println(Math.pow(4, 0.5)); // Displays 2.0 System.out.println(Math.pow(2.5, 2)); // Displays 6.25 System.out.println(Math.pow(2.5, -2)); // Displays 0.16
  • 29.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Number Literals A literal is a constant value that appears directly in the program. For example, 34, 1,000,000, and 5.0 are literals in the following statements: int i = 34; long x = 1000000; double d = 5.0;
  • 30.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Integer Literals An integer literal can be assigned to an integer variable as long as it can fit into the variable. A compilation error would occur if the literal were too large for the variable to hold. For example, the statement byte b = 1000 would cause a compilation error, because 1000 cannot be stored in a variable of the byte type. An integer literal is assumed to be of the int type, whose value is between     31 31 2 2147483648 to 2 1 2147483647 .    To denote an integer literal of the long type, append it with the letter L or l. L is preferred because l (lowercase L) can easily be confused with 1 (the digit one).
  • 31.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Floating-Point Literals Floating-point literals are written with a decimal point. By default, a floating-point literal is treated as a double type value. For example, 5.0 is considered a double value, not a float value. You can make a number a float by appending the letter f or F, and make a number a double by appending the letter d or D. For example, you can use 100.2f or 100.2F for a float number, and 100.2d or 100.2D for a double number.
  • 32.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved double versus float The double type values are more accurate than the float type values. For example, System.out.println("1.0 / 3.0 is " + 1.0 / 3.0); displays 16 digits 3 1 0.3333333333 33333 .0 / 3.0 is System.out.println("1.0F / 3.0F is " + 1.0F / 3.0F); displays 7 digits 0.33333334 1.0 / 3.0 is F F
  • 33.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Scientific Notation Floating-point literals can also be specified in scientific notation, for example, 1.23456e+2, same as 1.23456e2, is equivalent to 123.456, and  1.23456e 2 is equivalent to 0.0123456. E (or e) represents an exponent and it can be either in lowercase or uppercase.
  • 34.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved JShell JShell is a command line interactive tool introduced in Java 9. JShell enables you to type a single Java statement and get it executed to see the result right away without having to write a complete class. This feature is commonly known as REPL (Read-Evaluate-Print Loop), which evaluates expressions and executes statements as they are entered and shows the result immediately.
  • 35.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Arithmetic Expressions    10 5 3 4 4 9 9( ) 5 y a b c x x x x y         is translated to           3 4 * / 5 10 * 5 * / 9 * 4 / 9 / x y a b c x x x y        
  • 36.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved How to Evaluate an Expression Though Java has its own way to evaluate an expression behind the scene, the result of a Java expression and its corresponding arithmetic expression are the same. Therefore, you can safely apply the arithmetic rule for evaluating a Java expression. 3 + 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 53 (1) inside parentheses first (2) multiplication (3) multiplication (4) addition (6) subtraction (5) addition
  • 37.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Converting Temperatures Write a program that converts a Fahrenheit degree to Celsius using the formula:   5 32 9 celsius fahrenheit         Note: you have to write       celsius 5.0 / 9 * fahrenheit 32 FahrenheitToCelsius
  • 38.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Displaying Current Time Write a program that displays current time in GMT in the format hour:minute:second such as 1:45:19. The currentTimeMillis method in the System class returns the current time in milliseconds since the midnight, January 1, 1970 GMT. (1970 was the year when the Unix operating system was formally introduced.) You can use this method to obtain the current time, and then compute the current second, minute, and hour as follows. ShowCurrentTime
  • 39.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Augmented Assignment Operators Operator Name Example Equivalent += Addition assignment i += 8 i = i + 8 negative = Subtraction assignment i minus = 8 I = I minus 8 *= Multiplication assignment i *= 8 i = i * 8 forward slash = Division assignment I forward slash = 8 I = I over 8 %= Remainder assignment i %= 8 i = i % 8   i -= 8 i= i - 8 / = i / = 8 i= i / 8
  • 40.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Increment and Decrement Operators (1 of 3) Operator Name Description Example (assume i = 1) ++var preincrement Increment var by 1, and use the new var value in the statement int j = ++i; // j is 2, i is 2 var++ postincrement Increment var by 1, but use the original var value in the statement int j = i++; // j is 1, i is 2 dash dash variable; predecrement Decrement var by 1, and use the new var value in the statement int j = --i; // j is 0, i is 0 variable dash dash; postdecrement Decrement var by 1, and use the original var value in the statement int j = i--; // j is 1, i is 0 -- var var --
  • 41.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Increment and Decrement Operators (2 of 3) int i = 10; int newNum = 10 * i++; int newNum = 10 * i; i = i + 1; Same effect as int i = 10; int newNum = 10 * (++i); i = i + 1; int newNum = 10 * i; Same effect as
  • 42.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Increment and Decrement Operators (3 of 3) Using increment and decrement operators makes expressions short, but it also makes them complex and difficult to read. Avoid using these operators in expressions that modify multiple variables, or the same variable for multiple times such as this: int k = ++i + i.
  • 43.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Assignment Expressions and Assignment Statements Prior to Java 2, all the expressions can be used as statements. Since Java 2, only the following types of expressions can be statements: variable op= expression; // Where op is +, , *, /, or % ++variable; variable++;   variable;   variable ;
  • 44.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Numeric Type Conversion Consider the following statements: byte i = 100; long k = i * 3 + 4; double d = i * 3.1 + k / 2;
  • 45.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Conversion Rules When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules: 1. If one of the operands is double, the other is converted into double. 2. Otherwise, if one of the operands is float, the other is converted into float. 3. Otherwise, if one of the operands is long, the other is converted into long. 4. Otherwise, both operands are converted into int.
  • 46.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Type Casting Implicit casting double d = 3; (type widening) Explicit casting int i = (int)3.0; (type narrowing) int i = (int)3.9; (Fraction part is truncated) What is wrong? int x = 5 / 2.0; byte, short, int, long, float, double range increases
  • 47.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Keeping Two Digits After Decimal Points Write a program that displays the sales tax with two digits after the decimal point. SalesTax
  • 48.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Casting in an Augmented Expression In Java, an augmented expression of the form x1 op= x2 is implemented as x1 = (T)(x1 op x2), where T is the type for x1. Therefore, the following code is correct. int sum = 0; sum += 4.5; // sum becomes 4 after this statement sum += 4.5 is equivalent to sum = (int)(sum + 4.5).
  • 49.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Software Development Process
  • 50.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Requirement Specification
  • 51.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved System Analysis
  • 52.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved System Design
  • 53.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved IPO
  • 54.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Implementation
  • 55.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Testing
  • 56.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Deployment
  • 57.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Maintenance
  • 58.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Computing Loan Payments This program lets the user enter the interest rate, number of years, and loan amount, and computes monthly payment and total payment.   12 1 1 1 numberOfYears loanAmount monthlyInterestRate monthlyPayment monthlyInterestRate      ComputeLoan
  • 59.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Monetary Units This program lets the user enter the amount in decimal representing dollars and cents and output a report listing the monetary equivalent in single dollars, quarters, dimes, nickels, and pennies. Your program should report maximum number of dollars, then the maximum number of quarters, and so on, in this order. ComputeChange
  • 60.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Common Errors and Pitfalls • Common Error 1: Undeclared/Uninitialized Variables and Unused Variables • Common Error 2: Integer Overflow • Common Error 3: Round-off Errors • Common Error 4: Unintended Integer Division • Common Error 5: Redundant Input Objects • Common Pitfall 1: Redundant Input Objects
  • 61.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Common Error 1: Undeclared/Uninitialized Variables and Unused Variables double interestRate = 0.05; double interest = interestrate * 45;
  • 62.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Common Error 2: Integer Overflow int value = 2147483647 + 1; // value will actually be 2147483648
  • 63.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Common Error 3: Round-off Errors System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1); System.out.println(1.0 - 0.9);
  • 64.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Common Error 4: Unintended Integer Division int number1 = 1; int number2 = 2; double average = (number1 + number2) / 2; System.out.println(average); (a) int number1 = 1; int number2 = 2; double average = (number1 + number2) / 2.0; System.out.println(average); (b)
  • 65.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Common Pitfall 1: Redundant Input Objects Scanner input = new Scanner(System.in); System.out.print("Enter an integer: "); int v1 = input.nextInt(); Scanner input1 = new Scanner(System.in); System.out.print("Enter a double value: "); double v2 = input1.nextDouble();
  • 66.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.
  • 67.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introduction to Java Programming and Data Structures Thirteenth Edition Chapter 3 Selections Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 68.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Motivations If you assigned a negative value for radius in Listing 2.2, ComputeAreaWithConsoleInput.java, the program would print an invalid result. If the radius is negative, you don't want the program to compute the area. How can you deal with this situation?
  • 69.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (1 of 2) 3.1 To declare boolean variables and write Boolean expressions using relational operators (§3.2). 3.2 To implement selection control using one-way if statements (§3.3). 3.3 To implement selection control using two-way if-else statements (§3.4). 3.4 To implement selection control using nested if and multi- way if statements (§3.5). 3.5 To avoid common errors and pitfalls in if statements (§3.6). 3.6 To generate random numbers using the Math.random() method (§3.7).
  • 70.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (2 of 2) 3.7 To program using selection statements for a variety of examples (SubtractionQuiz, BMI, ComputeTax) (§§3.7–3.9). 3.8 To combine conditions using logical operators (&&, ||, and !) (§3.10). 3.9 To program using selection statements with combined conditions (LeapYear, Lottery) (§§3.11–3.12). 3.10 To implement selection control using switch statements and expressions (§3.13). 3.11 To write expressions using the conditional expression (§3.14). 3.12 To examine the rules governing operator precedence and associativity (§3.15). 3.13 To apply common techniques to debug errors (§3.16).
  • 71.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The boolean Type and Operators Often in a program you need to compare two values, such as whether i is greater than j. Java provides six comparison operators (also known as relational operators) that can be used to compare two values. The result of the comparison is a Boolean value: true or false. boolean b = (1 > 2);
  • 72.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Relational Operators Java Operator Mathematics Symbol Name Example (radius is 5) Result < < less than radius < 0 false <= Less than or equal to less than or equal to radius <= 0 false > > greater than radius > 0 true >= Greater than or equal to greater than or equal to radius >= 0 true == = equal to radius == 0 false != Not equal to not equal to radius != 0 true   
  • 73.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: A Simple Math Learning Tool This example creates a program to let a first grader practice additions. The program randomly generates two single-digit integers number1 and number2 and displays a question such as “What is 7 + 9?” to the student. After the student types the answer, the program displays a message to indicate whether the answer is true or false. AdditionQuiz
  • 74.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved One-Way if Statements
  • 75.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Note if i > 0 { System.out.println("i is positive"); } (a) Wrong (b) Correct if (i > 0) { System.out.println("i is positive"); } if (i > 0) { System.out.println("i is positive"); } (a) Equivalent (b) if (i > 0) System.out.println("i is positive");
  • 76.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Simple if Demo Write a program that prompts the user to enter an integer. If the number is a multiple of 5, print HiFive. If the number is divisible by 2, print HiEven. SimpleIfDemo
  • 77.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Two-Way if Statement if (boolean-expression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; }
  • 78.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved if-else Example if (radius >= 0) { area = radius * radius * 3.14159; System.out.println("The area for the “ + “circle of radius " + radius + " is " + area); } else { System.out.println("Negative input"); }
  • 79.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Multiple Alternative if Statements if (score >= 90.0) System.out.print("A"); else if (score >= 80.0) System.out.print("B"); else if (score >= 70.0) System.out.print("C"); else if (score >= 60.0) System.out.print("D"); else System.out.print("F"); (a) Equivalent if (score >= 90.0) System.out.print("A"); else if (score >= 80.0) System.out.print("B"); else if (score >= 70.0) System.out.print("C"); else if (score >= 60.0) System.out.print("D"); else System.out.print("F"); (b) This is better
  • 80.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Multi-Way if-else Statements
  • 81.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace if-else Statement (1 of 5)
  • 82.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace if-else Statement (2 of 5)
  • 83.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace if-else Statement (3 of 5)
  • 84.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace if-else Statement (4 of 5)
  • 85.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace if-else Statement (5 of 5)
  • 86.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Note (1 of 2) The else clause matches the most recent if clause in the same block.
  • 87.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Note (2 of 2) Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces: int i = 1; int j = 2; int k = 3; if (i > j) { if (i > k) System.out.println("A"); } else System.out.println("B"); This statement prints B.
  • 88.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Common Errors Adding a semicolon at the end of an if clause is a common mistake. This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error. This error often occurs when you use the next-line block style.
  • 89.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved TIP if (number % 2 == 0) even = true; else even = false; (a) Equivalent boolean even = number % 2 == 0; (b)
  • 90.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved CAUTION if (even == true) System.out.println( "It is even."); (a) Equivalent if (even) System.out.println( "It is even."); (b)
  • 91.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: An Improved Math Learning Tool This example creates a program to teach a first grade child how to learn subtractions. The program randomly generates two single-digit integers number1 and number2 with number1 >= number2 and displays a question such as “What is  9 2?” to the student. After the student types the answer, the program displays whether the answer is correct. SubtractionQuiz
  • 92.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Body Mass Index Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your weight in kilograms and dividing by the square of your height in meters. The interpretation of BMI for people 16 years or older is as follows: BMI Interpretation BMI < 18.5 Underweight 18.5 <= BMI < 25.0 Normal 25.0 <= BMI < 30.0 Overweight 30.0 <= BMI Obese ComputeAndInterpretBMI
  • 93.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Computing Taxes (1 of 2) The US federal personal income tax is calculated based on the filing status and taxable income. There are four filing statuses: single filers, married filing jointly, married filing separately, and head of household. The tax rates for 2009 are shown below. Marginal Tax Rate Single Married Filing Jointly or Qualifying Widow(er) Married Filing Separately Head of Household 10% $0 - $8,350 $0 - $16,700 $0 - $8,350 $0 - $11,950 15% $8,351 - $33,950 $16,701 - $67,900 $8,351 - $33,950 $11,951 - $45,500 25% $33,951 - $82,250 $67,901 - $137,050 $33,951 - $68,525 $45,501 - $117,450 28% $82,251 - $171,550 $137,051 - $208,850 $68,526 - $104,425 $117,451 - $190,200 33% $171,551 - $372,950 $208,851 - $372,950 $104,426 - $186,475 $190,201 - $372,950 35% $372,951+ $372,951+ $186,476+ $372,951+
  • 94.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Computing Taxes (2 of 2) if (status == 0) { // Compute tax for single filers } else if (status == 1) { // Compute tax for married file jointly // or qualifying widow(er) } else if (status == 2) { // Compute tax for married file separately } else if (status == 3) { // Compute tax for head of household } else { // Display wrong status } ComputeTax
  • 95.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Logical Operators Operator Name Description ! not logical negation && and logical conjunction || or logical disjunction ^ exclusive or logical exclusion
  • 96.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Truth Table for Operator ! p !p Example (assume age = 24, weight = 140) true false !(age > 18) is false, because (age > 18) is true. false true !(weight == 150) is true, because (weight == 150) is false.
  • 97.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Truth Table for Operator && p1 p2 p1 && p2 Example (assume age = 24, weight = 140) false false false (age <= 18) && (weight < 140) is false, because both conditions are both false. false true false Blank true false false (age > 18) && (weight > 140) is false, because (weight > 140) is false. true true true (age > 18) && (weight >= 140) is true, because both (age > 18) and (weight >= 140) are true.
  • 98.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Truth Table for Operator || p1 p2 p1 || p2 Example (assume age = 24, weight = 140) false false false Blank false true true (age > 34) || (weight <= 140) is true, because (age > 34) is false, but (weight <= 140) is true. true false true (age > 14) || (weight >= 150) is false, because (age > 14) is true. true true true Blank
  • 99.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Truth Table for Operator ^ p1 p2 p1 ^ p2 Example (assume age = 24, weight = 140) false false false (age > 34) ^ (weight > 140) is true, because (age > 34) is false and (weight > 140) is false. false true true (age > 34) ^ (weight >= 140) is true, because (age > 34) is false but (weight >= 140) is true. true false true (age > 14) ^ (weight > 140) is true, because (age > 14) is true and (weight > 140) is false. true true false Blank
  • 100.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Examples (1 of 2) Here is a program that checks whether a number is divisible by 2 and 3, whether a number is divisible by 2 or 3, and whether a number is divisible by 2 or 3 but not both: TestBooleanOperators
  • 101.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Examples (2 of 2) System.out.println("Is " + number + " divisible by 2 and 3? " + ((number % 2 == 0) && (number % 3 == 0))); System.out.println("Is " + number + " divisible by 2 or 3? " + ((number % 2 == 0) || (number % 3 == 0))); System.out.println("Is " + number + " divisible by 2 or 3, but not both? " + ((number % 2 == 0) ^ (number % 3 == 0))); TestBooleanOperators
  • 102.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The & and | Operators (1 of 2) Supplement III.B, “The & and | Operators”
  • 103.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The & and | Operators (2 of 2) If x is 1, what is x after this expression? (x > 1) & (x++ < 10) If x is 1, what is x after this expression? (1 > x) && ( 1 > x++) How about (1 == x) | (10 > x++)? (1 == x) || (10 > x++)?
  • 104.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Determining Leap Year? This program first prompts the user to enter a year as an int value and checks if it is a leap year. A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400. (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) LeapYear
  • 105.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Lottery Write a program that randomly generates a lottery of a two- digit number, prompts the user to enter a two-digit number, and determines whether the user wins according to the following rule: • If the user input matches the lottery in exact order, the award is $10,000. • If the user input matches the lottery, the award is $3,000. • If one digit in the user input matches a digit in the lottery, the award is $1,000. Lottery
  • 106.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved switch Statements switch (status) { case 0: compute taxes for single filers; break; case 1: compute taxes for married file jointly; break; case 2: compute taxes for married file separately; break; case 3: compute taxes for head of household; break; default: System.out.println("Errors: invalid status"); System.exit(1); }
  • 107.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved switch Statement Flow Chart
  • 108.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved switch Statement Rules (1 of 2)
  • 109.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved switch Statement Rules (2 of 2)
  • 110.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace switch Statement (1 of 7)
  • 111.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace switch Statement (2 of 7)
  • 112.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace switch Statement (3 of 7)
  • 113.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace switch Statement (4 of 7)
  • 114.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace switch Statement (5 of 7)
  • 115.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace switch Statement (6 of 7)
  • 116.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace switch Statement (7 of 7)
  • 117.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Chinese Zodiac Write a program that prompts the user to enter a year and displays the animal for the year. ChineseZodiac
  • 118.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved 118 JDK 14 Arrow Operator (->) Forgetting a break statement when it is needed is a common error. To avoid this type of errors, JDK 14 introduced a new arrow operator (->). You can use the arrow operator to replace the colon operator (:). With the arrow operator, there is no need to use the break statement. When a case is matched, the matching statement(s) are executed, and the switch statement is finished. int day = 1; switch (day) { case 1 -> System.out.print(1 + " "); case 2 -> System.out.print(2 + " "); case 3 -> System.out.print(3 + " "); }
  • 119.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved 119 JDK 14 switch Expression Java 14 also introduced switch expressions. A switch expression returns a value. Here is an example: int day = 1; System.out.println( switch (day) { case 1 -> 1 + " "; case 2 -> 2 + " "; case 3 -> 3 + " "; default -> " "; } ); The switch expression in this example returns a string. A switch expression must cover all cases, while a switch statement does not have to cover all cases. In the preceding example, the default clause is to required to cover the integers not listed in the cases.
  • 120.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved 120 JDK 14 switch Combining Cases In Java 14, the cases can be combined. For example, the preceding code can be simplified as follows: int day = 1; System.out.println( switch (day) { case 1, 2, 3 -> day + " "; default -> " "; } ); case 1, 2, 3 means case 1, case 2, or case 3.
  • 121.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved 121 The yield Keyword In Java 14, the cases can be combined. For example, the preceding code can be simplified as follows: int day = 1; System.out.println( switch (day) { case 1, 2, 3 -> day + " "; default -> " "; } ); case 1, 2, 3 means case 1, case 2, or case 3.
  • 122.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved 122 The yield Keyword If the result for a matching case in a switch expression is not a simple value, you need to use the yield keyword to return the value. Here is an example, int year = 2000; int month = 2; System.out.println( switch (month) { case 2 -> { if (isLeapYear(year)) yield "29 days"; else yield "28 days"; } default -> " "; } );
  • 123.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Conditional Operators if (x > 0) y = 1 else y = -1; is equivalent to y = (x > 0) ? 1 : -1; (boolean-expression) ? expression1 : expression2 Ternary operator Binary operator Unary operator
  • 124.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Conditional Operator (1 of 2) if (num % 2 == 0) System.out.println(num + “is even”); else System.out.println(num + “is odd”); System.out.println( (num % 2 == 0)? num + “is even” : num + “is odd”);
  • 125.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Conditional Operator (2 of 2) boolean-expression ? exp1 : exp2
  • 126.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Operator Precedence • var++, var-- • +, - (Unary plus and minus), ++var,--var • (type) Casting • ! (Not) • *, /, % (Multiplication, division, and remainder) • +, - (Binary addition and subtraction) • <, <=, >, >= (Relational operators) • ==, !=; (Equality) • ^ (Exclusive OR) • && (Conditional AND) Short-circuit AND • || (Conditional OR) Short-circuit OR • =, +=, -=, *=, /=, %= (Assignment operator)
  • 127.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Operator Precedence and Associativity The expression in the parentheses is evaluated first. (Parentheses can be nested, in which case the expression in the inner parentheses is executed first.) When evaluating an expression without parentheses, the operators are applied according to the precedence rule and the associativity rule. If operators with the same precedence are next to each other, their associativity determines the order of evaluation. All binary operators except assignment operators are left- associative.
  • 128.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Operator Associativity When two operators with the same precedence are evaluated, the associativity of the operators determines the order of evaluation. All binary operators except assignment operators are left-associative. a b c d    is equivalent to ((a b) c) d    Assignment operators are right-associative. Therefore, the expression a b c 5     is equivalent to a (b (c 5))    
  • 129.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example Applying the operator precedence and associativity rule, the expression 3 4 * 4 5 * (4 3) 1     is evaluated as follows: 3 + 4 * 4 > 5 * (4 + 3) - 1 3 + 4 * 4 > 5 * 7 – 1 3 + 16 > 5 * 7 – 1 3 + 16 > 35 – 1 19 > 35 – 1 19 > 34 false (1) inside parentheses first (2) multiplication (3) multiplication (4) addition (5) subtraction (6) greater than
  • 130.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Operand Evaluation Order Supplement III.A, “Advanced discussions on how an expression is evaluated in the JVM.”
  • 131.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Debugging Logic errors are called bugs. The process of finding and correcting errors is called debugging. A common approach to debugging is to use a combination of methods to narrow down to the part of the program where the bug is located. You can hand-trace the program (i.e., catch errors by reading the program), or you can insert print statements in order to show the values of the variables or the execution flow of the program. This approach might work for a short, simple program. But for a large, complex program, the most effective approach for debugging is to use a debugger utility.
  • 132.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Debugger Debugger is a program that facilitates debugging. You can use a debugger to • Execute a single statement at a time. • Trace into or stepping over a method. • Set breakpoints. • Display variables. • Display call stack. • Modify variables.
  • 133.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Debugging in NetBeans Supplement II.E, Learning Java Effectively with NetBeans
  • 134.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Debugging in Eclipse Supplement II.G, Learning Java Effectively with Eclipse
  • 135.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.
  • 136.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introduction to Java Programming and Data Structures Thirteenth Edition Chapter 4 Mathematical Functions, Characters, and Strings Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 137.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Motivations Suppose you need to estimate the area enclosed by four cities, given the GPS locations (latitude and longitude) of these cities, as shown in the following diagram. How would you write a program to solve this problem? You will be able to write such a program after completing this chapter.
  • 138.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (1 of 2) 4.1 To solve mathematics problems by using the methods in the Math class (§4.2). 4.2 To represent characters using the char type (§4.3). 4.3 To encode characters using ASCII and Unicode (§4.3.1). 4.4 To represent special characters using the escape sequences (§4.4.2). 4.5 To cast a numeric value to a character and cast a character to an integer (§4.3.3). 4.6 To compare and test characters using the static methods in the Character class (§4.3.4). 4.7 To introduce objects and instance methods (§4.4). 4.8 To represent strings using the String objects (§4.4). 4.9 To return the string length using the length() method (§4.4.1). 4.10 To return a character in the string using the charAt(i) method (§4.4.2). 4.11 To use the + operator to concatenate strings (§4.4.3).
  • 139.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (2 of 2) 4.12 To return an uppercase string or a lowercase string and to trim a string (§4.4.4). 4.13 To read strings from the console (§4.4.4). 4.14 To read a character from the console (§4.4.5). 4.15 To compare strings using the equals method and the compareTo methods (§4.4.6). 4.16 To obtain substrings (§4.4.7). 4.17 To find a character or a substring in a string using the indexOf method (§4.4.8). 4.18 To program using characters and strings (GuessBirthday) (§4.5.1). 4.19 To convert a hexadecimal character to a decimal value (HexDigit2Dec) (§4.5.2). 4.20 To revise the lottery program using strings (LotteryUsingStrings) (§4.5.3). 4.21 To format output using the System.out.printf method (§4.6). 4.22 To form multi-line strings using text blocks (§4.7).
  • 140.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Mathematical Functions Java provides many useful methods in the Math class for performing common mathematical functions.
  • 141.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Math Class • Class constants: – PI – E • Class methods: – Trigonometric Methods – Exponent Methods – Rounding Methods – min, max, abs, and random Methods
  • 142.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trigonometric Methods • sin(double a) • cos(double a) • tan(double a) • acos(double a) • asin(double a) • atan(double a) Radians toRadians(90) Examples: Math.sin(0) returns 0.0 Math.sin(Math.PI / 6) returns 0.5 Math.sin(Math.PI / 2) returns 1.0 Math.cos(0) returns 1.0 Math.cos(Math.PI / 6) returns 0.866 Math.cos(Math.PI / 2) returns 0
  • 143.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Exponent Methods • exp(double a) Returns e raised to the power of a. • log(double a) Returns the natural logarithm of a. • log10(double a) Returns the 10-based logarithm of a. • pow(double a, double b) Returns a raised to the power of b. • sqrt(double a) Returns the square root of a. Examples: Math.exp(1) returns 2.71 Math.log(2.71) returns 1.0 Math.pow(2, 3) returns 8.0 Math.pow(3, 2) returns 9.0 Math.pow(3.5, 2.5) returns 22.91765 Math.sqrt(4) returns 2.0 Math.sqrt(10.5) returns 3.24
  • 144.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Rounding Methods • double ceil(double x) x rounded up to its nearest integer. This integer is returned as a double value. • double floor(double x) x is rounded down to its nearest integer. This integer is returned as a double value. • double rint(double x) x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double. • int round(float x) Return (int)Math.floor(x+0.5). • long round(double x) Return (long)Math.floor(x+0.5).
  • 145.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Rounding Methods Examples Math.ceil(2.1) returns 3.0 Math.ceil(2.0) returns 2.0 Math.ceil(-2.0) returns –2.0 Math.ceil(-2.1) returns -2.0 Math.floor(2.1) returns 2.0 Math.floor(2.0) returns 2.0 Math.floor(-2.0) returns –2.0 Math.floor(-2.1) returns -3.0 Math.rint(2.1) returns 2.0 Math.rint(2.0) returns 2.0 Math.rint(-2.0) returns –2.0 Math.rint(-2.1) returns -2.0 Math.rint(2.5) returns 2.0 Math.rint(-2.5) returns -2.0 Math.round(2.6f) returns 3 Math.round(2.0) returns 2 Math.round(-2.0f) returns -2 Math.round(-2.6) returns -3
  • 146.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved min, max, and abs • max(a, b) and min(a, b) Returns the maximum or minimum of two parameters. • abs(a) Returns the absolute value of the parameter. • random() Returns a random double value in the range [0.0, 1.0). Examples: Math.max(2, 3) returns 3 Math.max(2.5, 3) returns 3.0 Math.min(2.5, 3.6) returns 2.5 Math.abs(-2) returns 2 Math.abs(-2.1) returns 2.1
  • 147.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The random Method Generates a random double value greater than or equal to 0.0 and less than 1.0 (0 <= Math.random() < 1.0). Examples: (int)(Math.random() * 10) Returns a random integer between 0 and 9. 50 + (int)(Math.random() * 50) Returns a random integer between 50 and 99. In general, a + Math.random() * b Returns a random number between a and a + b, excluding a + b.
  • 148.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Case Study: Computing Angles of a Triangle A B C a b c A = acos((a * a - b * b - c * c) / (-2 * b * c)) B = acos((b * b - a * a - c * c) / (-2 * a * c)) C = acos((c * c - b * b - a * a) / (-2 * a * b)) x1, y1 x2, y2 x3, y3 Write a program that prompts the user to enter the x- and y-coordinates of the three corner points in a triangle and then displays the triangle’s angles. ComputeAngles
  • 149.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Character Data Type NOTE: The increment and decrement operators can also be used on char variables to get the next or preceding Unicode character. For example, the following statements display character b. char ch = 'a'; System.out.println(++ch);
  • 150.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Unicode Format Java characters use Unicode, a 16-bit encoding scheme established by the Unicode Consortium to support the interchange, processing, and display of written texts in the world’s diverse languages. Unicode takes two bytes, preceded by u, expressed in four hexadecimal numbers that run from 'u0000' to 'uFFFF'. So, Unicode can represent 65535 + 1 characters.
  • 151.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved ASCII Code for Commonly Used Characters Characters Code Value in Decimal Unicode Value '0' to '9' 48 to 57 u0030 to u0039 'A' to 'Z' 65 to 90 u0041 to u005A 'a' to 'z' 97 to 122 u0061 to u007A
  • 152.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Escape Sequences for Special Characters Escape Sequence Name Unicode Code Decimal Value b Backspace u0008 8 t Tab u0009 9 n Linefeed u000A 10 f Formfeed u000C 12 r Carriage Return u000D 13 Backslash u005C 92 ” Double Quote u0022 34
  • 153.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Appendix B: ASCII Character Set (1 of 2) ASCII Character Set is a subset of the Unicode from u0000 to u007f TABLE B.1 ASCII Character Set in the Decimal Index Blank 0 1 2 3 4 5 6 7 8 9 0 nul soh stx etx eot enq ack bel bs ht 1 nl vt ff cr so si dle dcl dc2 dc3 2 dc4 nak syn etb can em sub esc fs gs 3 rs us sp ! “ # $ % & ‘ 4 ( ) * + , - . / 0 1 5 2 3 4 5 6 7 8 9 : ; 6 < = > ? @ A B C D E 7 F G H I J K L M N O 8 P Q R S T U V W X Y 9 Z [ ] ^ _ ` a b c 10 d e f g h i j k l m 11 n o p q r s t u v w 12 x y z { | } ~ del Blank Blank
  • 154.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Appendix B: ASCII Character Set (2 of 2) ASCII Character Set is a subset of the Unicode from u0000 to u007f TABLE B.2 ASCII Character Set in the Hexadecimal Index Blank 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 nul soh stx etx eot enq ack bel bs ht nl vt ff cr so si 1 dle dcl dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us 2 sp ! “ # $ % & ‘ ( ) * + , - . / 3 0 1 2 3 4 5 6 7 8 9 : ; < = > ? 4 @ A B C D E F G H I J K L M N O 5 P Q R S T U V W X Y Z [ ] ^ _ 6 ‘ a b c d e f g h i j k l m n o 7 p q r s t u v w x y z { | } ~ del
  • 155.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Casting between char and Numeric Types int i = 'a'; // Same as int i = (int)'a'; char c = 97; // Same as char c = (char)97;
  • 156.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Comparing and Testing Characters if (ch >= 'A' && ch <= 'Z') System.out.println(ch + " is an uppercase letter"); else if (ch >= 'a' && ch <= 'z') System.out.println(ch + " is a lowercase letter"); else if (ch >= '0' && ch <= '9') System.out.println(ch + " is a numeric character");
  • 157.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Methods in the Character Class Method Description isDigit(ch) Returns true if the specified character is a digit. isLetter(ch) Returns true if the specified character is a letter. isLetterOfDigit(ch) Returns true if the specified character is a letter or digit. isLowerCase(ch) Returns true if the specified character is a lowercase letter. isUpperCase(ch) Returns true if the specified character is an uppercase letter. toLowerCase(ch) Returns the lowercase of the specified character. toUpperCase(ch) Returns the uppercase of the specified character.
  • 158.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The String Type The char type only represents one character. To represent a string of characters, use the data type called String. For example, String message = "Welcome to Java"; String is actually a predefined class in the Java library just like the System class and Scanner class. The String type is not a primitive type. It is known as a reference type. Any Java class can be used as a reference type for a variable. Reference data types will be thoroughly discussed in Chapter 9, “Objects and Classes.” For the time being, you just need to know how to declare a String variable, how to assign a string to the variable, how to concatenate strings, and to perform simple operations for strings.
  • 159.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Simple Methods for String Objects (1 of 2) Method Description length() Returns the number of characters in this string. charAt(index) Returns the character at the specified index from this string. concat(s1) Returns a new string that concatenates this string with string s1. toUpperCase() Returns a new string with all letters in uppercase. toLowerCase() Returns a new string with all letters in lowercase. trim() Returns a new string with whitespace characters trimmed on both sides.
  • 160.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Simple Methods for String Objects (2 of 2) Strings are objects in Java. The methods in the preceding table can only be invoked from a specific string instance. For this reason, these methods are called instance methods. A non-instance method is called a static method. A static method can be invoked without using an object. All the methods defined in the Math class are static methods. They are not tied to a specific object instance. The syntax to invoke an instance method is referenceVariable.methodName(arguments).
  • 161.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Getting String Length String message = "Welcome to Java"; System.out.println("The length of " + message + " is " + message.length());
  • 162.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Getting Characters from a String String message = "Welcome to Java"; System.out.println("The first character in message is " + message.charAt(0));
  • 163.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Converting Strings "Welcome".toLowerCase() returns a new string, welcome. "Welcome".toUpperCase() returns a new string, WELCOME. " Welcome ".trim() returns a new string, Welcome.
  • 164.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved String Concatenation String s3 = s1.concat(s2); or String s3 = s1 + s2; // Three strings are concatenated String message = "Welcome " + "to " + "Java"; // String Chapter is concatenated with number 2 String s = "Chapter" + 2; // s becomes Chapter2 // String Supplement is concatenated with character B String s1 = "Supplement" + 'B'; // s1 becomes SupplementB
  • 165.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Reading a String From the Console Scanner input = new Scanner(System.in); System.out.print("Enter three words separated by spaces: "); String s1 = input.next(); String s2 = input.next(); String s3 = input.next(); System.out.println("s1 is " + s1); System.out.println("s2 is " + s2); System.out.println("s3 is " + s3);
  • 166.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Reading a Character From the Console Scanner input = new Scanner(System.in); System.out.print("Enter a character: "); String s = input.nextLine(); char ch = s.charAt(0); System.out.println("The character entered is " + ch);
  • 167.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Comparing Strings Method Description equals(s1) Returns true if this string is equal to string s1. equalsIgnoreCase(s1) Returns true if this string is equal to string s1; it is case insensitive. compareTo(s1) Returns an integer greater than 0, equal to 0, or less than 0 to indicate whether this string is greater than, equal to, or less than s1. compareToIgnoreCase(s1) Same as compareTo except that the comparison is case insensitive. startsWith(prefix) Returns true if this string starts with the specified prefix. endsWith(suffix) Returns true if this string ends with the specified suffix. OrderTwoCities
  • 168.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Obtaining Substrings Method Description substring(beginIndex) Returns this string’s substring that begins with the character at the specified beginIndex and extends to the end of the string, as shown in Figure 4.2. substring(beginIndex, endIndex) Returns this string’s substring that begins at the specified beginIndex and extends to the character at index endIndex – 1, as shown in Figure 9.6. Note that the character at endIndex is not part of the substring.
  • 169.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Finding a Character or a Substring in a String (1 of 2) Method Description indexOf(ch) Returns the index of the first occurrence of ch in the string. Returns -1 if not matched. indexOf(ch, fromIndex) Returns the index of the first occurrence of ch after fromIndex in the string. Returns -1 if not matched. indexOf(s) Returns the index of the first occurrence of string s in this string. Returns -1 if not matched. indexOf(s, fromIndex) Returns the index of the first occurrence of string s in this string after fromIndex. Returns -1 if not matched. lastIndexOf(ch) Returns the index of the last occurrence of ch in the string. Returns -1 if not matched. lastIndexOf(ch, fromIndex) Returns the index of the last occurrence of ch before fromIndex in this string. Returns -1 if not matched. lastIndexOf(s) Returns the index of the last occurrence of string s. Returns -1 if not matched. lastIndexOf(s, fromIndex) Returns the index of the last occurrence of string s before fromIndex. Returns -1 if not matched.
  • 170.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Finding a Character or a Substring in a String (2 of 2) int k = s.indexOf(' '); String firstName = s.substring(0, k); String lastName = s.substring(k + 1);
  • 171.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Conversion between Strings and Numbers int intValue = Integer.parseInt(intString); double doubleValue = Double.parseDouble(doubleString); String s = number + "";
  • 172.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Guessing Birthday The program can guess your birth date. Run to see how it works. GuessBirthday
  • 173.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Mathematics Basis for the Game 19 is 10011 in binary. 7 is 111 in binary. 23 is 11101 in binary 10000 10 + 1 10011 00110 10 + 1 00111 19 7 10000 1000 100 + 1 11101 23
  • 174.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Case Study: Converting a Hexadecimal Digit to a Decimal Value Write a program that converts a hexadecimal digit into a decimal value. HexDigit2Dec
  • 175.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Case Study: Revising the Lottery Program Using Strings A problem can be solved using many different approaches. This section rewrites the lottery program in Listing 3.7 using strings. Using strings simplifies this program. LotteryUsingStrings
  • 176.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Formatting Output Use the printf statement. System.out.printf(format, items); Where format is a string that may consist of substrings and format specifiers. A format specifier specifies how an item should be displayed. An item may be a numeric value, character, boolean value, or a string. Each specifier begins with a percent sign.
  • 177.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Frequently-Used Specifiers Specifier Output Example %b a boolean value true or false %c a character 'a' %d a decimal integer 200 %f a floating-point number 45.460000 %e a number in standard scientific notation 4.556000e+01 %s a string "Java is cool" int count = 5; double amount = 45.56; System.out.printf("count is %d and amount is %f", count, amount); display count is 5 and amount is 45.560000 items
  • 178.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved FormatDemo The example gives a program that uses printf to display a table. FormatDemo
  • 179.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved 179 Text blocks became a standard feature since Java 15. It enables you to form a multi-line string. Here is an example of a text block: String tb = """ Java Python C++"""; System.out.println(tb); The code displays three lines Java Python C++ A text block contains multiple line. The first line starts with three double quotation marks (""") followed by space characters. The last line ends with three double quotation marks ("""). Text Blocks
  • 180.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved 180 You can use indentation in a text block. To achieve this, the compiler first removes the maximum left common space characters for all lines. For example, the maximum common left space characters for all lines in the following text block is 2, because there are two leading space characters before “Java”. String tb = """ Java Python C++"""; After removing two leading space characters from each line, the resulting string is Java Python C++ After removing the maximum common left space characters, the indentation of the text block is preserved. Indentation in Text Blocks
  • 181.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved 181 Indentation in Text Blocks: ending """ Note if the ending """ is on a separate line by itself, its leading spaces are counted in the maximum common left space. For example, in the following code, String tb = """ Java Python C++ """; The maximum common left space is 0, because there are no space before the ending """. The resulting string will be Java Python C++
  • 182.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved 182 Right Trailing Space The right trailing space are trimmed by default. If you want to keep right trailing space, use s. For example, the following code keep three right space characters after “Python”. String tb = """ Java Python s C++"""; Note that there are two spaces after Python and before s. Including s, there will be three spaces after “Python”.
  • 183.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved 183 Escape Characters You used s escape character for a space. You can also use other escape characters in needed. For example, for the following text block: String tb = """ Java tPythonn C++"""; The resulting string is Java Python C++ The space before “Python” is due to the tab character (t). The space line after “Python” is due to the new line character “n”.
  • 184.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved 184 """ in Text Block as Literal If you need to put """ into the text block, you can use """. For example, for the following text block: String tb = """ Java""" Python C++"""; The resulting string is Java""" Python C++
  • 185.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved 185 New String Methods As part of the new feature on text blocks, several new String methods are introduced. You can use the stripIndent() to remove the maximum common left space from a multi-line string in the same way as a text block is processed. You can use the formatted(args) method to format a string. For example, for the following code: String tb = """ Product: %s Price: $%.2f""".formatted("Salt", 4.52); The resulting string is Produce: Salt Price: $4.52
  • 186.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.
  • 187.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introduction to Java Programming and Data Structures Thirteenth Edition Chapter 5 Loops Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 188.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Motivations Suppose that you need to print a string (e.g., "Welcome to Java!") a hundred times. It would be tedious to have to write the following statement a hundred times: System.out.println("Welcome to Java!"); So, how do you solve this problem?
  • 189.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Opening Problem Problem:
  • 190.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introducing while Loops int count = 0; while (count < 100) { System.out.println("Welcome to Java"); count++; }
  • 191.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (1 of 2) 5.1 To write programs for executing statements repeatedly using a while loop (§5.2). 5.2 To write loops for the guessing number problem (§5.3). 5.3 To follow the loop design strategy to develop loops (§5.4). 5.4 To control a loop with a sentinel value (§5.4). 5.5 To obtain large input from a file using input redirection rather than typing from the keyboard (§5.5). 5.6 To write loops using do-while statements (§5.6). 5.7 To write loops using for statements (§5.7).
  • 192.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (2 of 2) 5.8 To discover the similarities and differences of three types of loop statements (§5.8). 5.9 To write nested loops (§5.9). 5.10 To learn the techniques for minimizing numerical errors (§5.10). 5.11 To learn loops from a variety of examples (GCD, FutureTuition, Dec2Hex) (§5.11). 5.12 To implement program control with break and continue (§5.12). 5.13 To process characters in a string using a loop in a case study for checking palindrome (§5.13). 5.14 To write a program that displays prime numbers (§5.14).
  • 193.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved while Loop Flow Chart
  • 194.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace while Loop (1 of 9)
  • 195.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace while Loop (2 of 9)
  • 196.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace while Loop (3 of 9)
  • 197.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace while Loop (4 of 9)
  • 198.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace while Loop (5 of 9)
  • 199.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace while Loop (6 of 9)
  • 200.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace while Loop (7 of 9)
  • 201.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace while Loop (8 of 9)
  • 202.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace while Loop (9 of 9)
  • 203.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Repeat Addition Until Correct Recall that Listing 3.1 AdditionQuiz.java gives a program that prompts the user to enter an answer for a question on addition of two single digits. Using a loop, you can now rewrite the program to let the user enter a new answer until it is correct. RepeatAdditionQuiz
  • 204.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Guessing Numbers Write a program that randomly generates an integer between 0 and 100, inclusive. The program prompts the user to enter a number continuously until the number matches the randomly generated number. For each user input, the program tells the user whether the input is too low or too high, so the user can choose the next input intelligently. Here is a sample run: GuessNumberOneTime GuessNumber
  • 205.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: An Advanced Math Learning Tool The Math subtraction learning tool program generates just one question for each run. You can use a loop to generate questions repeatedly. This example gives a program that generates five questions and reports the number of the correct answers after a student answers all five questions. SubtractionQuizLoop
  • 206.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Ending a Loop with a Sentinel Value Often the number of times a loop is executed is not predetermined. You may use an input value to signify the end of the loop. Such a value is known as a sentinel value. Write a program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input. SentinelValue
  • 207.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Caution (1 of 3) Don’t 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 inaccurate results. Consider the following code for computing 1 + 0.9 + 0.8 + ... + 0.1: double item = 1; double sum = 0; while (item != 0) { // No guarantee item will be 0 sum += item; item −= 0.1; } System.out.println(sum);
  • 208.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved do-while Loop do { // Loop body; Statement(s); } while (loop-continuation-condition);
  • 209.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved for Loops
  • 210.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace for Loop (1 to 10)
  • 211.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace for Loop (2 to 10)
  • 212.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace for Loop (3 to 10)
  • 213.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace for Loop (4 to 10)
  • 214.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace for Loop (5 to 10)
  • 215.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace for Loop (6 to 10)
  • 216.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace for Loop (7 to 10)
  • 217.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace for Loop (8 to 10)
  • 218.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace for Loop (9 to 10)
  • 219.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace for Loop (10 to 10)
  • 220.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Note (1 of 2) The initial-action in a for loop can be a list of zero or more comma-separated expressions. The action-after-each- iteration in a for loop can be a list of zero or more comma- separated statements. Therefore, the following two for loops are correct. They are rarely used in practice, however. for (int i = 1; i < 100; System.out.println(i++)); for (int i = 0, j = 0; (i + j < 10); i++, j++) { // Do something }
  • 221.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Note (2 of 2) If the loop-continuation-condition in a for loop is omitted, it is implicitly true. Thus the statement given below in (a), which is an infinite loop, is correct. Nevertheless, it is better to use the equivalent loop in (b) to avoid confusion: for ( ; ; ) { // Do something } (a) Equivalent while (true) { // Do something } (b)
  • 222.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Caution (2 of 3) Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below:
  • 223.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Caution (3 of 3) Similarly, the following loop is also wrong: In the case of the do loop, the following semicolon is needed to end the loop.
  • 224.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Which Loop to Use? The three forms of loop statements, while, do-while, and for, are expressively equivalent; that is, you can write a loop in any of these three forms. For example, a while loop in (a) in the following figure can always be converted into the following for loop in (b): while (loop-continuation-condition) { // Loop body } (a) Equivalent (b) for ( ; loop-continuation-condition; ) { // Loop body } A for loop in (a) in the following figure can generally be converted into the following while loop in (b) except in certain special cases (see Review Question 3.19 for one of them): for (initial-action; loop-continuation-condition; action-after-each-iteration) { // Loop body; } (a) Equivalent (b) initial-action; while (loop-continuation-condition) { // Loop body; action-after-each-iteration; }
  • 225.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Recommendations Use the one that is most intuitive and comfortable for you. In general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message 100 times. A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0. A do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition.
  • 226.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Nested Loops Problem: Write a program that uses nested for loops to print a multiplication table. MultiplicationTable
  • 227.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Minimizing Numerical Errors Numeric errors involving floating-point numbers are inevitable. This section discusses how to minimize such errors through an example. Here is an example that sums a series that starts with 0.01 and ends with 1.0. The numbers in the series will increment by 0.01, as follows: 0.01 + 0.02 + 0.03 and so on. TestSum
  • 228.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Finding the Greatest Common Divisor Problem: Write a program that prompts the user to enter two positive integers and finds their greatest common divisor. Solution: Suppose you enter two integers 4 and 2, their greatest common divisor is 2. Suppose you enter two integers 16 and 24, their greatest common divisor is 8. So, how do you find the greatest common divisor? Let the two input integers be n1 and n2. You know number 1 is a common divisor, but it may not be the greatest commons divisor. So you can check whether k (for k = 2, 3, 4, and so on) is a common divisor for n1 and n2, until k is greater than n1 or n2. GreatestCommonDivisor
  • 229.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Predicting the Future Tuition Problem: Suppose that the tuition for a university is $10,000 this year and tuition increases 7% every year. In how many years will the tuition be doubled? FutureTuition
  • 230.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Predicating the Future Tuition double tuition = 10000; int year = 0 // Year 0 tuition = tuition * 1.07; year++; // Year 1 tuition = tuition * 1.07; year++; // Year 2 tuition = tuition * 1.07; year++; // Year 3 ...
  • 231.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Case Study: Converting Decimals to Hexadecimals Hexadecimals are often used in computer systems programming (see Appendix F for an introduction to number systems). How do you convert a decimal number to a hexadecimal number? To convert a decimal number d to a hexadecimal number is to find the hexadecimal digits 1 2 2 1 0 , , , , , , and n n n h h h h h h   such that 1 2 2 1 0 1 2 2 1 0 16 16 16 16 16 16 n n n n n n d h h h h h h                  These hexadecimal digits can be found by successively dividing d by 16 until the quotient is 0. The remainders are 0 1 2 2 1 , , , , , , and . n n n h h h h h h   Dec2Hex
  • 232.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Monte Carlo Simulation The Monte Carlo simulation refers to a technique that uses random numbers and probability to solve problems. This method has a wide range of applications in computational mathematics, physics, chemistry, and finance. This section gives an example of using the Monto Carlo simulation for estimating .  x y 1 -1 1 -1 circleArea / squareArea / 4.    can be approximated as 4 * numberOfHits / numberOfTrials MonteCarloSimulation
  • 233.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Using break and continue Examples for using the break and continue keywords: • TestBreak.java TestBreak • TestContinue.java TestContinue
  • 234.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved break public class TestBreak { public static void main(String[] args) { int sum = 0; int number = 0; while (number < 20) { number++; sum += number; if (sum >= 100) break; } System.out.println("The number is " + number); System.out.println("The sum is " + sum); } }
  • 235.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved continue public class TestContinue { public static void main(String[] args) { int sum = 0; int number = 0; while (number < 20) { number++; if (number == 10 || number == 11) continue; sum += number; } System.out.println("The sum is " + sum); } }
  • 236.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Guessing Number Problem Revisited Here is a program for guessing a number. You can rewrite it using a break statement. GuessNumberUsingBreak
  • 237.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Checking Palindrome A string is a palindrome if it reads the same forward and backward. The words “mom,” “dad,” and “noon,” for instance, are all palindromes. The problem is to write a program that prompts the user to enter a string and reports whether the string is a palindrome. One solution is to check whether the first character in the string is the same as the last character. If so, check whether the second character is the same as the second-to- last character. This process continues until a mismatch is found or all the characters in the string are checked, except for the middle character if the string has an odd number of characters. String s low high a b c d e f g n h g f e d c b a Palindrome
  • 238.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Displaying Prime Numbers Problem: Write a program that displays the first 50 prime numbers in five lines, each of which contains 10 numbers. An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not. Solution: The problem can be broken into the following tasks: • For number = 2, 3, 4, 5, 6, ..., test whether the number is prime. • Determine whether a given number is prime. • Count the prime numbers. • Print each prime number, and print 10 numbers per line. PrimeNumber
  • 239.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Debugging Loops in IDE Tools Supplements II.C, II.E, and II.G.
  • 240.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.
  • 241.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introduction to Java Programming and Data Structures Thirteenth Edition Chapter 6 Methods Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 242.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
  • 243.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem (1 of 2) int sum = 0; for (int i = 1; i <= 10; i++) sum += i; System.out.println("Sum from 1 to 10 is " + sum); sum = 0; for (int i = 20; i <= 30; i++) sum += i; System.out.println("Sum from 20 to 30 is " + sum); sum = 0; for (int i = 35; i <= 45; i++) sum += i; System.out.println("Sum from 35 to 45 is " + sum);
  • 244.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem (2 of 2)
  • 245.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Solution MethodDemo
  • 246.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives 6.1 To define methods with formal parameters (§6.2). 6.2 To invoke methods with actual parameters (i.e., arguments) (§6.2). 6.3 To define methods with a return value (§6.3). 6.4 To define methods without a return value (§6.4). 6.5 To pass arguments by value (§6.5). 6.6 To develop reusable code that is modular, easy to read, easy to debug, and easy to maintain (§6.6). 6.7 To write a method that converts hexadecimals to decimals (§6.7). 6.8 To use method overloading and understand ambiguous overloading (§6.8). 6.9 To determine the scope of variables (§6.9). 6.10 To apply the concept of method abstraction in software development (§6.10). 6.11 To design and implement methods using stepwise refinement (§6.11).
  • 247.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Defining Methods (1 of 2) A method is a collection of statements that are grouped together to perform an operation. public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } Define a method Invoke a method int z = max(x, y); actual parameters (arguments)
  • 248.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Defining Methods (2 of 2) A method is a collection of statements that are grouped together to perform an operation. public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } modifier return value type method name formal parameters return value method body method header parameter list Define a method Invoke a method int z = max(x, y); actual parameters (arguments) method signature
  • 249.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Method Signature Method signature is the combination of the method name and the parameter list.
  • 250.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Formal Parameters The variables defined in the method header are known as formal parameters.
  • 251.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Actual Parameters When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument.
  • 252.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Return Value Type A method may return a value. The returnValueType is the data type of the value the method returns. If the method does not return a value, the returnValueType is the keyword void. For example, the returnValueType in the main method is void.
  • 253.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Calling Methods (1 of 2) Testing the max method This program demonstrates calling a method max to return the largest of the int values TestMax
  • 254.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Calling Methods (2 of 2) pass the value of i pass the value of j
  • 255.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Method Invocation (1 of 10)
  • 256.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Method Invocation (2 of 10)
  • 257.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Method Invocation (3 of 10)
  • 258.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Method Invocation (4 of 10)
  • 259.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Method Invocation (5 of 10)
  • 260.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Method Invocation (6 of 10)
  • 261.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Method Invocation (7 of 10)
  • 262.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Method Invocation (8 of 10)
  • 263.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Method Invocation (9 of 10)
  • 264.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Method Invocation (10 of 10)
  • 265.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved CAUTION A return statement is required for a value-returning method. The method shown below in (a) is logically correct, but it has a compilation error because the Java compiler thinks it possible that this method does not return any value. public static int sign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return –1; } (a) Should be (b) public static int sign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else return –1; } To fix this problem, delete if (n < 0) in (a), so that the compiler will see a return statement to be reached regardless of how the if statement is evaluated.
  • 266.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Reuse Methods from Other Classes Note: One of the benefits of methods is for reuse. The max method can be invoked from any class besides TestMax. If you create a new class Test, you can invoke the max method using ClassName.methodName (e.g., TestMax.max).
  • 267.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Call Stacks
  • 268.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Call Stack (1 of 10)
  • 269.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Call Stack (2 of 10)
  • 270.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Call Stack (3 of 10)
  • 271.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Call Stack (4 of 10)
  • 272.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Call Stack (5 of 10)
  • 273.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Call Stack (6 of 10)
  • 274.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Call Stack (7 of 10)
  • 275.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Call Stack (8 of 10)
  • 276.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Call Stack (9 of 10)
  • 277.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Call Stack (10 of 10)
  • 278.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved void Method Example This type of method does not return a value. The method performs some actions. TestVoidMethod TestReturnGradeMethod
  • 279.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Passing Parameters public static void nPrintln(String message, int n) { for (int i = 0; i < n; i++) System.out.println(message); } Suppose you invoke the method using nPrintln(“Welcome to Java”, 5); What is the output? Suppose you invoke the method using nPrintln(“Computer Science”, 15); What is the output? Can you invoke the method using nPrintln(15, “Computer Science”);
  • 280.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Pass by Value (1 of 3) This program demonstrates passing values to the methods. Increment
  • 281.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Pass by Value (2 of 3) Testing Pass by value This program demonstrates passing values to the methods. TestPassByValue
  • 282.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Pass by Value (3 of 3)
  • 283.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Modularizing Code Methods can be used to reduce redundant coding and enable code reuse. Methods can also be used to modularize code and improve the quality of the program. GreatestCommonDivisorMethod PrimeNumberMethod
  • 284.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Case Study: Converting Hexadecimals to Decimals Write a method that converts a hexadecimal number into a decimal number.         ABCD A *16 ^3 B *16 ^ 2 C *16 ^1 D *16 ^0 A *16 B *16 C *16 D 10 *16 11 *16 12 *16 13 ?              Hex2Dec
  • 285.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Overloading Methods Overloading the max Method public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; } TestMethodOverloading
  • 286.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Ambiguous Invocation (1 of 2) Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compile error.
  • 287.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Ambiguous Invocation (2 of 2) public class AmbiguousOverloading { public static void main(String[] args) { System.out.println(max(1, 2)); } public static double max(int num1, double num2) { if (num1 > num2) return num1; else return num2; } public static double max(double num1, int num2) { if (num1 > num2) return num1; else return num2; } }
  • 288.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Scope of Local Variables (1 of 6) A local variable: a variable defined inside a method. Scope: the part of the program where the variable can be referenced. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used.
  • 289.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Scope of Local Variables (2 of 6) You can declare a local variable with the same name multiple times in different non-nesting blocks in a method, but you cannot declare a local variable twice in nested blocks.
  • 290.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Scope of Local Variables (3 of 6) A variable declared in the initial action part of a for loop header has its scope in the entire loop. But a variable declared inside a for loop body has its scope limited in the loop body from its declaration and to the end of the block that contains the variable. public static void method1() { . . for (int i = 1; i < 10; i++) { . . int j; . . . } } The scope of j The scope of i
  • 291.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Scope of Local Variables (4 of 6) public static void method1() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { x += i; } for (int i = 1; i < 10; i++) { y += i; } } It is fine to declare i in two non-nesting blocks public static void method2() { int i = 1; int sum = 0; for (int i = 1; i < 10; i++) { sum += i; } } It is wrong to declare i in two nesting blocks
  • 292.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Scope of Local Variables (5 of 6) // Fine with no errors public static void correctMethod() { int x = 1; int y = 1; // i is declared for (int i = 1; i < 10; i++) { x += i; } // i is declared again for (int i = 1; i < 10; i++) { y += i; } }
  • 293.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Scope of Local Variables (6 of 6) // With errors public static void incorrectMethod() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { int x = 0; x += i; } }
  • 294.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Method Abstraction You can think of the method body as a black box that contains the detailed implementation for the method. Method Header Method body Black Box Optional arguments for Input Optional return value
  • 295.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Benefits of Methods • Write a method once and reuse it anywhere. • Information hiding. Hide the implementation from the user. • Reduce complexity.
  • 296.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Case Study: Generating Random Characters (1 of 4) 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. As introduced in Section 4.3, each character has a unique Unicode between 0 and FFFF in hexadecimal (65535 in decimal). To generate a random character is to generate a random integer between 0 and 65535 using the following expression: (note that since 0 <= Math.random() < 1.0, you have to add 1 to 65535.) (int)(Math.random() * (65535 + 1))
  • 297.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Case Study: Generating Random Characters (2 of 4) Now let us consider how to generate a random lowercase letter. The Unicode for lowercase letters are consecutive integers starting from the Unicode for 'a', then for 'b', 'c', ..., and 'z'. The Unicode for 'a' is (int)'a' So, a random integer between (int)'a' and (int)'z' is (int)((int)'a' + Math.random() * ((int)'z' - (int)'a' + 1)
  • 298.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Case Study: Generating Random Characters (3 of 4) As discussed in Chapter 2, all numeric operators can be applied to the char operands. The char operand is cast into a number if the other operand is a number or a character. So, the preceding expression can be simplified as follows: 'a' + Math.random() * ('z' - 'a' + 1) So a random lowercase letter is (char)('a' + Math.random() * ('z' - 'a' + 1))
  • 299.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Case Study: Generating Random Characters (4 of 4) To generalize the foregoing discussion, a random character between any two characters ch1 and ch2 with ch1 < ch2 can be generated as follows: (char)(ch1 + Math.random() * (ch2 – ch1 + 1))
  • 300.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The RandomCharacter Class (1 of 2) // RandomCharacter.java: Generate random characters public class RandomCharacter { /** Generate a random character between ch1 and ch2 */ public static char getRandomCharacter(char ch1, char ch2) { return (char)(ch1 + Math.random() * (ch2 - ch1 + 1)); } /** Generate a random lowercase letter */ public static char getRandomLowerCaseLetter() { return getRandomCharacter('a', 'z'); } /** Generate a random uppercase letter */ public static char getRandomUpperCaseLetter() { return getRandomCharacter('A', 'Z'); } RandomCharacter TestRandomCharacter
  • 301.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The RandomCharacter Class (2 of 2) /** Generate a random digit character */ public static char getRandomDigitCharacter() { return getRandomCharacter('0', '9'); } /** Generate a random character */ public static char getRandomCharacter() { return getRandomCharacter('u0000', 'uFFFF'); } } RandomCharacter TestRandomCharacter
  • 302.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Stepwise Refinement (Optional) The concept of method abstraction can be applied to the process of developing programs. When writing a large program, you can use the “divide and conquer” strategy, also known as stepwise refinement, to decompose it into subproblems. The subproblems can be further decomposed into smaller, more manageable problems.
  • 303.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved PrintCalender Case Study Let us use the PrintCalendar example to demonstrate the stepwise refinement approach. PrintCalendar
  • 304.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Design Diagram (1 of 7) printCalendar (main)
  • 305.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Design Diagram (2 of 7) printCalendar (main) readInput printMonth
  • 306.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Design Diagram (3 of 7) printCalendar (main) readInput printMonth printMonthTitle printMonthBody
  • 307.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Design Diagram (4 of 7) printCalendar (main) readInput printMonth printMonthTitle printMonthBody getMonthName
  • 308.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Design Diagram (5 of 7) printCalendar (main) readInput printMonth getStartDay printMonthTitle printMonthBody getNumOfDaysInMonth getMonthName
  • 309.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Design Diagram (6 of 7) printCalendar (main) readInput printMonth getStartDay printMonthTitle printMonthBody getTotalNumOfDays getNumOfDaysInMonth getMonthName
  • 310.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Design Diagram (7 of 7) printCalendar (main) readInput printMonth getStartDay printMonthTitle printMonthBody getTotalNumOfDays getNumOfDaysInMonth getMonthName isLeapYear
  • 311.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Implementation: Top-Down Top-down approach is to implement one method in the structure chart at a time from the top to the bottom. Stubs can be used for the methods waiting to be implemented. A stub is a simple but incomplete version of a method. The use of stubs enables you to test invoking the method from a caller. Implement the main method first and then use a stub for the printMonth method. For example, let printMonth display the year and the month in the stub. Thus, your program may begin like this: A Skeleton for printCalendar
  • 312.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Implementation: Bottom-Up Bottom-up approach is to implement one method in the structure chart at a time from the bottom to the top. For each method implemented, write a test program to test it. Both top-down and bottom-up methods are fine. Both approaches implement the methods incrementally and help to isolate programming errors and makes debugging easy. Sometimes, they can be used together.
  • 313.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Benefits of Stepwise Refinement Simpler Program Reusing Methods Easier Developing, Debugging, and Testing Better Facilitating Teamwork
  • 314.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.
  • 315.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introduction to Java Programming and Data Structures Thirteenth Edition Chapter 7 Single-Dimensional Arrays Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 316.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average.
  • 317.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (1 of 2) 7.1 To describe why arrays are necessary in programming (§7.1). 7.2 To declare array reference variables and create arrays (§§7.2.1– 7.2.2). 7.3 To obtain array size using arrayRefVar.length and know default values in an array (§7.2.3). 7.4 To access array elements using indexes (§7.2.4). 7.5 To declare, create, and initialize an array using an array initializer (§7.2.5). 7.6 To program common array operations (displaying arrays, summing all elements, finding the minimum and maximum elements, random shuffling, and shifting elements) (§7.2.6). 7.7 To simplify programming using the foreach loops (§7.2.7).
  • 318.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (2 of 2) 7.8 To apply arrays in application development (AnalyzeNumbers, DeckOfCards) (§§7.3–7.4). 7.9 To copy contents from one array to another (§7.5). 7.10 To develop and invoke methods with array arguments and return values (§§7.6–7.8). 7.11 To define a method with a variable-length argument list (§7.9). 7.12 To search elements using the linear (§7.10.1) or binary (§7.10.2) search algorithm. 7.13 To sort an array using the selection sort approach (§7.11). 7.14 To use the methods in the java.util.Arrays class (§7.12). 7.15 To pass arguments to the main method from the command line (§7.13).
  • 319.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introducing Arrays Array is a data structure that represents a collection of the same types of data.
  • 320.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Declaring Array Variables • datatype[] arrayRefVar; Example: double[] myList; • datatype arrayRefVar[]; // This style is allowed, but not preferred Example: double myList[];
  • 321.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Creating Arrays arrayRefVar = new datatype[arraySize]; Example: myList = new double[10]; myList[0] references the first element in the array. myList[9] references the last element in the array.
  • 322.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Declaring and Creating in One Step • datatype[] arrayRefVar = new datatype[arraySize]; double[] myList = new double[10]; • datatype arrayRefVar[] = new datatype[arraySize]; double myList[] = new double[10];
  • 323.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Length of an Array Once an array is created, its size is fixed. It cannot be changed. You can find its size using arrayRefVar.length For example, myList.length returns 10
  • 324.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Default Values When an array is created, its elements are assigned the default value of 0 for the numeric primitive data types, 'u0000' for char types, and false for boolean types.
  • 325.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Indexed Variables The array elements are accessed through the index. The array indices are 0-based, i.e., it starts from 0 to arrayRefVar.length-1. In the example in Figure 6.1, myList holds ten double values and the indices are from 0 to 9. Each element in the array is represented using the following syntax, known as an indexed variable: arrayRefVar[index];
  • 326.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Using Indexed Variables 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 value in myList[0] and myList[1] to myList[2]. myList[2] = myList[0] + myList[1];
  • 327.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Array Initializers • Declaring, creating, initializing in one step: double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand syntax must be in one statement.
  • 328.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Declaring, Creating, Initializing Using the Shorthand Notation double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand notation is equivalent to the following statements: double[] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;
  • 329.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved CAUTION Using the shorthand notation, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error. For example, the following is wrong: double[] myList; myList = {1.9, 2.9, 3.4, 3.5};
  • 330.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Program with Arrays (1 of 16)
  • 331.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Program with Arrays (2 of 16)
  • 332.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Program with Arrays (3 of 16)
  • 333.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Program with Arrays (4 of 16)
  • 334.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Program with Arrays (5 of 16)
  • 335.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Program with Arrays (6 of 16)
  • 336.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Program with Arrays (7 of 16)
  • 337.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Program with Arrays (8 of 16)
  • 338.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Program with Arrays (9 of 16)
  • 339.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Program with Arrays (10 of 16)
  • 340.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Program with Arrays (11 of 16)
  • 341.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Program with Arrays (12 of 16)
  • 342.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Program with Arrays (13 of 16)
  • 343.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Program with Arrays (14 of 16)
  • 344.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Program with Arrays (15 of 16)
  • 345.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Program with Arrays (16 of 16)
  • 346.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Processing Arrays See the examples in the text. 1. (Initializing arrays with input values) 2. (Initializing arrays with random values) 3. (Printing arrays) 4. (Summing all elements) 5. (Finding the largest element) 6. (Finding the smallest index of the largest element) 7. (Random shuffling) 8. (Shifting elements)
  • 347.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Initializing Arrays With Input Values java.util.Scanner input = new java.util.Scanner(System.in); System.out.print("Enter " + myList.length + " values: "); for (int i = 0; i < myList.length; i++) myList[i] = input.nextDouble();
  • 348.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Initializing Arrays With Random Values for (int i = 0; i < myList.length; i++) { myList[i] = Math.random() * 100; }
  • 349.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Printing Arrays for (int i = 0; i < myList.length; i++) { System.out.print(myList[i] + " "); }
  • 350.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Summing All Elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; }
  • 351.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Finding the Largest Element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; }
  • 352.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Random Shuffling for (int i = 0; i < myList.length - 1; i++) { // Generate an index j randomly int j = (int)(Math.random() * myList.length); // Swap myList[i] with myList[j] double temp = myList[i]; myList[i] = myList[j]; myList[j] = temp; } myList [0] [1] . . . A random index i swap . . . [i] [j]
  • 353.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Shifting Elements
  • 354.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Enhanced for Loop (for-each loop) JDK 1.5 introduced a new for loop that enables you to traverse the complete array sequentially without using an index variable. For example, the following code displays all elements in the array myList: for (double value: myList) System.out.println(value); In general, the syntax is for (elementType value: arrayRefVar) { // Process the value } You still have to use an index variable if you wish to traverse the array in a different order or change the elements in the array.
  • 355.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Analyze Numbers Read one hundred numbers, compute their average, and find out how many numbers are above the average. AnalyzeNumbers
  • 356.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Deck of Cards (1 of 4) The problem is to write a program that picks four cards randomly from a deck of 52 cards. All the cards can be represented using an array named deck, filled with initial values 0 to 51, as follows: int[] deck = new int[52]; // Initialize cards for (int i = 0; i < deck.length; i++) deck[i] = i; DeckOfCards
  • 357.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Deck of Cards (2 of 4)
  • 358.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Deck of Cards (3 of 4) DeckOfCards
  • 359.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Deck of Cards (4 of 4) This problem builds a foundation for future more interesting and realistic applications: See Exercise 20.15. https://liveexample.pearsonc mg.com/dsanimation/24Point .html
  • 360.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copying Arrays (1 of 2) Often, in a program, you need to duplicate an array or a part of an array. In such cases you could attempt to use the assignment statement (=), as follows: list2 = list1;
  • 361.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copying Arrays (2 of 2) Using a loop: int[] sourceArray = {2, 3, 1, 5, 10}; int[] targetArray = new int[sourceArray.length]; for (int i = 0; i < sourceArrays.length; i++) targetArray[i] = sourceArray[i];
  • 362.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The arraycopy Utility arraycopy(sourceArray, src_pos, targetArray, tar_pos, length); Example: System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
  • 363.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Passing Arrays to Methods
  • 364.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Anonymous Array The statement printArray(new int[]{3, 1, 2, 6, 4, 2}); creates an array using the following syntax: new dataType[]{literal0, literal1, ..., literalk}; There is no explicit reference variable for the array. Such array is called an anonymous array.
  • 365.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Pass By Value Java uses pass by value to pass arguments to a method. There are important differences between passing a value of variables of primitive data types and passing arrays. • For a parameter of a primitive type value, the actual value is passed. Changing the value of the local parameter inside the method does not affect the value of the variable outside the method. • For a parameter of an array type, the value of the parameter contains a reference to an array; this reference is passed to the method. Any changes to the array that occur inside the method body will affect the original array that was passed as the argument.
  • 366.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Simple Example
  • 367.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Call Stack (1 of 2) When invoking m(x, y), the values of x and y are passed to number and numbers. Since y contains the reference value to the array, numbers now contains the same reference value to the same array.
  • 368.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Call Stack (2 of 2) When invoking m(x, y), the values of x and y are passed to number and numbers. Since y contains the reference value to the array, numbers now contains the same reference value to the same array.
  • 369.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Heap Space required for the main method int[] y: int x: 1 reference The arrays are stored in a heap. Heap 5555 0 0 The JVM stores the array in an area of memory, called heap, which is used for dynamic memory allocation where blocks of memory are allocated and freed in an arbitrary order.
  • 370.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Passing Arrays as Arguments • Objective: Demonstrate differences of passing primitive data type variables and array variables. TestPassArray
  • 371.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example Invoke swap(int n1, int n2). The primitive type values in a[0] and a[1] are passed to the swap method. Space required for the main method int[] a Stack Space required for the swap method n2: 2 n1: 1 reference a[1]: 2 a[0]: 1 The arrays are stored in a heap. Invoke swapFirstTwoInArray(int[] array). The reference value in a is passed to the swapFirstTwoInArray method. Heap Space required for the main method int[] a Stack Space required for the swapFirstTwoInArray method int[] array reference reference
  • 372.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Returning an Array from a Method
  • 373.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (1 of 22)
  • 374.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (2 of 22)
  • 375.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (3 of 22)
  • 376.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (4 of 22)
  • 377.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (5 of 22)
  • 378.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (6 of 22)
  • 379.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (7 of 22)
  • 380.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (8 of 22)
  • 381.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (9 of 22)
  • 382.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (10 of 22)
  • 383.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (11 of 22)
  • 384.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (12 of 22)
  • 385.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (13 of 22)
  • 386.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (14 of 22)
  • 387.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (15 of 22)
  • 388.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (16 of 22)
  • 389.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (17 of 22)
  • 390.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (18 of 22)
  • 391.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (19 of 22)
  • 392.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (20 of 22)
  • 393.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (21 of 22)
  • 394.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace the Reverse Method (22 of 22)
  • 395.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Counting Occurrence of Each Letter • Generate 100 lowercase letters randomly and assign to an array of characters. • Count the occurrence of each letter in the array. CountLettersInArray
  • 396.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Variable-Length Arguments You can pass a variable number of arguments of the same type to a method. VarArgsDemo
  • 397.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Searching Arrays Searching is the process of looking for a specific element in an array; for example, discovering whether a certain score is included in a list of scores. Searching is a common task in computer programming. There are many algorithms and data structures devoted to searching. In this section, two commonly used approaches are discussed, linear search and binary search. public class LinearSearch { /** The method for finding a key in the list */ public static int linearSearch(int[] list, int key) { for (int i = 0; i < list.length; i++) if (key == list[i]) return i; return -1; } } list key Compare key with list[i] for i = 0, 1, … [0] [1] [2] …
  • 398.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Linear Search The linear search approach compares the key element, key, sequentially with each element in the array list. The method continues to do so until the key matches an element in the list or the list is exhausted without a match being found. If a match is made, the linear search returns the index of the element in the array that matches the key. If no match is found, the search returns 1. 
  • 399.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Linear Search Animation (1 of 2)
  • 400.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Linear Search Animation (2 of 2) https://liveexample.pearsoncmg.com/dsanimation/LinearSe archeBook.html
  • 401.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved From Idea to Solution (1 of 6) Trace the method
  • 402.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Binary Search (1 of 6) For binary search to work, the elements in the array must already be ordered. Without loss of generality, assume that the array is in ascending order. e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79 The binary search first compares the key with the element in the middle of the array.
  • 403.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Binary Search (2 of 6) Consider the following three cases: • If the key is less than the middle element, you only need to search the key 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 only need to search the key in the second half of the array.
  • 404.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Binary Search (3 of 6)
  • 405.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Binary Search Animation https://liveexample.pearsoncmg.com/dsanimation/BinarySe archeBook.html
  • 406.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Binary Search (4 of 6)
  • 407.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Binary Search (5 of 6) [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] 2 4 7 10 11 45 50 59 60 66 69 70 79 key is 54 key > 50 list mid [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] key < 66 key < 59 high low mid high low list [7] [8] mid high low list 59 60 66 69 70 79 59 60 [6] [7] [8] high low 59 60
  • 408.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Binary Search (6 of 6) The binarySearch method returns the index of the element in the list that matches the search key if it is contained in the list. Otherwise, it returns -insertion point - 1. The insertion point is the point at which the key would be inserted into the list.
  • 409.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved From Idea to Solution (2 of 6) /** Use binary search to find the key in the list */ public static int binarySearch(int[] list, int key) { int low = 0; int high = list.length - 1; while (high >= low) { int mid = (low + high) / 2; if (key < list[mid]) high = mid - 1; else if (key == list[mid]) return mid; else low = mid + 1; } return -1 - low; }
  • 410.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Arrays.binarySearch Method Since binary search is frequently used in programming, Java provides several overloaded binarySearch methods for searching a key in an array of int, double, char, short, long, and float in the java.util.Arrays class. For example, the following code searches the keys in an array of numbers and an array of characters. For the binarySearch method to work, the array must be pre-sorted in increasing order.
  • 411.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Sorting Arrays Sorting, like searching, is also a common task in computer programming. Many different algorithms have been developed for sorting. This section introduces a simple, intuitive sorting algorithms: selection sort.
  • 412.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Selection Sort Selection sort finds the smallest number in the list and places it first. It then finds the smallest number remaining and places it second, and so on until the list contains only a single number.
  • 413.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Selection Sort Animation https://liveexample.pearsoncmg.com/dsanimation/Selection SortNew.html
  • 414.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved From Idea to Solution (3 of 6) for (int i = 0; i < list.length; i++) { select the smallest element in list[i..listSize-1]; swap the smallest with list[i], if necessary; // list[i] is in its correct position. // The next iteration apply on list[i+1..listSize-1] } list [0] list [1] list [2] list [3] ... list [10] list [0] list [1] list [2] list [3] ... list [10] list [0] list [1] list [2] list [3] ... list [10] list [0] list [1] list [2] list [3] ... list [10] list [0] list [1] list [2] list [3] ... list [10] ... list [0] list [1] list [2] list [3] ... list [10]
  • 415.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved From Idea to Solution (4 of 6)
  • 416.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved From Idea to Solution (5 of 6)
  • 417.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved From Idea to Solution (6 of 6)
  • 418.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Wrap it in a Method
  • 419.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Arrays.sort Method Since sorting is frequently used in programming, Java provides several overloaded sort methods for sorting an array of int, double, char, short, long, and float in the java.util.Arrays class. For example, the following code sorts an array of numbers and an array of characters. double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5}; java.util.Arrays.sort(numbers); char[] chars = {'a', 'A', '4', 'F', 'D', 'P'}; java.util.Arrays.sort(chars); Java 8 now provides Arrays.parallelSort(list) that utilizes the multicore for fast sorting.
  • 420.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Arrays.toString(list) Method The Arrays.toString(list) method can be used to return a string representation for the list.
  • 421.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Main Method Is Just a Regular Method You can call a regular method by passing actual parameters. Can you pass arguments to main? Of course, yes. For example, the main method in class B is invoked by a method in A, as shown below: public class A { public static void main(String[] args) { String[] strings = {"New York", "Boston", "Atlanta"}; B.main(strings); } } class B { public static void main(String[] args) { for (int i = 0; i < args.length; i++) System.out.println(args[i]); } }
  • 422.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Command-Line Parameters class TestMain { public static void main(String[] args) { ... } } java TestMain arg0 arg1 arg2 ... argn
  • 423.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Processing Command-Line Parameters In the main method, get the arguments from args[0], args[1], ..., args[n], which corresponds to arg0, arg1, ..., argn in the command line.
  • 424.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Calculator • Objective: Write a program that will perform binary operations on integers. The program receives three parameters: an operator and two integers. java Calculator 2 + 3 java Calculator 2 3  java Calculator 2 / 3 java Calculator 2.3 Calculator
  • 425.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.
  • 426.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introduction to Java Programming and Data Structures Thirteenth Edition Chapter 8 Multidimensional Arrays Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 427.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Motivations (1 of 2) Thus far, you have used one-dimensional arrays to model linear collections of elements. You can use a two-dimensional array to represent a matrix or a table. For example, the following table that describes the distances between the cities can be represented using a two-dimensional array. Distance Table (in miles) Blank Chicago Boston New York Atlanta Miami Dallas Houston Chicago 0 983 787 714 1375 967 1087 Boston 983 0 214 1102 1763 1723 1842 New York 787 214 0 888 1549 1548 1627 Atlanta 714 1102 888 0 661 781 810 Miami 1375 1763 1549 661 0 1426 1187 Dallas 967 1723 1548 781 1426 0 239 Houston 1087 1842 1627 810 1187 239 0
  • 428.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Motivations (2 of 2)
  • 429.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (1 of 2) 8.1 To give examples of representing data using two- dimensional arrays (§8.1). 8.2 To declare variables for two-dimensional arrays, create arrays, and access array elements in a two-dimensional array using row and column indexes (§8.2). 8.3 To program common operations for two-dimensional arrays (displaying arrays, summing all elements, finding the minimum and maximum elements, and random shuffling) (§8.3). 8.4 To pass two-dimensional arrays to methods (§8.4).
  • 430.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (2 of 2) 8.5 To write a program for grading multiple-choice questions using two-dimensional arrays (§8.5). 8.6 To solve the closest-pair problem using two- dimensional arrays (§8.6). 8.7 To check a Sudoku solution using two-dimensional arrays (§8.7). 8.8 To use multidimensional arrays (§8.8).
  • 431.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Declare/Create Two-dimensional Arrays // Declare array ref var dataType[][] refVar; // Create array and assign its reference to variable refVar = new dataType[10][10]; // Combine declaration and creation in one statement dataType[][] refVar = new dataType[10][10]; // Alternative syntax dataType refVar[][] = new dataType[10][10];
  • 432.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Declaring Variables of Two-dimensional Arrays and Creating Two-dimensional Arrays int[][] matrix = new int[10][10]; or int matrix[][] = new int[10][10]; matrix[0][0] = 3; for (int i = 0; i < matrix.length; i++) for (int j = 0; j < matrix[i].length; j++) matrix[i][j] = (int)(Math.random() * 1000); double[][] x;
  • 433.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Two-dimensional Array Illustration matrix.length? 5 matrix[0].length? 5 array.length? 4 array[0].length? 3
  • 434.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Declaring, Creating, and Initializing Using Shorthand Notations
  • 435.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Lengths of Two-dimensional Arrays (1 of 2) int[][] x = new int[3][4];
  • 436.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Lengths of Two-dimensional Arrays (2 of 2) int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; array.length array[0].length array[1].length array[2].length array[3].length array[4].length ArrayIndexOutOfBoundsException
  • 437.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Ragged Arrays (1 of 2) Each row in a two-dimensional array is itself an array. So, the rows can have different lengths. Such an array is known as a ragged array. For example, int[][] matrix = { {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5} }; matrix.length is 5 matrix[0].length is 5 matrix[1].length is 4 matrix[2].length is 3 matrix[3].length is 2 matrix[4].length is 1
  • 438.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Ragged Arrays (2 of 2)
  • 439.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Processing Two-Dimensional Arrays See the examples in the text. 1. (Initializing arrays with input values) 2. (Printing arrays) 3. (Summing all elements) 4. (Summing all elements by column) 5. (Which row has the largest sum) 6. (Finding the smallest index of the largest element) 7. (Random shuffling)
  • 440.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Initializing Arrays With Input Values java.util.Scanner input = new Scanner(System.in); System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + " columns: "); for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { matrix[row][column] = input.nextInt(); } }
  • 441.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Initializing Arrays With Random Values for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { matrix[row][column] = (int)(Math.random() * 100); } }
  • 442.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Printing Arrays for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { System.out.print(matrix[row][column] + " "); } System.out.println(); }
  • 443.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Summing All Elements int total = 0; for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { total += matrix[row][column]; } }
  • 444.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Summing Elements by Column for (int column = 0; column < matrix[0].length; column++) { int total = 0; for (int row = 0; row < matrix.length; row++) total += matrix[row][column]; System.out.println("Sum for column " + column + " is " + total); }
  • 445.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Random Shuffling for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { int i1 = (int)(Math.random() * matrix.length); int j1 = (int)(Math.random() * matrix[i].length); // Swap matrix[i][j] with matrix[i1][j1] int temp = matrix[i][j]; matrix[i][j] = matrix[i1][j1]; matrix[i1][j1] = temp; } }
  • 446.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Passing Tow-Dimensional Arrays to Methods PassTwoDimensionalArray
  • 447.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Grading Multiple-Choice Test Students’ answer Objective: write a program that grades multiple-choice test. PassTwoDimensionalArray
  • 448.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Finding Two Points Nearest to Each Other https://liveexample.pearsoncmg.com/dsanimation/ClosestP aireBook.html PassTwoDimensionalArray
  • 449.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved What is Sudoku? 5 3 7 6 1 9 5 9 8 6 8 6 3 4 8 3 1 7 2 6 6 4 1 9 5 8 7 9 https://liveexample.pearsoncmg. com/dsanimation/Sudoku.html
  • 450.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Every Row Contains the Numbers 1 to 9 5 3 7 6 1 9 5 9 8 6 8 6 3 4 8 3 1 7 2 6 6 4 1 9 5 8 7 9
  • 451.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Every Column Contains the Numbers 1 to 9 5 3 7 6 1 9 5 9 8 6 8 6 3 4 8 3 1 7 2 6 6 4 1 9 5 8 7 9
  • 452.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Every 3 by 3 Box Contains the Numbers 1 to 9 5 3 7 6 1 9 5 9 8 6 8 6 3 4 8 3 1 7 2 6 6 4 1 9 5 8 7 9
  • 453.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Checking Whether a Solution Is Correct 5 3 7 6 1 9 5 9 8 6 8 6 3 4 8 3 1 7 2 6 6 4 1 9 5 8 7 9 5 3 4 6 7 8 9 1 2 6 7 2 1 9 5 3 4 8 1 9 8 3 4 2 5 6 7 8 5 9 7 6 1 4 2 3 4 2 6 8 5 3 7 9 1 7 1 3 9 2 4 8 5 6 9 6 1 5 3 7 2 8 4 2 8 7 4 1 9 6 3 5 3 4 5 2 8 6 1 7 9 CheckSudokuSolution
  • 454.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Multidimensional Arrays (1 of 2) Occasionally, you will need to represent n-dimensional data structures. In Java, you can create n-dimensional arrays for any integer n. The way to declare two-dimensional array variables and create two-dimensional arrays can be generalized to declare n-dimensional array variables and create n- dimensional arrays for n >= 3.
  • 455.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Multidimensional Arrays (2 of 2) double[][][] scores = { {{7.5, 20.5}, {9.0, 22.5}, {15, 33.5}, {13, 21.5}, {15, 2.5}}, {{4.5, 21.5}, {9.0, 22.5}, {15, 34.5}, {12, 20.5}, {14, 9.5}}, {{6.5, 30.5}, {9.4, 10.5}, {11, 33.5}, {11, 23.5}, {10, 2.5}}, {{6.5, 23.5}, {9.4, 32.5}, {13, 34.5}, {11, 20.5}, {16, 7.5}}, {{8.5, 26.5}, {9.4, 52.5}, {13, 36.5}, {13, 24.5}, {16, 2.5}}, {{9.5, 20.5}, {9.4, 42.5}, {13, 31.5}, {12, 20.5}, {16, 6.5}} }; scores[ i ] [ j ] [ k ] Which student Which exam Multiple-choice or essay
  • 456.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Calculating Total Scores Objective: write a program that calculates the total score for students in a class. Suppose the scores are stored in a three-dimensional array named scores. The first index in scores refers to a student, the second refers to an exam, and the third refers to the part of the exam. Suppose there are 7 students, 5 exams, and each exam has two parts--the multiple-choice part and the programming part. So, scores[i][j][0] represents the score on the multiple-choice part for the i’s student on the j’s exam. Your program displays the total score for each student. TotalScore
  • 457.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Weather Information Suppose a meteorology station records the temperature and humidity at each hour of every day and stores the data for the past ten days in a text file named weather.txt. Each line of the file consists of four numbers that indicate the day, hour, temperature, and humidity. Your task is to write a program that calculates the average daily temperature and humidity for the 10 days. 1 1 76.4 0.92 1 2 77.7 0.93 ... 10 23 97.7 0.71 10 24 98.7 0.74 (a) 10 24 98.7 0.74 1 2 77.7 0.93 ... 10 23 97.7 0.71 1 1 76.4 0.92 (b) Weather
  • 458.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Guessing Birthday Listing 4.3, GuessBirthday.java, gives a program that guesses a birthday. The program can be simplified by storing the numbers in five sets in a three-dimensional array, and it prompts the user for the answers using a loop. GuessBirthdayUsingArray
  • 459.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.
  • 460.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introduction to Java Programming and Data Structures Thirteenth Edition Chapter 9 Objects and Classes Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 461.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java features are not sufficient for developing graphical user interfaces and large scale software systems. Suppose you want to develop a graphical user interface as shown below. How do you program it?
  • 462.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (1 of 2) 9.1 To describe objects and classes, and use classes to model objects (§9.2). 9.2 To use UML graphical notation to describe classes and objects (§9.2). 9.3 To demonstrate how to define classes and create objects (§9.3). 9.4 To create objects using constructors (§9.4). 9.5 To define a reference variable using a reference type and access objects via object reference variables (§9.5). 9.6 To access an object’s data and methods using the object member access operator (.) (§9.5.1). 9.7 To define data fields of reference types and assign default values for an object’s data fields (§9.5.2). 9.8 To distinguish between object reference variables and primitive data type variables (§9.5.3).
  • 463.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (2 of 2) 9.9 To use the Java library classes Date, Random, and Point2D (§9.6). 9.10 To distinguish between instance and static variables and methods (§9.7). 9.11 To define private data fields with appropriate get and set methods (§9.8). 9.12 To encapsulate data fields to make classes easy to maintain (§9.9). 9.13 To develop methods with object arguments and differentiate between primitive-type arguments and object-type arguments (§9.10). 9.14 To store and process objects in arrays (§9.11). 9.15 To create immutable objects from immutable classes to protect the contents of objects (§9.12). 9.16 To determine the scope of variables in the context of a class (§9.13). 9.17 To use the keyword this to refer to the calling object itself (§9.14).
  • 464.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects. An object has a unique identity, state, and behaviors. The state of an object consists of a set of data fields (also known as properties) with their current values. The behavior of an object is defined by a set of methods.
  • 465.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objects Class Name: Circle Data Fields: radius is _______ Methods: getArea Circle Object 1 Data Fields: radius is 10 Circle Object 2 Data Fields: radius is 25 Circle Object 3 Data Fields: radius is 125 A class template Three objects of the Circle class An object has both a state and behavior. The state defines the object, and the behavior defines what the object does.
  • 466.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Classes (1 of 2) Classes are constructs that define objects of the same type. A Java class uses variables to define data fields and methods to define behaviors. Additionally, a class provides a special type of methods, known as constructors, which are invoked to construct objects from the class.
  • 467.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Classes (2 of 2) class Circle { /** The radius of this circle */ double radius = 1.0; /** Construct a circle object */ Circle() { } /** Construct a circle object */ Circle(double newRadius) { radius = newRadius; } /** Return the area of this circle */ double getArea() { return radius * radius * 3.14159; } } Data field Method Constructors
  • 468.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved UML Class Diagram Circle radius: double Circle() Circle(newRadius: double) getArea(): double getPerimeter(): double setRadius(newRadius: double): void circle1: Circle radius = 1.0 Class name Data fields Constructors and methods circle2: Circle radius = 25 circle3: Circle radius = 125 UML Class Diagram UML notation for objects
  • 469.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example: Defining Classes and Creating Objects (1 of 2) Objective: Demonstrate creating objects, accessing data, and using methods. TestSimpleCircle
  • 470.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example: Defining Classes and Creating Objects (2 of 2) TV TestTV
  • 471.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Constructors (1 of 2) Circle() { } Circle(double newRadius) { radius = newRadius; } Constructors are a special kind of methods that are invoked to construct objects.
  • 472.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Constructors (2 of 2) A constructor with no parameters is referred to as a no-arg constructor. • Constructors must have the same name as the class itself. • Constructors do not have a return type—not even void. • Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects.
  • 473.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Creating Objects Using Constructors new ClassName(); Example: new Circle(); new Circle(5.0);
  • 474.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Default Constructor A class may be defined without constructors. In this case, a no-arg constructor with an empty body is implicitly defined in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly defined in the class.
  • 475.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Declaring Object Reference Variables To reference an object, assign the object to a reference variable. To declare a reference variable, use the syntax: ClassName objectRefVar; Example: Circle myCircle;
  • 476.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Declaring/Creating Objects in a Single Step ClassName objectRefVar = new ClassName(); Example:
  • 477.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Accessing Object’s Members • Referencing the object’s data: objectRefVar.data e.g., myCircle.radius • Invoking the object’s method: objectRefVar.methodName(arguments) e.g., myCircle.getArea()
  • 478.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Code (1 of 7)
  • 479.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Code (2 of 7)
  • 480.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Code (3 of 7)
  • 481.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Code (4 of 7)
  • 482.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Code (5 of 7)
  • 483.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Code (6 of 7)
  • 484.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Code (7 of 7)
  • 485.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Caution Recall that you use Math.methodName(arguments) (e.g., Math.pow(3, 2.5)) to invoke a method in the Math class. Can you invoke getArea() using SimpleCircle.getArea()? The answer is no. All the methods used before this chapter are static methods, which are defined using the static keyword. However, getArea() is non-static. It must be invoked from an object using objectRefVar.methodName(arguments) (e.g., myCircle.getArea()). More explanations will be given in the section on “Static Variables, Constants, and Methods.”
  • 486.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Reference Data Fields The data fields can be of reference types. For example, the following Student class contains a data field name of the String type. public class Student { String name; // name has default value null int age; // age has default value 0 boolean isScienceMajor; // isScienceMajor has default value false char gender; // c has default value 'u0000’ }
  • 487.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Null Value If a data field of a reference type does not reference any object, the data field holds a special literal value, null.
  • 488.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Default Value for a Data Field The default value of a data field is null for a reference type, 0 for a numeric type, false for a boolean type, and 'u0000' for a char type. However, Java assigns no default value to a local variable inside a method. public class Test { public static void main(String[] args) { Student student = new Student(); System.out.println("name? " + student.name); System.out.println("age? " + student.age); System.out.println("isScienceMajor? " + student.isScienceMajor); System.out.println("gender? " + student.gender); } }
  • 489.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example (1 of 3) Java assigns no default value to a local variable inside a method.
  • 490.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Differences between Variables of Primitive Data Types and Object Types 1 Primitive type int i = 1 i Object type Circle c c reference Created using new Circle() c: Circle radius = 1
  • 491.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copying Variables of Primitive Data Types and Object Types i Primitive type assignment i = j Before: 1 j 2 i After: 2 j 2 c1 Object type assignment c1 = c2 Before: c2 c1 After: c2 c1: Circle radius = 5 c2: Circle radius = 9 c1: Circle radius = 5 c2: Circle radius = 9
  • 492.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Garbage Collection (1 of 2) As shown in the previous figure, after the assignment statement c1 = c2, c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer referenced. This object is known as garbage. Garbage is automatically collected by JVM.
  • 493.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Garbage Collection (2 of 2) TIP: If you know that an object is no longer needed, you can explicitly assign null to a reference variable for the object. The JVM will automatically collect the space if the object is not referenced by any variable.
  • 494.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Date Class Java provides a system-independent encapsulation of date and time in the java.util.Date class. You can use the Date class to create an instance for the current date and time and use its toString method to return the date and time as a string.
  • 495.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Date Class Example For example, the following code java.util.Date date = new java.util.Date(); System.out.println(date.toString()); displays a string like Sun Mar 09 13:50:19 EST 2003.
  • 496.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Random Class You have used Math.random() to obtain a random double value between 0.0 and 1.0 (excluding 1.0). A more useful random number generator is provided in the java.util.Random class. java.util.Random +Random() +Random(seed: long) +nextInt(): int +nextInt(n: int): int +nextLong(): long +nextDouble(): double +nextFloat(): float +nextBoolean(): boolean Constructs a Random object with the current time as its seed. Constructs a Random object with a specified seed. Returns a random int value. Returns a random int value between 0 and n (exclusive). Returns a random long value. Returns a random double value between 0.0 and 1.0 (exclusive). Returns a random float value between 0.0F and 1.0F (exclusive). Returns a random boolean value.
  • 497.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Random Class Example If two Random objects have the same seed, they will generate identical sequences of numbers. For example, the following code creates two Random objects with the same seed 3. Random random1 = new Random(3); System.out.print("From random1: "); for (int i = 0; i < 10; i++) System.out.print(random1.nextInt(1000) + " "); Random random2 = new Random(3); System.out.print("nFrom random2: "); for (int i = 0; i < 10; i++) System.out.print(random2.nextInt(1000) + " "); From random1: 734 660 210 581 128 202 549 564 459 961 From random2: 734 660 210 581 128 202 549 564 459 961
  • 498.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Point2D Class Java API has a conveninent Point2D class in the javafx.geometry package for representing a point in a two-dimensional plane. TestPoint2D
  • 499.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Instance Variables, and Methods Instance variables belong to a specific instance. Instance methods are invoked by an instance of the class.
  • 500.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Static Variables, Constants, and Methods (1 of 3) Static variables are shared by all the instances of the class. Static methods are not tied to a specific object. Static constants are final variables shared by all the instances of the class.
  • 501.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Static Variables, Constants, and Methods (2 of 3) To declare static variables, constants, and methods, use the static modifier.
  • 502.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Static Variables, Constants, and Methods (3 of 3)
  • 503.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example of Using Instance and Class Variables and Method Objective: Demonstrate the roles of instance and class variables and their uses. This example adds a class variable numberOfObjects to track the number of Circle objects created. CircleWithStaticMembers TestCircleWithStaticMembers
  • 504.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Visibility Modifiers and Accessor/Mutator Methods (1 of 3) By default, the class, variable, or method can be accessed by any class in the same package. • public The class, data, or method is visible to any class in any package. • private The data or methods can be accessed only by the declaring class. The get and set methods are used to read and modify private properties.
  • 505.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Visibility Modifiers and Accessor/Mutator Methods (2 of 3) The private modifier restricts access to within a class, the default modifier restricts access to within a package, and the public modifier enables unrestricted access.
  • 506.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Visibility Modifiers and Accessor/Mutator Methods (3 of 3) The default modifier on a class restricts access to within a package, and the public modifier enables unrestricted access.
  • 507.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Note An object cannot access its private members, as shown in (b). It is OK, however, if the object is declared in its own class, as shown in (a).
  • 508.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Why Data Fields Should Be Private? To protect data. To make code easy to maintain.
  • 509.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example of Data Field Encapsulation Circle -radius: double -numberOfObjects: int +Circle() +Circle(radius: double) +getRadius(): double +setRadius(radius: double): void +getNumberOfObjects(): int +getArea(): double The radius of this circle (default: 1.0). The number of circle objects created. Constructs a default circle object. Constructs a circle object with the specified radius. Returns the radius of this circle. Sets a new radius for this circle. Returns the number of circle objects created. Returns the area of this circle. The - sign indicates private modifier CircleWithPrivateDataFields TestCircleWithPrivateDataFields
  • 510.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Passing Objects to Methods (1 of 2) • Passing by value for primitive type value (the value is passed to the parameter) • Passing by value for reference type value (the value is the reference to the object) TestPassObject
  • 511.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Passing Objects to Methods (2 of 2)
  • 512.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Array of Objects (1 of 3) Circle[] circleArray = new Circle[10]; An array of objects is actually an array of reference variables. So invoking circleArray[1].getArea() involves two levels of referencing as shown in the next figure. circleArray references to the entire array. circleArray[1] references to a Circle object.
  • 513.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Array of Objects (2 of 3) Circle[] circleArray = new Circle[10];
  • 514.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Array of Objects (3 of 3) Summarizing the areas of the circles TotalArea
  • 515.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Immutable Objects and Classes If the contents of an object cannot be changed once the object is created, the object is called an immutable object and its class is called an immutable class. If you delete the set method in the Circle class in Listing 8.10, the class would be immutable because radius is private and cannot be changed without a set method. A class with all private data fields and without mutators is not necessarily immutable. For example, the following class Student has all private data fields and no mutators, but it is mutable.
  • 516.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example (2 of 3) public class Student { private int id; private BirthDate birthDate; public Student(int ssn, int year, int month, int day) { id = ssn; birthDate = new BirthDate(year, month, day); } public int getId() { return id; } public BirthDate getBirthDate() { return birthDate; } } public class BirthDate { private int year; private int month; private int day; public BirthDate(int newYear, int newMonth, int newDay) { year = newYear; month = newMonth; day = newDay; } public void setYear(int newYear) { year = newYear; } }
  • 517.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example (3 of 3) public class Test { public static void main(String[] args) { Student student = new Student(111223333, 1970, 5, 3); BirthDate date = student.getBirthDate(); date.setYear(2010); // Now the student birth year is changed! } }
  • 518.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved What Class is Immutable? For a class to be immutable, it must mark all data fields private and provide no mutator methods and no accessor methods that would return a reference to a mutable data field object.
  • 519.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Scope of Variables • The scope of instance and static variables is the entire class. They can be declared anywhere inside a class. • The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be initialized explicitly before it can be used.
  • 520.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The this Keyword • The this keyword is the name of a reference that refers to an object itself. One common use of the this keyword is reference a class’s hidden data fields. • Another common use of the this keyword to enable a constructor to invoke another constructor of the same class.
  • 521.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Reference the Hidden Data Fields public class F { private int i = 5; private static double k = 0; void setI(int i) { this.i = i; } static void setK(double k) { F.k = k; } } Suppose that f1 and f2 are two objects of F. F f1 = new F(); F f2 = new F(); Invoking f1.setI(10) is to execute this.i = 10, where this refers f1 Invoking f2.setI(45) is to execute this.i = 45, where this refers f2
  • 522.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Calling Overloaded Constructor
  • 523.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.
  • 524.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introduction to Java Programming and Data Structures Thirteenth Edition Chapter 10 Thinking in Objects Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 525.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Motivations You see the advantages of object-oriented programming from the preceding chapter. This chapter will demonstrate how to solve problems using the object-oriented paradigm.
  • 526.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives 10.1 To apply class abstraction to develop software (§10.2). 10.2 To explore the differences between the procedural paradigm and object- oriented paradigm (§10.3). 10.3 To discover the relationships between classes (§10.4). 10.4 To design programs using the object-oriented paradigm (§§10.5–10.6). 10.5 To create objects for primitive values using the wrapper classes (Byte, Short, Integer, Long, Float, Double, Character, and Boolean) (§10.7). 10.6 To simplify programming using automatic conversion between primitive types and wrapper class types (§10.8). 10.7 To use the BigInteger and BigDecimal classes for computing very large numbers with arbitrary precisions (§10.9). 10.8 To use the String class to process immutable strings (§10.10). 10.9 To use the StringBuilder and StringBuffer classes to process mutable strings (§10.11).
  • 527.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Class Abstraction and Encapsulation Class abstraction means to separate class implementation from the use of the class. The creator of the class provides a description of the class and let the user know how the class can be used. The user of the class does not need to know how the class is implemented. The detail of implementation is encapsulated and hidden from the user. Class Contract (Signatures of public methods and public constants) Class Class implementation is like a black box hidden from the clients Clients use the class through the contract of the class
  • 528.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Designing the Loan Class Loan -annualInterestRate: double -numberOfYears: int -loanAmount: double -loanDate: Date +Loan() +Loan(annualInterestRate: double, numberOfYears: int, loanAmount: double) +getAnnualInterestRate(): double +getNumberOfYears(): int +getLoanAmount(): double +getLoanDate(): Date +setAnnualInterestRate( annualInterestRate: double): void +setNumberOfYears( numberOfYears: int): void +setLoanAmount( loanAmount: double): void +getMonthlyPayment(): double +getTotalPayment(): double The annual interest rate of the loan (default: 2.5). The number of years for the loan (default: 1) The loan amount (default: 1000). The date this loan was created. Constructs a default Loan object. Constructs a loan with specified interest rate, years, and loan amount. Returns the annual interest rate of this loan. Returns the number of the years of this loan. Returns the amount of this loan. Returns the date of the creation of this loan. Sets a new annual interest rate to this loan. Sets a new number of years to this loan. Sets a new amount to this loan. Returns the monthly payment of this loan. Returns the total payment of this loan. Loan TestLoanClass
  • 529.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Object-Oriented Thinking Chapters 1-8 introduced fundamental programming techniques for problem solving using loops, methods, and arrays. The studies of these techniques lay a solid foundation for object-oriented programming. Classes provide more flexibility and modularity for building reusable software. This section improves the solution for a problem introduced in Chapter 3 using the object-oriented approach. From the improvements, you will gain the insight on the differences between the procedural programming and object-oriented programming and see the benefits of developing reusable code using objects and classes.
  • 530.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The BMI Class BMI UseBMIClass
  • 531.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Class Relationships Association Aggregation Composition Inheritance (Chapter 13) Association: is a general binary relationship that describes an activity between two classes.
  • 532.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Object Composition Composition is actually a special case of the aggregation relationship. Aggregation models has-a relationships and represents an ownership relationship between two objects. The owner object is called an aggregating object and its class an aggregating class. The subject object is called an aggregated object and its class an aggregated class. Name Address Student Composition Aggregation 1..3 1 1 1
  • 533.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Class Representation An aggregation relationship is usually represented as a data field in the aggregating class. For example, the relationship in Figure 10.6 can be represented as follows: public class Name { ... } public class Student { private Name name; private Address address; ... } public class Address { ... } Aggregated class Aggregating class Aggregated class
  • 534.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Aggregation or Composition Since aggregation and composition relationships are represented using classes in similar ways, many texts don’t differentiate them and call both compositions.
  • 535.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Aggregation Between Same Class (1 of 2) Aggregation may exist between objects of the same class. For example, a person may have a supervisor. Person Supervisor 1 1 public class Person { // The type for the data is the class itself private Person supervisor; ... }
  • 536.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Aggregation Between Same Class (2 of 2) What happens if a person has several supervisors?
  • 537.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example: The Course Class Course -courseName: String -students: String[] -numberOfStudents: int +Course(courseName: String) +getCourseName(): String +addStudent(student: String): void +dropStudent(student: String): void +getStudents(): String[] +getNumberOfStudents(): int The name of the course. An array to store the students for the course. The number of students (default: 0). Creates a course with the specified name. Returns the course name. Adds a new student to the course. Drops a student from the course. Returns the students in the course. Returns the number of students in the course. Course TestCourse
  • 538.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example: The StackOfIntegers Class StackOfIntegers -elements: int[] -size: int +StackOfIntegers() +StackOfIntegers(capacity: int) +empty(): boolean +peek(): int +push(value: int): int +pop(): int +getSize(): int An array to store integers in the stack. The number of integers in the stack. Constructs an empty stack with a default capacity of 16. Constructs an empty stack with a specified capacity. Returns true if the stack is empty. Returns the integer at the top of the stack without removing it from the stack. Stores an integer into the top of the stack. Removes the integer at the top of the stack and returns it. Returns the number of elements in the stack. TestStackOfIntegers
  • 539.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Designing the StackOfIntegers Class
  • 540.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Implementing StackOfIntegers Class StackOfIntegers
  • 541.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Wrapper Classes • Boolean • Character • Short • Byte • Integer • Long • Float • Double Note: (1) The wrapper classes do not have no-arg constructors. (2) The instances of all wrapper classes are immutable, i.e., their internal values cannot be changed once the objects are created.
  • 542.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Integer and Double Classes java.lang.Integer -value: int +MAX_VALUE: int +MIN_VALUE: int +Integer(value: int) +Integer(s: String) +byteValue(): byte +shortValue(): short +intValue(): int +longVlaue(): long +floatValue(): float +doubleValue():double +compareTo(o: Integer): int +toString(): String +valueOf(s: String): Integer +valueOf(s: String, radix: int): Integer +parseInt(s: String): int +parseInt(s: String, radix: int): int java.lang.Double -value: double +MAX_VALUE: double +MIN_VALUE: double +Double(value: double) +Double(s: String) +byteValue(): byte +shortValue(): short +intValue(): int +longVlaue(): long +floatValue(): float +doubleValue():double +compareTo(o: Double): int +toString(): String +valueOf(s: String): Double +valueOf(s: String, radix: int): Double +parseDouble(s: String): double +parseDouble(s: String, radix: int): double
  • 543.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Integer Class and the Double Class • Constructors • Class Constants MAX_VALUE, MIN_VALUE • Conversion Methods
  • 544.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Numeric Wrapper Class Constructors You can construct a wrapper object either from a primitive data type value or from a string representing the numeric value. The constructors for Integer and Double are: public Integer(int value) public Integer(String s) public Double(double value) public Double(String s)
  • 545.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Numeric Wrapper Class Constants Each numerical wrapper class has the constants MAX_VALUE and MIN_VALUE. MAX_VALUE represents the maximum value of the corresponding primitive data type. For Byte, Short, Integer, and Long, MIN_VALUE represents the minimum byte, short, int, and long values. For Float and Double, MIN_VALUE represents the minimum positive float and double values. The following statements display the maximum integer (2,147,483,647), the minimum positive float (1.4E-45), and the maximum double floating-point number (1.79769313486231570e+308d).
  • 546.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Conversion Methods Each numeric wrapper class implements the abstract methods doubleValue, floatValue, intValue, longValue, and shortValue, which are defined in the Number class. These methods “convert” objects into primitive type values.
  • 547.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Static valueOf Methods The numeric wrapper classes have a useful class method, valueOf(String s). This method creates a new object initialized to the value represented by the specified string. For example: Double doubleObject = Double.valueOf("12.4"); Integer integerObject = Integer.valueOf("12");
  • 548.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Methods for Parsing Strings into Numbers You have used the parseInt method in the Integer class to parse a numeric string into an int value and the parseDouble method in the Double class to parse a numeric string into a double value. Each numeric wrapper class has two overloaded parsing methods to parse a numeric string into an appropriate numeric value.
  • 549.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Automatic Conversion Between Primitive Types and Wrapper Class Types JDK 1.5 allows primitive type and wrapper classes to be converted automatically. For example, the following statement in (a) can be simplified as in (b): Integer[] intArray = {new Integer(2), new Integer(4), new Integer(3)}; (a) Equivalent (b) Integer[] intArray = {2, 4, 3}; New JDK 1.5 boxing
  • 550.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved BigInteger and BigDecimal (1 of 2) If you need to compute with very large integers or high precision floating-point values, you can use the BigInteger and BigDecimal classes in the java.math package. Both are immutable. Both extend the Number class and implement the Comparable interface.
  • 551.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved BigInteger and BigDecimal (2 of 2) BigInteger a = new BigInteger("9223372036854775807"); BigInteger b = new BigInteger("2"); BigInteger c = a.multiply(b); // 9223372036854775807 * 2 System.out.println(c); BigDecimal a = new BigDecimal(1.0); BigDecimal b = new BigDecimal(3); BigDecimal c = a.divide(b, 20, BigDecimal.ROUND_UP); System.out.println(c); LargeFactorial
  • 552.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The String Class • Constructing a String: String message = "Welcome to Java“; String message = new String("Welcome to Java“); String s = new String(); • Obtaining String length and Retrieving Individual Characters in a string • String Concatenation (concat) • Substrings (substring(index), substring(start, end)) • Comparisons (equals, compareTo) • String Conversions • Finding a Character or a Substring in a String • Conversions between Strings and Arrays • Converting Characters and Numeric Values to Strings
  • 553.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Constructing Strings String newString = new String(stringLiteral); String message = new String("Welcome to Java"); Since strings are used frequently, Java provides a shorthand initializer for creating a string: String message = "Welcome to Java";
  • 554.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Strings Are Immutable A String object is immutable; its contents cannot be changed. Does the following code change the contents of the string? String s = "Java"; s = "HTML";
  • 555.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Code (1 of 5)
  • 556.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Code (2 of 5)
  • 557.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Interned Strings Since strings are immutable and are frequently used, to improve efficiency and save memory, the JVM uses a unique instance for string literals with the same character sequence. Such an instance is called interned. For example, the following statements:
  • 558.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Examples (1 of 4) String s1 = "Welcome to Java"; String s2 = new String("Welcome to Java"); String s3 = "Welcome to Java"; System.out.println("s1 == s2 is " + (s1 == s2)); System.out.println("s1 == s3 is " + (s1 == s3)); : String Interned string object for "Welcome to Java" : String A string object for "Welcome to Java" s1 s2 s3 display s1 == s is false s1 == s3 is true A new object is created if you use the new operator. If you use the string initializer, no new object is created if the interned object is already created.
  • 559.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Code (3 of 5)
  • 560.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Code (4 of 5)
  • 561.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Code (5 of 5)
  • 562.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Replacing and Splitting Strings (1 of 2) java.lang.String +replace(oldChar: char, newChar: char): String +replaceFirst(oldString: String, newString: String): String +replaceAll(oldString: String, newString: String): String +split(delimiter: String): String[] Returns a new string that replaces all matching character in this string with the new character. Returns a new string that replaces the first matching substring in this string with the new substring. Returns a new string that replace all matching substrings in this string with the new substring. Returns an array of strings consisting of the substrings split by the delimiter.
  • 563.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Examples (2 of 4) "Welcome".replace('e', 'A') returns a new string, WAlcomA. "Welcome".replaceFirst("e", "AB") returns a new string, WABlcome. "Welcome".replace("e", "AB") returns a new string, WABlcomAB. "Welcome".replace("el", "AB") returns a new string, WABcome.
  • 564.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Splitting a String String[] tokens = "Java#HTML#Perl".split("#", 0); for (int i = 0; i < tokens.length; i++) System.out.print(tokens[i] + " "); displays Java HTML Perl
  • 565.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Matching, Replacing and Splitting by Patterns (1 of 3) You can match, replace, or split a string by specifying a pattern. This is an extremely useful and powerful feature, commonly known as regular expression. Regular expression is complex to beginning students. For this reason, two simple patterns are used in this section. Please refer to Supplement III.F, “Regular Expressions,” for further studies. "Java".matches("Java"); "Java".equals("Java"); "Java is fun".matches("Java.*"); "Java is cool".matches("Java.*");
  • 566.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Matching, Replacing and Splitting by Patterns (2 of 3) The replaceAll, replaceFirst, and split methods can be used with a regular expression. For example, the following statement returns a new string that replaces $, +, or # in "a+b$#c" by the string NNN. String s = "a+b$#c".replaceAll("[$+#]", "NNN"); System.out.println(s); Here the regular expression [$+#] specifies a pattern that matches $, +, or #. So, the output is aNNNbNNNNNNc.
  • 567.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Matching, Replacing and Splitting by Patterns (3 of 3) The following statement splits the string into an array of strings delimited by some punctuation marks. String[] tokens = "Java,C?C#,C++".split("[.,:;?]"); for (int i = 0; i < tokens.length; i++) System.out.println(tokens[i]);
  • 568.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Convert Character and Numbers to Strings The String class provides several static valueOf methods for converting a character, an array of characters, and numeric values to strings. These methods have the same name valueOf with different argument types char, char[], double, long, int, and float. For example, to convert a double value to a string, use String.valueOf(5.44). The return value is string consists of characters ‘5’, ‘.’, ‘4’, and ‘4’.
  • 569.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved StringBuilder and StringBuffer The StringBuilder/StringBuffer class is an alternative to the String class. In general, a StringBuilder/StringBuffer can be used wherever a string is used. StringBuilder/StringBuffer is more flexible than String. You can add, insert, or append new contents into a string buffer, whereas the value of a String object is fixed once the string is created.
  • 570.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved StringBuilder Constructors java.lang.StringBuilder +StringBuilder() +StringBuilder(capacity: int) +StringBuilder(s: String) Constructs an empty string builder with capacity 16. Constructs a string builder with the specified capacity. Constructs a string builder with the specified string.
  • 571.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Modifying Strings in the Builder
  • 572.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Examples (3 of 4) stringBuilder.append("Java"); stringBuilder.insert(11, "HTML and "); stringBuilder.delete(8, 11) changes the builder to Welcome Java. stringBuilder.deleteCharAt(8) changes the builder to Welcome o Java. stringBuilder.reverse() changes the builder to avaJ ot emocleW. stringBuilder.replace(11, 15, "HTML") changes the builder to Welcome to HTML. stringBuilder.setCharAt(0, 'w') sets the builder to welcome to Java.
  • 573.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The toString, capacity, length, setLength, and charAt Methods java.lang.StringBuilder +toString(): String +capacity(): int +charAt(index: int): char +length(): int +setLength(newLength: int): void +substring(startIndex: int): String +substring(startIndex: int, endIndex: int): String +trimToSize(): void Returns a string object from the string builder. Returns the capacity of this string builder. Returns the character at the specified index. Returns the number of characters in this builder. Sets a new length in this builder. Returns a substring starting at startIndex. Returns a substring from startIndex to endIndex-1. Reduces the storage size used for the string builder.
  • 574.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Checking Palindromes Ignoring Non-alphanumeric Characters This example gives a program that counts the number of occurrence of each letter in a string. Assume the letters are not case-sensitive. PalindromeIgnoreNonAlphanumeric
  • 575.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Regular Expressions A regular expression (abbreviated regex) is a string that describes a pattern for matching a set of strings. Regular expression is a powerful tool for string manipulations. You can use regular expressions for matching, replacing, and splitting strings.
  • 576.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Matching Strings "Java".matches("Java"); "Java".equals("Java"); "Java is fun".matches("Java.*") "Java is cool".matches("Java.*") "Java is powerful".matches("Java.*")
  • 577.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Regular Expression Syntax
  • 578.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Replacing and Splitting Strings (2 of 2) java.lang.String +matches(regex: String): boolean +replaceAll(regex: String, replacement: String): String +replaceFirst(regex: String, replacement: String): String +split(regex: String): String[] Returns true if this string matches the pattern. Returns a new string that replaces all matching substrings with the replacement. Returns a new string that replaces the first matching substring with the replacement. Returns an array of strings consisting of the substrings split by the matches.
  • 579.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Examples (4 of 4) String s = "Java Java Java".replaceAll("vw", "wi") ; String s = "Java Java Java".replaceFirst("vw", "wi") ; String[] s = "Java1HTML2Perl".split("d");
  • 580.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.
  • 581.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introduction to Java Programming and Data Structures Thirteenth Edition Chapter 11 Inheritance and Polymorphism Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 582.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Motivations Suppose you will 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? The answer is to use inheritance.
  • 583.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (1 of 2) 11.1 To define a subclass from a superclass through inheritance (§11.2). 11.2 To invoke the superclass’s constructors and methods using the super keyword (§11.3). 11.3 To override instance methods in the subclass (§11.4). 11.4 To distinguish differences between overriding and overloading (§11.5). 11.5 To explore the toString() method in the Object class (§11.6). 11.6 To discover polymorphism and dynamic binding (§§11.7–11.8). 11.7 To describe casting and explain why explicit downcasting is necessary (§11.9). 11.8 To explore the equals method in the Object class (§11.10).
  • 584.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (2 of 2) 11.9 To store, retrieve, and manipulate objects in an ArrayList (§11.11). 11.10 To construct an array list from an array, to sort and shuffle a list, and to obtain max and min element from a list (§11.12). 11.11 To implement a Stack class using ArrayList (§11.13). 11.12 To enable data and methods in a superclass accessible from subclasses using the protected visibility modifier (§11.14). 11.13 To prevent class extending and method overriding using the final modifier (§11.14). 11.14 To automatically generate boilerplate code using Lombok (§11.16).
  • 585.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Superclasses and Subclasses GeometricObject -color: String -filled: boolean -dateCreated: java.util.Date +GeometricObject() +GeometricObject(color: String, filled: boolean) +getColor(): String +setColor(color: String): void +isFilled(): boolean +setFilled(filled: boolean): void +getDateCreated(): java.util.Date +toString(): String The color of the object (default: white). Indicates whether the object is filled with a color (default: false). The date when the object was created. Creates a GeometricObject. Creates a GeometricObject with the specified color and filled values. Returns the color. Sets a new color. Returns the filled property. Sets a new filled property. Returns the dateCreated. Returns a string representation of this object. Circle -radius: double +Circle() +Circle(radius: double) +Circle(radius: double, color: String, filled: boolean) +getRadius(): double +setRadius(radius: double): void +getArea(): double +getPerimeter(): double +getDiameter(): double +printCircle(): void Rectangle -width: double -height: double +Rectangle() +Rectangle(width: double, height: double) +Rectangle(width: double, height: double color: String, filled: boolean) +getWidth(): double +setWidth(width: double): void +getHeight(): double +setHeight(height: double): void +getArea(): double +getPerimeter(): double GeometricObject Circle Rectangle TestCircleRectangle
  • 586.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Are Superclass’s Constructor Inherited? No. They are not inherited. They are invoked explicitly or implicitly. Explicitly using the super keyword. A constructor is used to construct an instance of a class. Unlike properties and methods, a superclass's constructors are not inherited in the subclass. They can only be invoked from the subclasses' constructors, using the keyword super. If the keyword super is not explicitly used, the superclass's no- arg constructor is automatically invoked.
  • 587.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Superclass’s Constructor Is Always Invoked A constructor may invoke an overloaded constructor or its superclass’s constructor. If none of them is invoked explicitly, the compiler puts super() as the first statement in the constructor. For example, public A() { } is equivalent to public A() { super(); } public A(double d) { // some statements } is equivalent to public A(double d) { super(); // some statements }
  • 588.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Using the Keyword super The keyword super refers to the superclass of the class in which super appears. This keyword can be used in two ways: • To call a superclass constructor • To call a superclass method
  • 589.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Caution You must use the keyword super to call the superclass constructor. Invoking a superclass constructor’s name in a subclass causes a syntax error. Java requires that the statement that uses the keyword super appear first in the constructor.
  • 590.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Constructor Chaining (1 of 2) Constructing an instance of a class invokes all the superclasses’ constructors along the inheritance chain. This is known as constructor chaining. public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); } } class Employee extends Person { public Employee() {
  • 591.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Constructor Chaining (2 of 2) this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); } public Employee(String s) { System.out.println(s); } } class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } }
  • 592.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Execution (1 of 9)
  • 593.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Execution (2 of 9)
  • 594.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Execution (3 of 9)
  • 595.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Execution (4 of 9)
  • 596.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Execution (5 of 9)
  • 597.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Execution (6 of 9)
  • 598.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Execution (7 of 9)
  • 599.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Execution (8 of 9)
  • 600.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Execution (9 of 9)
  • 601.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example on the Impact of a Superclass Without no-arg Constructor Find out the errors in the program: public class Apple extends Fruit { } class Fruit { public Fruit(String name) { System.out.println("Fruit's constructor is invoked"); } }
  • 602.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Defining a Subclass A subclass inherits from a superclass. You can also: • Add new properties • Add new methods • Override the methods of the superclass
  • 603.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Calling Superclass Methods You could rewrite the printCircle() method in the Circle class as follows: public void printCircle() { System.out.println("The circle is created " + super.getDateCreated() + " and the radius is " + radius); }
  • 604.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Overriding Methods in the Superclass A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to modify the implementation of a method defined in the superclass. This is referred to as method overriding. public class Circle extends GeometricObject { // Other methods are omitted /** Override the toString method defined in GeometricObject */ public String toString() { return super.toString() + "nradius is " + radius; } }
  • 605.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Note (1 of 4) An instance method can be overridden only if it is accessible. Thus a private method cannot be overridden, because it is not accessible outside its own class. If a method defined in a subclass is private in its superclass, the two methods are completely unrelated.
  • 606.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Note (2 of 4) Like an instance method, a static method can be inherited. However, a static method cannot be overridden. If a static method defined in the superclass is redefined in a subclass, the method defined in the superclass is hidden.
  • 607.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Overriding versus Overloading public class Test { public static void main(String[] args) { A a = new A(); a.p(10); a.p(10.0); } } class B { public void p(double i) { System.out.println(i * 2); } } class A extends B { // This method overrides the method in B public void p(double i) { System.out.println(i); } } public class Test { public static void main(String[] args) { A a = new A(); a.p(10); a.p(10.0); } } class B { public void p(double i) { System.out.println(i * 2); } } class A extends B { // This method overloads the method in B public void p(int i) { System.out.println(i); } }
  • 608.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Object Class and Its Methods Every class in Java is descended from the java.lang.Object class. If no inheritance is specified when a class is defined, the superclass of the class is Object. public class Circle { ... } Equivalent public class Circle extends Object { ... }
  • 609.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The toString() Method in Object The toString() method returns a string representation of the object. The default implementation returns a string consisting of a class name of which the object is an instance, the at sign (@), and a number representing this object. Loan loan = new Loan(); System.out.println(loan.toString()); The code displays something like Loan@15037e5 . This message is not very helpful or informative. Usually you should override the toString method so that it returns a digestible string representation of the object.
  • 610.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Polymorphism Polymorphism means that a variable of a supertype can refer to a subtype object. A class defines a type. A type defined by a subclass is called a subtype, and a type defined by its superclass is called a supertype. Therefore, you can say that Circle is a subtype of GeometricObject and GeometricObject is a supertype for Circle. PolymorphismDemo
  • 611.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Polymorphism, Dynamic Binding and Generic Programming (1 of 2) DynamicBindingDemo
  • 612.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Polymorphism, Dynamic Binding and Generic Programming (2 of 2) An object of a subtype can be used wherever its supertype value is required. This feature is known as polymorphism. When the method m(Object x) is executed, the argument x’s toString method is invoked. x may be an instance of GraduateStudent, Student, Person, or Object. Classes GraduateStudent, Student, Person, and Object have their own implementation of the toString method. Which implementation is used will be determined dynamically by the Java Virtual Machine at runtime. This capability is known as dynamic binding.
  • 613.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Dynamic Binding Dynamic binding works as follows: Suppose an object o is an instance of classes 1 2 n-1 n C , C , , C , and C , where 1 C is a subclass of 2 2 C , C is a subclass of 3 n-1 C , , and C is a subclass of n C . That is, n C is the most general class, and 1 C is the most specific class. In Java, n C is the Object class. If o invokes a method p, the JVM searches the implementation for the method p in 1 2 n-1 n C , C , , C and C , in this order, until it is found. Once an implementation is found, the search stops and the first-found implementation is invoked. Cn Cn-1 . . . . . C2 C1 Object Since o is an instance of C1, o is also an instance of C2, C3, …, Cn-1, and Cn
  • 614.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Method Matching versus Binding Matching a method signature and binding a method implementation are two issues. The compiler finds a matching method according to parameter type, number of parameters, and order of the parameters at compilation time. A method may be implemented in several subclasses. The Java Virtual Machine dynamically binds the implementation of the method at runtime.
  • 615.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Generic Programming (1 of 2) public class PolymorphismDemo { public static void main(String[] args) { m(new GraduateStudent()); m(new Student()); m(new Person()); m(new Object()); } public static void m(Object x) { System.out.println(x.toSt ring()); } } class GraduateStudent extends Student { } class Student extends Person { public String toString() { return "Student"; } } class Person extends Object { public String toString() { return "Person"; } }
  • 616.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Generic Programming (2 of 2) Polymorphism allows methods to be used generically for a wide range of object arguments. This is known as generic programming. If a method’s parameter type is a superclass (e.g., Object), you may pass an object to this method of any of the parameter’s subclasses (e.g., Student or String). When an object (e.g., a Student object or a String object) is used in the method, the particular implementation of the method of the object that is invoked (e.g., toString) is determined dynamically.
  • 617.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Casting Objects You have already used the casting operator to convert variables of one primitive type to another. Casting can also be used to convert an object of one class type to another within an inheritance hierarchy. In the preceding section, the statement m(new Student()); assigns the object new Student() to a parameter of the Object type. This statement is equivalent to:
  • 618.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Why Casting Is Necessary? Suppose you want to assign the object reference o to a variable of the Student type using the following statement: Student b = o; A compile error would occur. Why does the statement Object o = new Student() work and the statement Student b = o doesn’t? This is because a Student object is always an instance of Object, but an Object is not necessarily an instance of Student. Even though you can see that o is really a Student object, the compiler is not so clever to know it. To tell the compiler that o is a Student object, use an explicit casting. The syntax is similar to the one used for casting among primitive data types. Enclose the target object type in parentheses and place it before the object to be cast, as follows: Student b = (Student)o; // Explicit casting
  • 619.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Casting From Superclass to Subclass Explicit casting must be used when casting an object from a superclass to a subclass. This type of casting may not always succeed. Apple x = (Apple)fruit; Orange x = (Orange)fruit;
  • 620.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The instanceof Operator Use the instanceof operator to test whether an object is an instance of a class: Object myObject = new Circle(); ... // Some lines of code /** Perform casting if myObject is an instance of Circle */ if (myObject instanceof Circle) { System.out.println("The circle diameter is " + ((Circle)myObject).getDiameter()); ... }
  • 621.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved 621 Java 16 instanceof Pattern Matching When using the if statement to test if an object is an instance of a class, you can specify a binding variable. If the result of the instanceof operator is true, then the object being tested is assigned to the binding variable. This new syntax, known as instanceof pattern matching, became a standard feature since Java 16. You can simplify the code in lines 15-24 using this new feature as follows:
  • 622.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved 622 Java 16 New Features on instanceof if (myObject instanceof Circle circle) { System.out.println("The circle area is " + circle.getArea()); System.out.println("The circle diameter is " + circle.getDiameter()); } else if (myObject instanceof Rectangle rectangle) { System.out.println("The rectangle area is " + rectangle.getArea()); }
  • 623.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved TIP To help understand casting, you may also consider the analogy of fruit, apple, and orange with the Fruit class as the superclass for Apple and Orange. An apple is a fruit, so you can always safely assign an instance of Apple to a variable for Fruit. However, a fruit is not necessarily an apple, so you have to use explicit casting to assign an instance of Fruit to a variable of Apple.
  • 624.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example: Demonstrating Polymorphism and Casting This example creates two geometric objects: a circle, and a rectangle, invokes the displayGeometricObject method to display the objects. The displayGeometricObject displays the area and diameter if the object is a circle, and displays area if the object is a rectangle. CastingDemo
  • 625.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The equals Method The equals() method compares the contents of two objects. The default implementation of the equals method in the Object class is as follows: public boolean equals(Object obj){ return this == obj; } For example, the equals method is overridden in the Circle class. public boolean equals(Object o) { if (o instanceof Circle) { return radius ==((Circle)o).radius; } else return false; }
  • 626.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Note (3 of 4) The == comparison operator is used for comparing two primitive data type values or for determining whether two objects have the same references. The equals method is intended to test whether two objects have the same contents, provided that the method is modified in the defining class of the objects. The == operator is stronger than the equals method, in that the == operator checks whether the two reference variables refer to the same object.
  • 627.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The ArrayList Class You can create an array to store objects. But the array’s size is fixed once the array is created. Java provides the ArrayList class that can be used to store an unlimited number of objects. java.util.ArrayList<E> +ArrayList() +add(o: E) : void +add(index: int, o: E) : void +clear(): void +contains(o: Object): boolean +get(index: int) : E +indexOf(o: Object) : int +isEmpty(): boolean +lastIndexOf(o: Object) : int +remove(o: Object): boolean +size(): int +remove(index: int) : boolean +set(index: int, o: E) : E Creates an empty list. Appends a new element o at the end of this list. Adds a new element o at the specified index in this list. Removes all the elements from this list. Returns true if this list contains the element o. Returns the element from this list at the specified index. Returns the index of the first matching element in this list. Returns true if this list contains no elements. Returns the index of the last matching element in this list. Removes the element o from this list. Returns the number of elements in this list. Removes the element at the specified index. Sets the element at the specified index.
  • 628.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Generic Type ArrayList is known as a generic class with a generic type E. You can specify a concrete type to replace E when creating an ArrayList. For example, the following statement creates an ArrayList and assigns its reference to variable cities. This ArrayList object can be used to store strings. ArrayList<String> cities = new ArrayList<String>(); ArrayList<String> cities = new ArrayList<>(); TestArrayList
  • 629.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Differences and Similarities Between Arrays and ArrayList Operation Array ArrayList Creating an array/ArrayList String[] a = new String[10] ArrayList<String> list = new ArrayList<>(); Accessing an element a[index] list.get(index); Updating an element a[index] = "London"; list.set(index, "London"); Returning size a.length list.size(); Adding a new element Blank list.add("London"); Inserting a new element Blank list.add(index, "London"); Removing an element Blank list.remove(index); Removing an element Blank list.remove(Object); Removing all elements Blank list.clear(); DistinctNumbers
  • 630.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Array Lists from/to Arrays Creating an ArrayList from an array of objects: String[] array = {"red", "green", "blue"}; ArrayList<String> list = new ArrayList<>(Arrays.asList(array)); Creating an array of objects from an ArrayList: String[] array1 = new String[list.size()]; list.toArray(array1);
  • 631.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved max and min in an Array List String[] array = {"red", "green", "blue"}; System.out.pritnln(java.util.Collections.max( new ArrayList<String>(Arrays.asList(array))); String[] array = {"red", "green", "blue"}; System.out.pritnln(java.util.Collections.min( new ArrayList<String>(Arrays.asList(array)));
  • 632.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Shuffling an Array List Integer[] array = {3, 5, 95, 4, 15, 34, 3, 6, 5}; ArrayList<Integer> list = new ArrayList<>(Arrays.asList(array)); java.util.Collections.shuffle(list); System.out.println(list);
  • 633.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Stack Animation https://liveexample.pearsoncmg.com/dsanimation/StackeBook.html
  • 634.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The MyStack Classes A stack to hold objects. MyStack MyStack -list: ArrayList +isEmpty(): boolean +getSize(): int +peek(): Object +pop(): Object +push(o: Object): void +search(o: Object): int Returns true if this stack is empty. Returns the number of elements in this stack. Returns the top element in this stack. Returns and removes the top element in this stack. Adds a new element to the top of this stack. Returns the position of the first element in the stack from the top that matches the specified element. A list to store elements.
  • 635.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The protected Modifier • The protected modifier can be applied on data and methods in a class. A protected data or a protected method in a public class can be accessed by any class in the same package or its subclasses, even if the subclasses are in a different package. • private, default, protected, public private, none (if no modifier is used), protected, public Visibility increases
  • 636.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Accessibility Summary Modifier on members in a class Accessed from the same class Accessed from the same package Accessed from a subclass Accessed from a different package public sign sign sign sign protected sign sign sign Blank default sign sign Blank Blank private sign Blank Blank Blank
  • 637.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Visibility Modifiers public class C1 { public int x; protected int y; int z; private int u; protected void m() { } } public class C2 { C1 o = new C1(); can access o.x; can access o.y; can access o.z; cannot access o.u; can invoke o.m(); } public class C3 extends C1 { can access x; can access y; can access z; cannot access u; can invoke m(); } package p1; public class C4 extends C1 { can access x; can access y; cannot access z; cannot access u; can invoke m(); } package p2; public class C5 { C1 o = new C1(); can access o.x; cannot access o.y; cannot access o.z; cannot access o.u; cannot invoke o.m(); }
  • 638.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved A Subclass Cannot Weaken the Accessibility A subclass may override a protected method in its superclass and change its visibility to public. However, a subclass cannot weaken the accessibility of a method defined in the superclass. For example, if a method is defined as public in the superclass, it must be defined as public in the subclass.
  • 639.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Note (4 of 4) The modifiers are used on classes and class members (data and methods), except that the final modifier can also be used on local variables in a method. A final local variable is a constant inside a method.
  • 640.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The final Modifier • The final class cannot be extended: final class Math { ... } • The final variable is a constant: final static double PI = 3.14159; • The final method cannot be overridden by its subclasses.
  • 641.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.
  • 642.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved 642 Lombok: Generating Boilerplate Code Using Annotations When you write Java code, there are lot of getter and setter methods. It is tedious to write all these boilerplate code. Project Lombok comes to rescue. Project Lombok is a Java library that provides annotations to tell the Java compiler to automatically generate boilerplate code such as getter and setter methods for data fields. To use Lombok, you need download a jar file named lombok.jar from https://projectlombok.org/download.
  • 643.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introduction to Java Programming and Data Structures Thirteenth Edition Chapter 12 Exception Handling and Text IO Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 644.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can continue to run or terminate gracefully? This is the subject we will introduce in this chapter.
  • 645.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (1 of 2) 12.1 To get an overview of exceptions and exception handling (§12.2). 12.2 To explore the advantages of using exception handling (§12.2). 12.3 To distinguish exception types: Error (fatal) vs. Exception (nonfatal) and checked versus unchecked (§12.3). 12.4 To declare exceptions in a method header (§12.4.1). 12.5 To throw exceptions in a method (§12.4.2). 12.6 To write a try-catch block to handle exceptions (§12.4.3). 12.7 To explain how an exception is propagated (§12.4.3). 12.8 To obtain information from an exception object (§12.4.4). 12.9 To develop applications with exception handling (§12.4.5). 12.10 To use the finally clause in a try-catch block (§12.5). 12.11 To use exceptions only for unexpected errors (§12.6).
  • 646.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (2 of 2) 12.12 To rethrow exceptions in a catch block (§12.7). 12.13 To create chained exceptions (§12.8). 12.14 To define custom exception classes (§12.9). 12.15 To discover file/directory properties, to delete and rename files/directories, and to create directories using the File class (§12.10). 12.16 To write data to a file using the PrintWriter class (§12.11.1). 12.17 To use try-with-resources to ensure that the resources are closed automatically (§12.11.2). 12.18 To read data from a file using the Scanner class (§12.11.3). 12.19 To understand how data is read using a Scanner (§12.11.4). 12.20 To develop a program that replaces text in a file (§12.11.5). 12.21 To read data from the Web (§12.12). 12.22 To develop a Web crawler (§12.13).
  • 647.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Exception-Handling Overview Show runtime error Quotient Fix it using an if statement QuotientWithIf With a method QuotientWithMethod
  • 648.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Exception Advantages QuotientWithException Now you see the advantages of using exception handling. It enables a method to throw an exception to its caller. Without this capability, a method must handle the exception or terminate the program.
  • 649.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Handling InputMismatchException InputMismatchExceptionDemo By handling InputMismatchException, your program will continuously read an input until it is correct.
  • 650.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Exception Types LinkageError Error Throwable ClassNotFoundException VirtualMachineError IOException Exception RuntimeException Object ArithmeticException NullPointerException IndexOutOfBoundsException Many more classes Many more classes Many more classes IllegalArgumentException
  • 651.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved System Errors
  • 652.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Exceptions
  • 653.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Runtime Exceptions
  • 654.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Checked Exceptions versus Unchecked Exceptions RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions.
  • 655.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Unchecked Exceptions (1 of 2) In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example, a NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it; an IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array. These are the logic errors that should be corrected in the program. Unchecked exceptions can occur anywhere in the program. To avoid cumbersome overuse of try-catch blocks, Java does not mandate you to write code to catch unchecked exceptions.
  • 656.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Unchecked Exceptions (2 of 2)
  • 657.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Declaring, Throwing, and Catching Exceptions method1() { try { invoke method2; } catch (Exception ex) { Process exception; } } method2() throws Exception { if (an error occurs) { throw new Exception(); } } catch exception throw exception declare exception
  • 658.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Declaring Exceptions Every method must state the types of checked exceptions it might throw. This is known as declaring exceptions. public void myMethod() throws IOException public void myMethod() throws IOException, OtherException
  • 659.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Throwing Exceptions When the program detects an error, the program can create an instance of an appropriate exception type and throw it. This is known as throwing an exception. Here is an example, throw new TheException(); TheException ex = new TheException(); throw ex;
  • 660.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }
  • 661.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Catching Exceptions (1 of 2) try { statements; // Statements that may throw exceptions } catch (Exception1 exVar1) { handler for exception1; } catch (Exception2 exVar2) { handler for exception2; } ... catch (ExceptionN exVar3) { handler for exceptionN; }
  • 662.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Catching Exceptions (2 of 2) try catch try catch try catch An exception is thrown in method3 Call Stack main method main method method1 main method method1 main method method1 method2 method2 method3
  • 663.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Catch or Declare Checked Exceptions (1 of 2) Suppose p2 is defined as follows: void p2() throws IOException { if (a file does not exist) { throw new IOException("File does not exist"); } ... }
  • 664.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Catch or Declare Checked Exceptions (2 of 2)
  • 665.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example: Declaring, Throwing, and Catching Exceptions • Objective: This example demonstrates declaring, throwing, and catching exceptions by modifying the setRadius method in the Circle class defined in Chapter 9. The new setRadius method throws an exception if radius is negative. CircleWithException TestCircleWithException
  • 666.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Rethrowing Exceptions try { statements; } catch(TheException ex) { perform operations before exits; throw ex; }
  • 667.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The finally Clause try { statements; } catch(TheException ex){ handling ex; } finally { finalStatements; }
  • 668.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace a Program Execution (1 of 11)
  • 669.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace a Program Execution (2 of 11)
  • 670.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace a Program Execution (3 of 11)
  • 671.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace a Program Execution (4 of 11)
  • 672.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace a Program Execution (5 of 11)
  • 673.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace a Program Execution (6 of 11)
  • 674.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace a Program Execution (7 of 11)
  • 675.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace a Program Execution (8 of 11)
  • 676.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace a Program Execution (9 of 11)
  • 677.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace a Program Execution (10 of 11)
  • 678.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace a Program Execution (11 of 11)
  • 679.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Cautions When Using Exceptions • 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, and propagating the errors to the calling methods.
  • 680.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved When to Throw Exceptions • An exception occurs in a method. If you want the exception to be processed by its caller, you should create an exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw it.
  • 681.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved When to Use Exceptions (1 of 2) When should you use the try-catch block in the code? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code try { System.out.println(refVar.toString()); } catch (NullPointerException ex) { System.out.println("refVar is null"); }
  • 682.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved When to Use Exceptions (2 of 2) is better to be replaced by if (refVar != null) System.out.println(refVar.toString()); else System.out.println("refVar is null");
  • 683.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Defining Custom Exception Classes • Use the exception classes in the API whenever possible. • Define custom exception classes if the predefined classes are not sufficient. • Define custom exception classes by extending Exception or a subclass of Exception.
  • 684.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Custom Exception Class Example In Listing 13.8, the setRadius method throws an exception if the radius is negative. Suppose you wish to pass the radius to the handler, you have to create a custom exception class. InvalidRadiusException CircleWithRadiusException TestCircleWithRadiusException
  • 685.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Assertions An assertion is a Java statement that enables you to assert an assumption about your program. An assertion contains a Boolean expression that should be true during program execution. Assertions can be used to assure program correctness and avoid logic errors.
  • 686.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Declaring Assertions An assertion is declared using the new Java keyword assert in JDK 1.4 as follows: assert assertion; or assert assertion : detailMessage; where assertion is a Boolean expression and detailMessage is a primitive-type or an Object value.
  • 687.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Executing Assertions When an assertion statement is executed, Java evaluates the assertion. If it is false, an AssertionError will be thrown. The AssertionError class has a no-arg constructor and seven overloaded single-argument constructors of type int, long, float, double, boolean, char, and Object. For the first assert statement with no detail message, the no-arg constructor of AssertionError is used. For the second assert statement with a detail message, an appropriate AssertionError constructor is used to match the data type of the message. Since AssertionError is a subclass of Error, when an assertion becomes false, the program displays a message on the console and exits.
  • 688.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Executing Assertions Example public class AssertionDemo { public static void main(String[] args) { int i; int sum = 0; for (i = 0; i < 10; i++) { sum += i; } assert i == 10; assert sum > 10 && sum < 5 * 10 : "sum is " + sum; } }
  • 689.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Compiling Programs With Assertions Since assert is a new Java keyword introduced in JDK 1.4, you have to compile the program using a JDK 1.4 compiler. Furthermore, you need to include the switch –source 1.4 in the compiler command as follows: javac –source 1.4 AssertionDemo.java NOTE: If you use JDK 1.5, there is no need to use the – source 1.4 option in the command.
  • 690.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Running Programs With Assertions By default, the assertions are disabled at runtime. To enable it, use the switch –enableassertions, or –ea for short, as follows: java –ea AssertionDemo Assertions can be selectively enabled or disabled at class level or package level. The disable switch is – disableassertions or –da for short. For example, the following command enables assertions in package package1 and disables assertions in class Class1. java –ea:package1 –da:Class1 AssertionDemo
  • 691.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Using Exception Handling or Assertions (1 of 4) Assertion should not be used to replace exception handling. Exception handling deals with unusual circumstances during program execution. Assertions are to assure the correctness of the program. Exception handling addresses robustness and assertion addresses correctness. Like exception handling, assertions are not used for normal tests, but for internal consistency and validity checks. Assertions are checked at runtime and can be turned on or off at startup time.
  • 692.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Using Exception Handling or Assertions (2 of 4) Do not use assertions for argument checking in public methods. Valid arguments that may be passed to a public method are considered to be part of the method’s contract. The contract must always be obeyed whether assertions are enabled or disabled. For example, the following code in the Circle class should be rewritten using exception handling. public void setRadius(double newRadius) { assert newRadius >= 0; radius = newRadius; }
  • 693.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Using Exception Handling or Assertions (3 of 4) Use assertions to reaffirm assumptions. This gives you more confidence to assure correctness of the program. A common use of assertions is to replace assumptions with assertions in the code.
  • 694.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Using Exception Handling or Assertions (4 of 4) Another good use of assertions is place assertions in a switch statement without a default case. For example, switch (month) { case 1: ... ; break; case 2: ... ; break; ... case 12: ... ; break; default: assert false : "Invalid month: " + month }
  • 695.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The File Class The File class is intended to provide an abstraction that deals with most of the machine-dependent complexities of files and path names in a machine-independent fashion. The filename is a string. The File class is a wrapper class for the file name and its directory path.
  • 696.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Obtaining File Properties and Manipulating File
  • 697.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Explore File Properties Objective: Write a program that demonstrates how to create files in a platform-independent way and use the methods in the File class to obtain their properties. The following figures show a sample run of the program on Windows and on Unix. TestFileClass
  • 698.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Text I/O A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes. The objects contain the methods for reading/writing data from/to a file. This section introduces how to read/write strings and numeric values from/to a text file using the Scanner and PrintWriter classes.
  • 699.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Writing Data Using PrintWriter java.io.PrintWriter +PrintWriter(filename: String) +print(s: String): void +print(c: char): void +print(cArray: char[]): void +print(i: int): void +print(l: long): void +print(f: float): void +print(d: double): void +print(b: boolean): void Also contains the overloaded println methods. Also contains the overloaded printf methods. . Creates a PrintWriter for the specified file. Writes a string. Writes a character. Writes an array of character. Writes an int value. Writes a long value. Writes a float value. Writes a double value. Writes a boolean value. A println method acts like a print method; additionally it prints a line separator. The line separator string is defined by the system. It is rn on Windows and n on Unix. The printf method was introduced in §4.6, “Formatting Console Output and Strings.” WriteData
  • 700.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Try-with-resources Programmers often forget to close the file. JDK 7 provides the followings new try-with-resources syntax that automatically closes the files. try (declare and create resources) { Use the resource to process the file; } WriteDataWithAutoClose
  • 701.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Reading Data Using Scanner java.util.Scanner +Scanner(source: File) +Scanner(source: String) +close() +hasNext(): boolean +next(): String +nextByte(): byte +nextShort(): short +nextInt(): int +nextLong(): long +nextFloat(): float +nextDouble(): double +useDelimiter(pattern: String): Scanner Creates a Scanner object to read data from the specified file. Creates a Scanner object to read data from the specified string. Closes this scanner. Returns true if this scanner has another token in its input. Returns next token as a string. Returns next token as a byte. Returns next token as a short. Returns next token as an int. Returns next token as a long. Returns next token as a float. Returns next token as a double. Sets this scanner’s delimiting pattern. ReadData
  • 702.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem: Replacing Text Write a class named ReplaceText that replaces a string in a text file with a new string. The filename and strings are passed as command-line arguments as follows: java ReplaceText sourceFile targetFile oldString newString For example, invoking java ReplaceText FormatString.java t.txt StringBuilder StringBuffer replaces all the occurrences of StringBuilder by StringBuffer in FormatString.java and saves the new file in t.txt. ReplaceText
  • 703.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Reading Data From the Web (1 of 2) Just like you can read data from a file on your computer, you can read data from a file on the Web.
  • 704.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Reading Data From the Web (2 of 2) URL url = new URL("www.google.com/index.html"); After a URL object is created, you can use the openStream() method defined in the URL class to open an input stream and use this stream to create a Scanner object as follows: Scanner input = new Scanner(url.openStream()); ReadFileFromURL
  • 705.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Case Study: Web Crawler (1 of 3) This case study develops a program that travels the Web by following hyperlinks.
  • 706.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Case Study: Web Crawler (2 of 3) The program follows the URLs to traverse the Web. To avoid that each URL is traversed only once, the program maintains two lists of URLs. One list stores the URLs pending for traversing and the other stores the URLs that have already been traversed. The algorithm for this program can be described as follows:
  • 707.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Case Study: Web Crawler (3 of 3) Add the starting URL to a list named listOfPendingURLs; while listOfPendingURLs is not empty { Remove a URL from listOfPendingURLs; if this URL is not in listOfTraversedURLs { Add it to listOfTraversedURLs; Display this URL; Exit the while loop when the size of S is equal to 100. Read the page from this URL and for each URL contained in the page { Add it to listOfPendingURLs if it is not is listOfTraversedURLs; } } } WebCrawler
  • 708.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.
  • 709.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introduction to Java Programming and Data Structures Thirteenth Edition Chapter 13 Abstract Classes and Interfaces Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 710.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Motivations • 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 to perform an action? • In order to write such code, you have to know about interfaces. An interface is for defining common behavior for classes (including unrelated classes). Before discussing interfaces, we introduce a closely related subject: abstract classes.
  • 711.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives 13.1 To design and use abstract classes (§13.2). 13.2 To generalize numeric wrapper classes, BigInteger, and BigDecimal using the abstract Number class (§13.3). 13.3 To process a calendar using the Calendar and GregorianCalendar classes (§13.4). 13.4 To specify common behavior for objects using interfaces (§13.5). 13.5 To define interfaces and define classes that implement interfaces (§13.5). 13.6 To define a natural order using the Comparable interface (§13.6). 13.7 To make objects cloneable using the Cloneable interface (§13.7). 13.8 To explore the similarities and differences among concrete classes, abstract classes, and interfaces (§13.8). 13.9 To design the Rational class for processing rational numbers (§13.9). 13.10 To design classes that follow the class-design guidelines (§13.10). 13.11 To use a simple one-line code to define a record (§13.11).
  • 712.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Abstract Classes and Abstract Methods GeometricObject Circle Rectangle TestGeometricObject
  • 713.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Abstract Method in Abstract Class An abstract method cannot be contained in a nonabstract class. If a subclass of an abstract superclass does not implement all the abstract methods, the subclass must be defined abstract. In other words, in a nonabstract subclass extended from an abstract class, all the abstract methods must be implemented, even if they are not used in the subclass.
  • 714.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Object Cannot be Created From Abstract Class An abstract class cannot be instantiated using the new operator, but you can still define its constructors, which are invoked in the constructors of its subclasses. For instance, the constructors of GeometricObject are invoked in the Circle class and the Rectangle class.
  • 715.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Abstract Class Without Abstract Method A class that contains abstract methods must be abstract. However, it is possible to define an abstract class that contains no abstract methods. In this case, you cannot create instances of the class using the new operator. This class is used as a base class for defining a new subclass.
  • 716.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Superclass of Abstract Class May Be Concrete A subclass can be abstract even if its superclass is concrete. For example, the Object class is concrete, but its subclasses, such as GeometricObject, may be abstract.
  • 717.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Concrete Method Overridden to Be Abstract A subclass can override a method from its superclass to define it abstract. This is rare, but useful when the implementation of the method in the superclass becomes invalid in the subclass. In this case, the subclass must be defined abstract.
  • 718.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Abstract Class as Type You cannot create an instance from an abstract class using the new operator, but an abstract class can be used as a data type. Therefore, the following statement, which creates an array whose elements are of GeometricObject type, is correct. GeometricObject[] geo = new GeometricObject[10];
  • 719.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Case Study: The Abstract Number Class LargestNumbers
  • 720.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Abstract Calendar Class and Its GregorianCalendar Subclass (1 of 2)
  • 721.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Abstract Calendar Class and Its GregorianCalendar Subclass (2 of 2) An instance of java.util.Date represents a specific instant in time with millisecond precision. java.util.Calendar is an abstract base class for extracting detailed information such as year, month, date, hour, minute and second from a Date object. Subclasses of Calendar can implement specific calendar systems such as Gregorian calendar, Lunar Calendar and Jewish calendar. Currently, java.util.GregorianCalendar for the Gregorian calendar is supported in the Java API.
  • 722.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The GregorianCalendar Class You can use new GregorianCalendar() to construct a default GregorianCalendar with the current time and use new GregorianCalendar(year, month, date) to construct a GregorianCalendar with the specified year, month, and date. The month parameter is 0-based, i.e., 0 is for January.
  • 723.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The get Method in Calendar Class The get(int field) method defined in the Calendar class is useful to extract the date and time information from a Calendar object. The fields are defined as constants, as shown in the following. Constant Description YEAR The year of the calendar. MONTH The month of the calendar, with 0 for January. DATE The day of the calendar. HOUR The hour of the calendar (12-hour notation). HOUR_OF_DAY The hour of the calendar (24-hour notation). MINUTE The minute of the calendar. SECOND The second of the calendar. DAY_OF_WEEK The day number within the week, with 1 for Sunday. DAY_OF_MONTH Same as DATE. DAY_OF_YEAR The day number in the year, with I for the first day of the year. WEEK_OF_MONTH The week number within the month, with I for the first week. WEEK_OF_YEAR The week number within the year, with 1 for the first week. AM_PM Indicator for AM or PM (0 for AM and I for PM).
  • 724.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Getting Date/Time Information From Calendar TestCalendar
  • 725.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Interfaces What is an interface? Why is an interface useful? How do you define an interface? How do you use an interface?
  • 726.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved What Is an Interface? Why Is an Interface Useful? An interface is a classlike construct that contains only constants and abstract methods. In many ways, an interface is similar to an abstract class, but the intent of an interface is to specify common behavior for objects. For example, you can specify that the objects are comparable, edible, cloneable using appropriate interfaces.
  • 727.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Define an Interface To distinguish an interface from a class, Java uses the following syntax to define an interface: public interface InterfaceName { constant declarations; abstract method signatures; } Example: public interface Edible { /** Describe how to eat */ public abstract String howToEat(); }
  • 728.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Interface Is a Special Class An interface is treated like a special class in Java. Each interface is compiled into a separate bytecode file, just like a regular class. Like an abstract class, you cannot create an instance from an interface using the new operator, but in most cases you can use an interface more or less the same way you use an abstract class. For example, you can use an interface as a data type for a variable, as the result of casting, and so on.
  • 729.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example (1 of 2) You can now use the Edible interface to specify whether an object is edible. This is accomplished by letting the class for the object implement this interface using the implements keyword. For example, the classes Chicken and Fruit implement the Edible interface (See TestEdible). Edible TestEdible
  • 730.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Omitting Modifiers in Interfaces All data fields are public final static and all methods are public abstract in an interface. For this reason, these modifiers can be omitted, as shown below: public interface T1 { public static final int K = 1; public abstract void p(); } Equivalent public interface T1 { int K = 1; void p(); } A constant defined in an interface can be accessed using syntax InterfaceName.CONSTANT_NAME (e.g., T1.K).
  • 731.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example: The Comparable Interface // This interface is defined in // java.lang package package java.lang; public interface Comparable<E> { public int compareTo(E o); }
  • 732.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The toString, equals, and hashCode Methods Each wrapper class overrides the toString, equals, and hashCode methods defined in the Object class. Since all the numeric wrapper classes and the Character class implement the Comparable interface, the compareTo method is implemented in these classes.
  • 733.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Integer and BigInteger Classes public class Integer extends Number implements Comparable<Integer> { // class body omitted @Override public int compareTo(Integer o) { // Implementation omitted } } public class BigInteger extends Number implements Comparable<BigInteger> { // class body omitted @Override public int compareTo(BigInteger o) { // Implementation omitted } } String and Date Classes public class String extends Object implements Comparable<String> { // class body omitted @Override public int compareTo(String o) { // Implementation omitted } } public class Date extends Object implements Comparable<Date> { // class body omitted @Override public int compareTo(Date o) { // Implementation omitted } }
  • 734.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example (2 of 2) 1. System.out.println(new Integer(3).compareTo(new Integer(5))); 2. System.out.println("ABC".compareTo("ABE")); 3. java.util.Date date1 = new java.util.Date(2013, 1, 1); 4. java.util.Date date2 = new java.util.Date(2012, 1, 1); 5. System.out.println(date1.compareTo(date2));
  • 735.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Generic sort Method Let n be an Integer object, s be a String object, and d be a Date object. All the following expressions are true. s instanceof String s instanceof Object s instanceof Comparable d instanceof java.util.Date d instanceof Object d instanceof Comparable n instanceof Integer n instanceof Object n instanceof Comparable The java.util.Arrays.sort(array) method requires that the elements in an array are instances of Comparable<E>. SortComparableObjects
  • 736.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Defining Classes to Implement Comparable ComparableRectangle SortRectangles
  • 737.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Cloneable Interfaces Marker Interface: An empty interface. A marker interface does not contain constants or methods. It is used to denote that a class possesses certain desirable properties. A class that implements the Cloneable interface is marked cloneable, and its objects can be cloned using the clone() method defined in the Object class. package java.lang; public interface Cloneable { }
  • 738.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Examples Many classes (e.g., Date and Calendar) in the Java library implement Cloneable. Thus, the instances of these classes can be cloned. For example, the following code Calendar calendar = new GregorianCalendar(2003, 2, 1); Calendar calendarCopy = (Calendar)calendar.clone(); System.out.println("calendar == calendarCopy is " + (calendar == calendarCopy)); System.out.println("calendar.equals(calendarCopy) is " + calendar.equals(calendarCopy)); displays calendar == calendarCopy is false calendar.equals(calendarCopy) is true
  • 739.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Implementing Cloneable Interface To define a custom class that implements the Cloneable interface, the class must override the clone() method in the Object class. The following code defines a class named House that implements Cloneable and Comparable. House
  • 740.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Shallow versus Deep Copy (1 of 2) House house1 = new House(1, 1750.50); House house2 = (House)house1.clone(); Shallow Copy
  • 741.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Shallow versus Deep Copy (2 of 2) House house1 = new House(1, 1750.50); House house2 = (House)house1.clone(); Deep Copy
  • 742.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Interfaces versus Abstract Classes (1 of 2) In an interface, the data must be constants; an abstract class can have all types of data. Each method in an interface has only a signature without implementation; an abstract class can have concrete methods. Blank Variables Constructors Methods Abstract class No restrictions. Constructors are invoked by subclasses through constructor chaining. An abstract class cannot be instantiated using the new operator. No restrictions. Interface All variables must be public static final No constructors. An interface cannot be instantiated using the new operator. All methods must be public abstract instance methods
  • 743.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Interfaces versus Abstract Classes (2 of 2) All classes share a single root, the Object class, but there is no single root for interfaces. Like a class, an interface also defines a type. A variable of an interface type can reference any instance of the class that implements the interface. If a class extends an interface, this interface plays the same role as a superclass. You can use an interface as a data type and cast a variable of an interface type to its subclass, and vice versa. Suppose that c is an instance of Class2. c is also an instance of Object, Class1, Interface1, Interface1_1, Interface1_2, Interface2_1, and Interface2_2.
  • 744.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Caution: Conflict Interfaces In rare occasions, a class may implement two interfaces with conflict information (e.g., two same constants with different values or two methods with same signature but different return type). This type of errors will be detected by the compiler.
  • 745.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Whether to Use an Interface or a Class? Abstract classes and interfaces can both be used to model common features. How do you decide whether to use an interface or a class? In general, a strong is-a relationship that clearly describes a parent-child relationship should be modeled using classes. For example, a staff member is a person. A weak is-a relationship, also 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 String class implements the Comparable interface. You can also use interfaces to circumvent single inheritance restriction if multiple inheritance is desired. In the case of multiple inheritance, you have to design one as a superclass, and others as interface.
  • 746.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Rational Class Rational TestRationalClass
  • 747.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Designing a Class (1 of 5) (Coherence) A class should describe a single entity, and all the class operations should logically fit together to support a coherent purpose. You can use a class for students, for example, but you should not combine students and staff in the same class, because students and staff have different entities.
  • 748.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Designing a Class (2 of 5) (Separating responsibilities) A single entity with too many responsibilities can be broken into several classes to separate responsibilities. The classes String, StringBuilder, and StringBuffer all deal with strings, for example, but have different responsibilities. The String class deals with immutable strings, the StringBuilder class is for creating mutable strings, and the StringBuffer class is similar to StringBuilder except that StringBuffer contains synchronized methods for updating strings.
  • 749.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Designing a Class (3 of 5) Classes are designed for reuse. Users can incorporate classes in many different combinations, orders, and environments. Therefore, you should design a class that imposes no restrictions on what or when the user can do with it, design the properties to ensure that the user can set properties in any order, with any combination of values, and design methods to function independently of their order of occurrence.
  • 750.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Designing a Class (4 of 5) Provide a public no-arg constructor and override the equals method and the toString method defined in the Object class whenever possible.
  • 751.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Designing a Class (5 of 5) Follow standard Java programming style and naming conventions. Choose informative names for classes, data fields, and methods. Always place the data declaration before the constructor, and place constructors before methods. Always provide a constructor and initialize variables to avoid programming errors.
  • 752.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Using Visibility Modifiers (1 of 2) Each class can present two contracts – one for the users of the class and one for the extenders of the class. Make the fields private and accessor methods public if they are intended for the users of the class. Make the fields or method protected if they are intended for extenders of the class. The contract for the extenders encompasses the contract for the users. The extended class may increase the visibility of an instance method from protected to public, or change its implementation, but you should never change the implementation in a way that violates that contract.
  • 753.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Using Visibility Modifiers (2 of 2) A class should use the private modifier to hide its data from direct access by clients. You can use get methods and set methods to provide users with access to the private data, but only to private data you want the user to see or to modify. A class should also hide methods not intended for client use. The gcd method in the Rational class is private, for example, because it is only for internal use within the class.
  • 754.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Using the Static Modifier A property that is shared by all the instances of the class should be declared as a static property.
  • 755.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved 755 Records Often you need to create a simple object to hold data. Before Java 16, you have to define a class and write a lot of boilerplate code. This is tedious, however. Since Java 14, you can define a record to simplify coding. For example, the following code defines a record for Teachers. public record Teacher(String name, java.util.Date date) {} This simple one-line code is roughly equivalent to the following class definition in LiveExample 13.14. Teacher
  • 756.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.
  • 757.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introduction to Java Programming and Data Structures Thirteenth Edition Chapter 18 Recursion Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 758.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Motivations (1 of 2) Suppose you want to find all the files under a directory that contains a particular word. How do you solve this problem? There are several ways to solve this problem. An intuitive solution is to use recursion by searching the files in the subdirectories recursively.
  • 759.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Motivations (2 of 2) H-trees, depicted in Figure 18.1, are used in a very large- scale integration (VLSI) design as a clock distribution network for routing timing signals to all parts of a chip with equal propagation delays. How do you write a program to display H-trees? A good approach is to use recursion.
  • 760.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (1 of 2) 18.1 To describe what a recursive method is and the benefits of using recursion (§18.1). 18.2 To develop recursive methods for recursive mathematical functions (§§18.2–18.3). 18.3 To explain how recursive method calls are handled in a call stack (§§18.2–18.3). 18.4 To solve problems using recursion (§18.4). 18.5 To use an overloaded helper method to derive a recursive method (§18.5). 18.6 To implement a selection sort using recursion (§18.5.1).
  • 761.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (2 of 2) 18.7 To implement a binary search using recursion (§18.5.2). 18.8 To get the directory size using recursion (§18.6). 18.9 To solve the Tower of Hanoi problem using recursion (§18.7). 18.10 To draw fractals using recursion (§18.8). 18.11 To discover the relationship and difference between recursion and iteration (§18.9). 18.12 To know tail-recursive methods and why they are desirable (§18.10).
  • 762.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Computing Factorial (1 of 11) Mathematic notation: n! = n * (n-1)!, n > 0 0! = 1 Function: factorial(0) = 1; factorial(n) = n*factorial(n-1); n > 0 ComputeFactorial
  • 763.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Computing Factorial (2 of 11) factorial(0) 1 ;  factorial(n) n*factorial(n 1);   factorial(4)
  • 764.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Computing Factorial (3 of 11) factorial(0) 1;  factorial(n) n*factorial(n 1);   factorial(4) 4 * factorial(3) 
  • 765.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Computing Factorial (4 of 11)  factorial(0) 1; factorial(n) n*factorial(n 1);   factorial(4) 4 * factorial(3)  4 * 3 * factorial(2)) 
  • 766.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Computing Factorial (5 of 11) factorial(0) 1;  factorial(n) n*factorial(n 1);   factorial(4) 4 * factorial(3)  4 * 3 * factorial(2)  4 * 3 * (2 * factorial(1)) 
  • 767.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Computing Factorial (6 of 11) factorial(0) 1;  factorial(n) n*factorial(n 1);   factorial(4) 4 * factorial(3)  4 * 3 * factorial(2)  4 * 3 * (2 * factorial(1))  4 * 3 * (2 * (1* factorial(0))) 
  • 768.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Computing Factorial (7 of 11) factorial(0) 1;  factorial(n) n*factorial(n 1);   factorial(4) 4 * factorial(3)  4 * 3 * factorial(2)  4 * 3 * (2 * factorial(1))  4 * 3 * (2 * (1* factorial(0)))  4 * 3 * (2 * (1*1))) 
  • 769.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Computing Factorial (8 of 11) factorial(0) 1;  factorial(n) n*factorial(n 1);   factorial(4) 4 * factorial(3)  4 * 3 * factorial(2)  4 * 3 * (2 * factorial(1))  4 * 3 * (2 * (1* factorial(0)))  4 * 3 * (2 * (1*1)))  4 * 3 * (2 *1) 
  • 770.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Computing Factorial (9 of 11) factorial(0) 1;  factorial(n) n*factorial(n 1);   factorial(4) 4 * factorial(3)  4 * 3 * factorial(2)  4 * 3 * (2 * factorial(1))  4 * 3 * (2 * (1* factorial(0)))  4 * 3 * (2 * (1*1)))  4 * 3 * (2 *1)  4 * 3 * 2 
  • 771.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Computing Factorial (10 of 11) factorial(0) 1;  factorial(n) n*factorial(n 1);   factorial(4) 4 * factorial(3)  4 * (3 * factorial(2))  4 * (3 * (2 * factorial(1)))  4 * (3 * (2 * (1* factorial(0))))  4 * (3 * (2 * (1*1))))  4 * (3 * (2 *1))  4 * (3 * 2)  4 * (6) 
  • 772.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Computing Factorial (11 of 11) factorial(0) 1;  factorial(n) n*factorial(n 1);   factorial(4) 4 * factorial(3)  4 * (3 * factorial(2))  4 * (3 * (2 * factorial(1)))  4 * (3 * (2 * (1* factorial(0))))  4 * (3 * (2 * (1*1))))  4 * (3 * (2 *1))  4 * (3 * 2)  4 * (6)  24 
  • 773.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Recursive Factorial (1 of 11)
  • 774.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Recursive Factorial (2 of 11)
  • 775.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Recursive Factorial (3 of 11)
  • 776.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Recursive Factorial (4 of 11)
  • 777.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Recursive Factorial (5 of 11)
  • 778.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Recursive Factorial (6 of 11)
  • 779.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Recursive Factorial (7 of 11)
  • 780.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Recursive Factorial (8 of 11)
  • 781.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Recursive Factorial (9 of 11)
  • 782.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Recursive Factorial (10 of 11)
  • 783.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Recursive Factorial (11 of 11)
  • 784.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved factorial(4) Stack Trace Space Required for factorial(4) 1 Space Required for factorial(4) 2 Space Required for factorial(3) Space Required for factorial(4) 3 Space Required for factorial(3) Space Required for factorial(2) Space Required for factorial(4) 4 Space Required for factorial(3) Space Required for factorial(2) Space Required for factorial(1) Space Required for factorial(4) 5 Space Required for factorial(3) Space Required for factorial(2) Space Required for factorial(1) Space Required for factorial(0) Space Required for factorial(4) 6 Space Required for factorial(3) Space Required for factorial(2) Space Required for factorial(1) Space Required for factorial(4) 7 Space Required for factorial(3) Space Required for factorial(2) Space Required for factorial(4) 8 Space Required for factorial(3) Space Required for factorial(4) 9
  • 785.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Other Examples  f(0) 0;    f n n ( f(n ) 1);
  • 786.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Fibonacci Numbers (1 of 2) Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89… indices: 0 1 2 3 4 5 6 7 8 9 10 11  ( ) fib 0 0;  fib 1 ( ) 1; fib(index) fib(index 1) fib(index 2); index 2                   fib(3) fib 2 fib 1 fib(1) fib 0 fib 1 1 0 fib 1 1 ( ) ( ) ( ( )) ( ) ( ) ( ) ( fib 1 1 1 ) 2 ComputeFibonacci
  • 787.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Fibonacci Numbers (2 of 2) return fib(3) + fib(2) return fib(2) + fib(1) return fib(1) + fib(0) return 1 return fib(1) + fib(0) return 0 return 1 return 1 return 0 1: call fib(3) 2: call fib(2) 3: call fib(1) 4: return fib(1) 7: return fib(2) 5: call fib(0) 6: return fib(0) 8: call fib(1) 9: return fib(1) 10: return fib(3) 11: call fib(2) 16: return fib(2) 12: call fib(1) 13: return fib(1) 14: return fib(0) 15: return fib(0) fib(4) 0: call fib(4) 17: return fib(4)
  • 788.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem Solving Using Recursion (1 of 2) In general, to solve a problem using recursion, you break it into subproblems. If a subproblem resembles the original problem, you can apply the same approach to solve the subproblems recursively. A subproblem is almost the same as the original problem in nature with a smaller size.
  • 789.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Characteristics of Recursion • All recursive methods have the following characteristics: – The method is implemented using a conditional statement that leads to different cases. – One or more base cases (the simplest case) are used to stop recursion. – Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case.
  • 790.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Problem Solving Using Recursion (2 of 2) nPrintln(“Welcome”, n); 1. one is to print the message one time and the other is to print the message for n-1 times. 2. The second problem is the same as the original problem with a smaller size. 3. The base case for the problem is n==0. You can solve this problem using recursion as follows: public static void nPrintln(String message, int n) { if (n >= 1) { System.out.println(message); nPrintln(message, n - 1); } // The base case is n < 1 }
  • 791.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Think Recursively Many of the problems presented in the early chapters can be solved using recursion if you think recursively. For example, the palindrome problem can be solved recursively as follows: public static boolean isPalindrome(String s) { if (s.length() <= 1) // Base case return true; else if (s.charAt(0) != s.charAt(s.length() - 1)) // Base case return false; else return isPalindrome(s.substring(1, s.length() - 1)); } RecursivePalindromeUsingSubstring
  • 792.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Recursive Helper Methods (1 of 2) Sometimes you can find a solution by defining a recursive method to a problem similar to the original problem. This new method is called a recursive helper method. The original method can be solved by invoking the recursive helper method.
  • 793.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Recursive Helper Methods (2 of 2) The preceding recursive isPalindrome method is not efficient, because it creates a new string for every recursive call. To avoid creating new strings, use a helper method: public static boolean isPalindrome(String s) { return isPalindrome(s, 0, s.length() - 1); } public static boolean isPalindrome(String s, int low, int high) { if (high <= low) // Base case return true; else if (s.charAt(low) != s.charAt(high)) // Base case return false; else return isPalindrome(s, low + 1, high - 1); } RecursivePalindrome
  • 794.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Recursive Selection Sort 1. Find the smallest number in the list and swaps it with the first number. 2. Ignore the first number and sort the remaining smaller list recursively. RecursiveSelectionSort
  • 795.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Recursive Binary Search 1. Case 1: If the key is less than the middle element, recursively search the key in the first half of the array. 2. Case 2: If the key is equal to the middle element, the search ends with a match. 3. Case 3: If the key is greater than the middle element, recursively search the key in the second half of the array. RecursiveBinarySearch
  • 796.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Recursive Implementation /** Use binary search to find the key in the list */ public static int recursiveBinarySearch(int[] list, int key) { int low = 0; int high = list.length - 1; return recursiveBinarySearch(list, key, low, high); } /** Use binary search to find the key in the list between list[low] list[high] */ public static int recursiveBinarySearch(int[] list, int key, int low, int high) { if (low > high) // The list has been exhausted without a match return -low - 1; int mid = (low + high) / 2; if (key < list[mid]) return recursiveBinarySearch(list, key, low, mid - 1); else if (key == list[mid]) return mid; else return recursiveBinarySearch(list, key, mid + 1, high); }
  • 797.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Directory Size (1 of 2) The preceding examples can easily be solved without using recursion. This section presents a problem that is difficult to solve without using recursion. The problem is to find the size of a directory. The size of a directory is the sum of the sizes of all files in the directory. A directory may contain subdirectories. Suppose a directory contains files , , …, , and subdirectories , , …, , as shown below. directory ... 1 f 1 2 f 1 m f 1 1 d 1 2 d 1 n d 1 ...
  • 798.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Directory Size (2 of 2) The size of the directory can be defined recursively as follows: 1 2 1 2 ( ) ( ) ( ) ... ( ) ( ) ( ) ... ( ) m n size d size f size f size f size d size d size d         DirectorySize
  • 799.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Tower of Hanoi (1 of 2) • There are n disks labeled 1, 2, 3, …, n, and three towers labeled A, B, and C. • No disk can be on top of a smaller disk at any time. • All the disks are initially placed on tower A. • Only one disk can be moved at a time, and it must be the top disk on the tower.
  • 800.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Tower of Hanoi Animation https://liveexample.pearsoncmg.com/dsanimation/TowerOf Hanoi.html
  • 801.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Tower of Hanoi (2 of 2)
  • 802.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Solution to Tower of Hanoi (1 of 2) The Tower of Hanoi problem can be decomposed into three subproblems.
  • 803.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Solution to Tower of Hanoi (2 of 2) • Move the first  n 1 disks from A to C with the assistance of tower B. • Move disk n from A to B. • Move  n 1 disks from C to B with the assistance of tower A. TowerOfHanoi
  • 804.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Exercise 18.3 GCD gcd(2, 3) = 1 gcd(2, 10) = 2 gcd(25, 35) = 5 gcd(205, 301) = 5 gcd(m, n) Approach 1: Brute-force, start from min(n, m) down to 1, to check if a number is common divisor for both m and n, if so, it is the greatest common divisor. Approach 2: Euclid’s algorithm Approach 3: Recursive method
  • 805.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Approach 2: Euclid’s Algorithm // Get absolute value of m and n; t1 = Math.abs(m); t2 = Math.abs(n); // r is the remainder of t1 divided by t2; r = t1 % t2; while (r != 0) { t1 = t2; t2 = r; r = t1 % t2; } // When r is 0, t2 is the greatest common // divisor between t1 and t2 return t2;
  • 806.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Approach 3: Recursive Method gcd(m, n) = n if m % n = 0; gcd(m, n) = gcd(n, m % n); otherwise;
  • 807.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Fractals A fractal is a geometrical figure just like triangles, circles, and rectangles, but fractals can be divided into parts, each of which is a reduced-size copy of the whole. There are many interesting examples of fractals. This section introduces a simple fractal, called Sierpinski triangle, named after a famous Polish mathematician.
  • 808.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Sierpinski Triangle 1. It begins with an equilateral triangle, which is considered to be the Sierpinski fractal of order (or level) 0, as shown in Figure (a). 2. Connect the midpoints of the sides of the triangle of order 0 to create a Sierpinski triangle of order 1, as shown in Figure (b). 3. Leave the center triangle intact. Connect the midpoints of the sides of the three other triangles to create a Sierpinski of order 2, as shown in Figure (c). 4. You can repeat the same process recursively to create a Sierpinski triangle of order 3, 4, …, and so on, as shown in Figure (d).
  • 809.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Sierpinski Triangle Solution SierpinskiTriangle
  • 810.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Recursion versus Iteration Recursion is an alternative form of program control. It is essentially repetition without a loop. Recursion bears substantial overhead. Each time the program calls a method, the system must assign space for all of the method’s local variables and parameters. This can consume considerable memory and requires extra time to manage the additional space.
  • 811.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Advantages of Using Recursion Recursion is good for solving the problems that are inherently recursive.
  • 812.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Tail Recursion A recursive method is said to be tail recursive if there are no pending operations to be performed on return from a recursive call. Non-tail recursive Tail recursive ComputeFactorial ComputeFactorialTailRecursion
  • 813.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.
  • 814.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introduction to Java Programming and Data Structures Thirteenth Edition Chapter 20 Lists, Stacks, Queues, and Priority Queues Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 815.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (1 of 2) 20.1 To explore the relationship between interfaces and classes in the Java Collections Framework hierarchy (§20.2). 20.2 To use the common methods defined in the Collection interface for operating collections (§20.2). 20.3 To use the Iterator interface to traverse the elements in a collection (§20.3). 20.4 To use a foreach loop to traverse the elements in a collection (§20.3). 20.5 To use a forEach method to perform an action on each element in a collection (§20.4). 20.6 To explore how and when to use ArrayList or LinkedList to store a list of elements (§20.5). 20.7 To compare elements using the Comparable interface and the Comparator interface (§20.6).
  • 816.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives (2 of 2) 20.8 To use the static utility methods in the Collections class for sorting, searching, shuffling lists, and finding the largest and smallest element in collections (§20.7). 20.9 To develop a multiple bouncing balls application using ArrayList (§20.8). 20.10 To distinguish between Vector and ArrayList and to use the Stack class for creating stacks (§20.9). 20.11 To explore the relationships among Collection, Queue, LinkedList, and PriorityQueue and to create priority queues using the PriorityQueue class (§20.10). 20.12 To use stacks to write a program to evaluate expressions (§20.11).
  • 817.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved What Is Data Structure? A data structure is a collection of data organized in some fashion. The structure not only stores data, but also supports operations for accessing and manipulating the data.
  • 818.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Java Collection Framework hierarchy (1 of 2) A collection is a container object that holds a group of objects, often referred to as elements. The Java Collections Framework supports two types of collections: • One, for storing a collection , is simply called collection. • The other, for storing key/value pairs, is called a map.
  • 819.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Java Collection Framework hierarchy (2 of 2) Set and List are subinterfaces of Collection.
  • 820.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Collection Interface UML Diagram TestCollection
  • 821.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Iterators Iterator is a classic design pattern for walking through a data structure without having to expose the details of how data is stored in the data structure. TestIterator
  • 822.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Using the forEach Method Java 8 added a new forEach method in the Iterable interface. It functions like a foreach loop. TestForEach
  • 823.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The List Interface (1 of 2) A list stores elements in a sequential order, and allows the user to specify where the element is stored. The user can access the elements by index.
  • 824.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The List Interface (2 of 2)
  • 825.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The List Iterator
  • 826.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved ArrayList and LinkedList The ArrayList class and the LinkedList class are concrete implementations of the List interface. Which of the two classes you use depends on your specific needs. If you need to support random access through an index without inserting or removing elements from any place other than the end, ArrayList offers the most efficient collection. If, however, your application requires the insertion or deletion of elements from the beginning of the list, you should choose LinkedList. A list can grow or shrink dynamically. An array is fixed once it is created. If your application does not require insertion or deletion of elements, the most efficient data structure is the array.
  • 827.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved java.util.ArrayList «interface» java.util.List<E> Creates an empty list with the default initial capacity. Creates an array list from an existing collection. Creates an empty list with the specified initial capacity. Trims the capacity of this ArrayList instance to be the list's current size. +ArrayList() +ArrayList(c:Collection<?extendsE>) +ArrayList(initialCapacity: int) +trimToSize(): void «interface» java.util.Collection<E> java.util.ArrayList<E>
  • 828.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved java.util.LinkedList «interface» java.util.List<E> Creates a default empty linked list. Creates a linked list from an existing collection. Adds the object to the head of this list. Adds the object to the tail of this list. Returns the first element from this list. Returns the last element from this list. Returns and removes the first element from this list. Returns and removes the last element from this list. +LinkedList() +LinkedList(c: Collection<? extends E>) +addFirst(o: E): void +addLast(o: E): void +getFirst(): E +getLast(): E +removeFirst(): E +removeLast(): E «interface» java.util.Collection<E> java.util.LinkedList<E>
  • 829.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example: Using ArrayList and LinkedList This example creates an array list filled with numbers, and inserts new elements into the specified location in the list. The example also creates a linked list from the array list, inserts and removes the elements from the list. Finally, the example traverses the list forward and backward. TestArrayAndLinkedList
  • 830.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Comparator Interface You have learned to compare objects using the Comparable interface. What happens if the objects are not instances of Comparable. You can define a comparator to compare these elements. The Comparator interface has the compare method for comparing two objects.
  • 831.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Comparator<T> Interface public int compare(T element1, T element2) Returns a negative value if element1 is less than element2, a positive value if element1 is greater than element2, and zero if they are equal. GeometricObjectComparator TestCollection
  • 832.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Using Lambda Expression in Comparator Comparator is a functional interface. It has just a single method, compare. We can use lambda expression to simplify coding.
  • 833.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Other Comparator Examples SortStringByLength SortStringIgnoreCase
  • 834.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Method Reference String::compareToIgnoreCase is known as method reference, which is equivalent to the lambda expression: (s1, s2) -> s1.compareToIgnoreCase(s2) The compiler automatically translates a method reference to an equivalent lambda expression.
  • 835.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The comparing Method You can use the static comparing method in the Comparator interface to create a comparator. For example, the following code sorts a list of loans based on their loan amount property. Loan[] list = {new Loan(5.5, 10, 2323), new Loan(5, 10, 1000)}; Arrays.sort(list, Comparator.comparing(Loan::getLoanAmount));
  • 836.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Add Additional Sort Criteria You can sort using a primary criteria, second, third, and so on using the Comparator’s default thenComparing method. Loan[] list = {new Loan(5.5, 10, 100), new Loan(5, 10, 1000)}; Arrays.sort(list, Comparator.comparing(Loan::getLoanAmount) .thenComparing(Loan::getAnnualInterestRate));
  • 837.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Collections Class The Collections class contains various static methods for performing common operations in a collection and a list.
  • 838.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Collections Class UML Diagram
  • 839.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Case Study: Multiple Bouncing Balls MultipleBounceBall javafx.application.Application -char token +getToken +setToken +paintComponet +mouseClicked MultipleBallPane -animation: Timeline +MultipleBallPane() +play(): void +pause(): void +increaseSpeed(): void +decreaseSpeed(): void +rateProperty(): DoubleProperty +moveBall(): void javafx.scene.layout.Pane 1 1 Ball dx: double dy: double +Ball(x: double, y: double, radius: double, color: Color) javafx.scene.shape.Circle 1 m MultipleBounceBall
  • 840.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Vector and Stack Classes The Java Collections Framework was introduced with Java 2. Several data structures were supported prior to Java 2. Among them are the Vector class and the Stack class. These classes were redesigned to fit into the Java Collections Framework, but their old-style methods are retained for compatibility. This section introduces the Vector class and the Stack class.
  • 841.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Vector Class (1 of 2) The Vector class is replaced by the ArrayList. Vector contains the synchronized methods for accessing and modifying the vector. It is not efficient for most of the applications. You may encounter Vector in the legacy Java code.
  • 842.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Vector Class (2 of 2)
  • 843.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Stack Class The Stack class represents a last-in-first-out stack of objects. The elements are accessed only from the top of the stack. You can retrieve, insert, or remove an element from the top of the stack. java.util.Stack<E> +Stack() +empty(): boolean +peek(): E +pop(): E +push(o: E) : E +search(o: Object) : int java.util.Vector<E> Creates an empty stack. Returns true if this stack is empty. Returns the top element in this stack. Returns and removes the top element in this stack. Adds a new element to the top of this stack. Returns the position of the specified element in this stack.
  • 844.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Queues and Priority Queues A queue is a first-in/first-out data structure. Elements are appended to the end of the queue and are removed from the beginning of the queue. In a priority queue, elements are assigned priorities. When accessing elements, the element with the highest priority is removed first.
  • 845.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Queue Interface
  • 846.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Using LinkedList for Queue
  • 847.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The PriorityQueue Class PriorityQueueDemo
  • 848.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Case Study: Evaluating Expressions Stacks can be used to evaluate expressions. Evaluate Expression
  • 849.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Algorithm Phase 1: Scanning the expression The program scans the expression from left to right to extract operands, operators, and the parentheses. 1.1. If the extracted item is an operand, push it to operandStack. 1.2. If the extracted item is a + or - operator, process all the operators at the top of operatorStack and push the extracted operator to operatorStack. 1.3. If the extracted item is a * or / operator, process the * or / operators at the top of operatorStack and push the extracted operator to operatorStack. 1.4. If the extracted item is a ( symbol, push it to operatorStack. 1.5. If the extracted item is a ) symbol, repeatedly process the operators from the top of operatorStack until seeing the ( symbol on the stack. Phase 2: Clearing the stack Repeatedly process the operators from the top of operatorStack until operatorStack is empty.
  • 850.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example
  • 851.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.
  • 852.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introduction to Java Programming and Data Structures Thirteenth Edition Chapter 23 Sorting Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 853.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives 23.1 To study and analyze time complexity of various sorting algorithms (§§23.2–23.7). 23.2 To design, implement, and analyze insertion sort (§23.2). 23.3 To design, implement, and analyze bubble sort (§23.3). 23.4 To design, implement, and analyze merge sort (§23.4). 23.5 To design, implement, and analyze quick sort (§23.5). 23.6 To design and implement a binary heap (§23.6). 23.7 To design, implement, and analyze heap sort (§23.7). 23.8 To design, implement, and analyze bucket sort and radix sort (§23.8). 23.9 To design, implement, and analyze external sort for files that have a large amount of data (§23.9).
  • 854.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Why Study Sorting? • Sorting is a classic subject in computer science. There are three reasons for studying sorting algorithms. – First, sorting algorithms illustrate many creative approaches to problem solving and these approaches can be applied to solve other problems. – Second, sorting algorithms are good for practicing fundamental programming techniques using selection statements, loops, methods, and arrays. – Third, sorting algorithms are excellent examples to demonstrate algorithm performance.
  • 855.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved What Data to Sort? The data to be sorted might be integers, doubles, characters, or objects. §7.8, “Sorting Arrays,” presented selection sort and insertion sort for numeric values. The selection sort algorithm was extended to sort an array of objects in §11.5.7, “Example: Sorting an Array of Objects.” The Java API contains several overloaded sort methods for sorting primitive type values and objects in the java.util.Arrays and java.util.Collections class. For simplicity, this section assumes: • data to be sorted are integers, • data are sorted in ascending order, and • data are stored in an array. The programs can be easily modified to sort other types of data, to sort in descending order, or to sort data in an ArrayList or a LinkedList.
  • 856.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Insertion Sort (1 of 2) The insertion sort algorithm sorts a list of values by repeatedly inserting an unsorted element into a sorted sublist until the whole list is sorted. int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted 2 9 5 4 8 1 6 Step 1: Initially, the sorted sublist contains the first element in the list. Insert 9 into the sublist. 2 9 5 4 8 1 6 Step2: The sorted sublist is {2, 9}. Insert 5 into the sublist. 2 5 9 4 8 1 6 Step 3: The sorted sublist is {2, 5, 9}. Insert 4 into the sublist. 2 4 5 9 8 1 6 Step 4: The sorted sublist is {2, 4, 5, 9}. Insert 8 into the sublist. 2 4 5 8 9 1 6 Step 5: The sorted sublist is {2, 4, 5, 8, 9}. Insert 1 into the sublist. 1 2 4 5 8 9 6 Step 6: The sorted sublist is {1, 2, 4, 5, 8, 9}. Insert 6 into the sublist. 1 2 4 5 6 8 9 Step 7: The entire list is now sorted.
  • 857.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Insertion Sort Animation https://liveexample.pearsoncmg.com/dsanimation/Insertion SortNeweBook.html
  • 858.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Insertion Sort (2 of 2) int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted
  • 859.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved How to Insert? The insertion sort algorithm sorts a list of values by repeatedly inserting an unsorted element into a sorted sublist until the whole list is sorted. [0] [1] [2] [3] [4] [5] [6] 2 5 9 4 list Step 1: Save 4 to a temporary variable currentElement [0] [1] [2] [3] [4] [5] [6] 2 5 9 list Step 2: Move list[2] to list[3] [0] [1] [2] [3] [4] [5] [6] 2 5 9 list Step 3: Move list[1] to list[2] [0] [1] [2] [3] [4] [5] [6] 2 4 5 9 list Step 4: Assign currentElement to list[1]
  • 860.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved From Idea to Solution (1 of 2) for (int i = 1; i < list.length; i++) { insert list[i] into a sorted sublist list[0..i-1] so that list[0..i] is sorted } list[0] list[0] list[1] list[0] list[1] list[2] list[0] list[1] list[2] list[3] list[0] list[1] list[2] list[3] …
  • 861.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved From Idea to Solution (2 of 2) InsertionSort
  • 862.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Bubble Sort 2 5 9 4 8 1 2 5 4 9 8 1 2 5 4 8 9 1 2 5 4 8 1 9 (a) 1st pass 2 4 5 8 1 9 2 4 5 8 1 9 2 4 5 1 8 9 (b) 2nd pass 2 4 5 1 8 9 2 4 1 5 8 9 (c) 3rd pass 2 1 4 5 8 9 (d) 4th pass 2 9 5 4 8 1 (e) 5th pass 2 5 4 8 1 9 2 4 5 1 8 9 2 4 1 5 8 9 1 2 4 5 8 9 Bubble sort time:   2 O n     2 1 2 2 1 2 2 n n n n         BubbleSort
  • 863.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Bubble Sort Animation https://liveexample.pearsoncmg.com/dsanimation/BubbleS ortNeweBook.html
  • 864.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Merge Sort (1 of 2) 2 9 5 4 8 1 6 7 2 9 5 4 8 1 6 7 split 2 9 split 5 4 2 split 9 5 4 8 1 6 7 8 1 6 7 2 9 merge 4 5 1 8 6 7 2 4 5 9 1 6 7 8 1 2 4 5 6 7 8 9 merge merge divide conquer MergeSort
  • 865.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Merge Sort (2 of 2) mergeSort(list): firstHalf = mergeSort(firstHalf); secondHalf = mergeSort(secondHalf); list = merge(firstHalf, secondHalf);
  • 866.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Merge Two Sorted Lists 2 4 5 9 current1 1 1 6 7 8 current2 current3 (a) After moving 1 to temp (b) After moving all the elements in list2 to temp to temp 2 4 5 9 current1 1 2 4 5 6 7 8 9 1 6 7 8 current2 current3 (c) After moving 9 to temp 2 4 5 9 current1 1 2 4 5 6 7 8 1 6 7 8 current2 current3 Animation for Merging Two Sorted Lists
  • 867.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Merge Sort Time (1 of 2) Let ) ( T n denote the time required for sorting an array of n elements using merge sort. Without loss of generality, assume n is a power of 2. The merge sort algorithm splits the array into two subarrays, sorts the subarrays using the same algorithm recursively, and then merges the subarrays. So,   2 2 n n T n T T mergetime                  ( ) 2 2 n n T n T T O n               
  • 868.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Merge Sort Time (2 of 2) The first 2 ( ) / T n is the time for sorting the first half of the array and the second 2 ( ) / T n is the time for sorting the second half. To merge two subarrays, it takes at most 1 n  comparisons to compare the elements from the two subarrays and n moves to move elements to the temporary array. So, the total time is 2 1. n  Therefore,   2 2 1 log log 1 log log ( ) 2 2 1 2 2 2 1 2 1 2 2 2 2 1 2 4 2 2 2 2 2 ... 2 2 2 1 2 2 2 2 ... 2 2 2 1 2 2 log 2 1 2 log 1 log k k k n n n n n n n n T n T n T n T n n n T n n n n T n n n n n n n n O n n                                                                          
  • 869.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Quick Sort (1 of 2) Quick sort, developed by C. A. R. Hoare (1962), works as follows: The algorithm selects an element, called the pivot, in the array. Divide the array into two parts such that all the elements in the first part are less than or equal to the pivot and all the elements in the second part are greater than the pivot. Recursively apply the quick sort algorithm to the first part and then the second part.
  • 870.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Quick Sort (2 of 2) 5 2 9 3 8 4 0 1 6 7 pivot (a) The original array 4 2 1 3 0 5 8 9 6 7 pivot (b)The original array is partitioned 0 2 1 3 4 (c) The partial array (4 2 1 3 0) is partitioned 0 2 1 3 (d) The partial array (0 2 1 3) is partitioned 1 2 3 pivot pivot pivot (e) The partial array (2 1 3) is partitioned
  • 871.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Partition 5 2 9 3 8 4 0 1 6 7 pivot low high (a) Initialize pivot, low, and high 5 2 9 3 8 4 0 1 6 7 pivot low high (b) Search forward and backward 5 2 1 3 8 4 0 9 6 7 pivot low high (c) 9 is swapped with 1 5 2 1 3 8 4 0 9 6 7 pivot low high (d) Continue search 5 2 1 3 0 4 8 9 6 7 pivot low high (e) 8 is swapped with 0 5 2 1 3 0 4 8 9 6 7 pivot low high (f) when high < low, search is over 4 2 1 3 0 5 8 9 6 7 pivot (g) pivot is in the right place The index of the pivot is returned Animation for partition QuickSort
  • 872.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Quick Sort Time To partition an array of n elements, it takes 1 n  comparisons and n moves in the worst case. So, the time required for partition is ( ). O n
  • 873.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Worst-Case Time In the worst case, each time the pivot divides the array into one big subarray with the other empty. The size of the big subarray is one less than the one before divided. The algorithm requires 2 ( ) O n time:       2 1 2 2 1 n n O n       
  • 874.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Best-Case Time In the best case, each time the pivot divides the array into two parts of about the same size. Let   T n denote the time required for sorting an array of elements using quick sort. So,                     log 2 2 n n T n T T n O n n
  • 875.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Average-Case Time On the average, each time the pivot will not divide the array into two parts of the same size nor one empty part. Statistically, the sizes of the two parts are very close. So the average time is   log . O n n The exact average-case analysis is beyond the scope of this book.
  • 876.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Heap Heap is a useful data structure for designing efficient sorting algorithms and priority queues. A heap is a binary tree with the following properties: • It is a complete binary tree. • Each node is greater than or equal to any of its children.
  • 877.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Complete Binary Tree A binary tree is complete if every level of the tree is full except that the last level may not be full and all the leaves on the last level are placed left-most. For example, in the following figure, the binary trees in (a) and (b) are complete, but the binary trees in (c) and (d) are not complete. Further, the binary tree in (a) is a heap, but the binary tree in (b) is not a heap, because the root (39) is less than its right child (42). 22 29 14 33 32 39 42 22 29 14 32 42 39 22 14 33 32 39 42 22 29 32 42
  • 878.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved See How a Heap Works https://liveexample.pearsoncmg.com/dsanimation/HeapeBo ok.html
  • 879.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Representing a Heap For a node at position i, its left child is at position 2i+1 and its right child is at position 2i+2, and its parent is at index   1 / 2. i  For example, the node for element 39 is at position 4, so its left child (element 14) is at 9 (2*4+1), its right child (element 33) is at 10 (2*4+2), and its parent (element 42) is at 1     4 1 / 2 .  22 29 14 33 30 17 9 32 39 44 13 42 59 62 62 42 59 32 39 44 13 22 29 14 33 30 17 9 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10][11][12][13] [10][11] parent left right
  • 880.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Adding Elements to the Heap Adding 3, 5, 1, 19, 11, and 22 to a heap, initially empty 3 (a) After adding 3 (b) After adding 5 (c) After adding 1 (d) After adding 19 3 19 5 1 (e) After adding 11 3 5 19 11 1 (f) After adding 22 3 5 1 22 11 19 5 3 5 3 1
  • 881.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Rebuild the Heap After Adding a New Node Adding 88 to the heap (a) Add 88 to a heap 3 5 1 88 22 11 19 (b) After swapping 88 with 19 3 5 1 19 22 11 88 (b) After swapping 88 with 22 3 5 1 19 88 11 22
  • 882.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Removing the Root and Rebuild the Tree (1 of 5) Removing root 62 from the heap 22 29 14 33 30 17 9 32 39 44 13 42 59 62
  • 883.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Removing the Root and Rebuild the Tree (2 of 5) Move 9 to root 22 29 14 33 30 17 32 39 44 13 42 59 9
  • 884.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Removing the Root and Rebuild the Tree (3 of 5) Swap 9 with 59 22 29 14 33 30 17 32 39 44 13 42 9 59
  • 885.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Removing the Root and Rebuild the Tree (4 of 5) Swap 9 with 44 22 29 14 33 30 17 32 39 9 13 42 44 59
  • 886.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Removing the Root and Rebuild the Tree (5 of 5) Swap 9 with 30 22 29 14 33 9 17 32 39 30 13 42 44 59
  • 887.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Heap Class Heap
  • 888.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Heap Sort HeapSort
  • 889.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Heap Sort Time Let h denote the height for a heap of n elements. Since a heap is a complete binary tree, the first level has 1 node, the second level has 2 nodes, the kth level has   1 2 k  nodes, the    h 1 t h level has   2 2 h nodes, and the hth level has at least one node and at most   1 2 h nodes. Therefore, 2 2 1 1 2 2 1 2 ... 2 2 h h h n             1 2 1 2 1 h h n      1 2 1 2 h h n       1 log2 log 1 log2 h h n       1 log 1 h n h         log 1 log 1 1 n h n     
  • 890.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Bucket Sort and Radix Sort All sort algorithms discussed so far are general sorting algorithms that work for any types of keys (e.g., integers, strings, and any comparable objects). These algorithms sort the elements by comparing their keys. The lower bound for general sorting algorithms is   log . O n n So, no sorting algorithms based on comparisons can perform better than   log . O n n However, if the keys are small integers, you can use bucket sort without having to compare the keys.
  • 891.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Bucket Sort The bucket sort algorithm works as follows. Assume the keys are in the range from 0 to N 1.  We need N buckets labeled 0, 1, , and N 1 .  If an element’s key is i, the element is put into the bucket i. Each bucket holds the elements with the same key value. You can use an ArrayList to implement a bucket.
  • 892.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Radix Sort Sort 331, 454, 230, 34, 343, 45, 59, 453, 345, 231, 9 230, 331, 231, 343, 453, 454, 34, 45, 345, 59, 9 9, 230, 331, 231, 34, 343, 45, 345, 453, 454, 59 9, 34, 45, 59, 230, 231, 331, 343, 345, 453, 454
  • 893.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Radix Sort Animation https://liveexample.pearsoncmg.com/dsanimation/RadixSorteBook.html
  • 894.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved External Sort All the sort algorithms discussed in the preceding sections assume that all data to be sorted is available at one time in internal memory such as an array. To sort data stored in an external file, you may first bring data to the memory, then sort it internally. However, if the file is too large, all data in the file cannot be brought to memory at one time. Program Array …… Original file Temporary file S1 S2 Sk CreateLargeFile SortLargeFile
  • 895.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Phase One I Repeatedly bring data from the file to an array, sort the array using an internal sorting algorithm, and output the data from the array to a temporary file. Program Array …… Original file Temporary file S1 S2 Sk
  • 896.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Phase Two II Merge a pair of sorted segments (e.g., S1 with S2, S3 with S4, , and so on) into a larger sorted segment and save the new segment into a new temporary file. Continue the same process until one sorted segment results. S1 S2 S3 S4 S5 S6 S7 S8 Sk S1, S2 merged S3, S4 merged S5, S6 merged S7, S8 merged S1, S2, S3, S4 merged S5, S6 , S7, S8 merged S1, S2, S3, S4 , S5, S6 , S7, S8 merged Merge Merge Merge
  • 897.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Implementing Phase Two (1 of 2) II Each merge step merges two sorted segments to form a new segment. The new segment doubles the number elements. So the number of segments is reduced by half after each merge step. A segment is too large to be brought to an array in memory. To implement a merge step, copy half number of segments from file f1.dat to a temporary file f2.dat. Then merge the first remaining segment in f1.dat with the first segment in f2.dat into a temporary file named f3.dat.
  • 898.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Implementing Phase Two (2 of 2) II S1 S2 S3 S4 S5 S6 S7 S8 Sk S1, S5 merged S2, S6 merged S3, S7 merged S4, S8 merged f1.dat S1 S2 S3 S4 f2.dat Copy to f2.dat f3.dat
  • 899.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.
  • 900.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introduction to Java Programming and Data Structures Thirteenth Edition Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 901.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives 24.1 To design common operations of lists in an interface and make the interface a subtype of Collection (§24.2). 24.2 To design and implement an array list using an array (§24.3). 24.3 To create a linked list using a linked structure (§24.4). 24.4 To design MyLinkedList class (§24.5). 24.5 To implement MyLinkedList class (§24.6). 24.6 To compare the performance between MyArrayList and MyLinkedList (§24.7). 24.7 To explore variations of linked lists (§24.8). 24.8 To design and implement a stack class using an array list and a queue class using a linked list (§24.9). 24.9 To design and implement a priority queue using a heap (§24.10).
  • 902.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Lists A list is a popular data structure to store data in sequential order. For example, a list of students, a list of available rooms, a list of cities, and a list of books, etc. can be stored using lists. The common operations on a list are usually the following: • Retrieve an element from this list. • Insert a new element to this list. • Delete an element from this list. • Find how many elements are in this list. • Find if an element is in this list. • Find if this list is empty.
  • 903.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Two Ways to Implement Lists There are two ways to implement a list. Using arrays. One is to use an array to store the elements. The array is dynamically created. If the capacity of the array is exceeded, create a new larger array and copy all the elements from the current array to the new array. Using linked list. The other approach is to use a linked structure. A linked structure consists of nodes. Each node is dynamically created to hold an element. All the nodes are linked together to form a list.
  • 904.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Design of ArrayList and LinkedList For convenience, let’s name these two classes: MyArrayList and MyLinkedList. These two classes have common operations, but different data fields. The common operations can be generalized in an interface or an abstract class. Prior to Java 8, a popular design strategy is to define common operations in an interface and provide an abstract class for partially implementing the interface. So, the concrete class can simply extend the abstract class without implementing the full interface. Java 8 enables you to define default methods. You can provide default implementation for some of the methods in the interface rather than in an abstract class. MyList MyArrayList MyLinkedList java.util.Collection java.util.Iterable
  • 905.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved MyList Interface «interface» MyList<E> +add(index: int, e: E) : void +get(index: int) : E +indexOf(e: Object) : int +lastIndexOf(e: E) : int +remove(index: int) : E +set(index: int, e: E) : E Override the add, isEmpty, remove, containsAll, addAll, removeAll, retainAll, toArray(), and toArray(T[]) methods defined in Collection using default methods. Inserts a new element at the specified index in this list. Returns the element from this list at the specified index. Returns the index of the first matching element in this list. Returns the index of the last matching element in this list. Removes the element at the specified index and returns the removed element. Sets the element at the specified index and returns the element being replaced. «interface» java.util.Collection<E> MyList
  • 906.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Array Lists Array is a fixed-size data structure. Once an array is created, its size cannot be changed. Nevertheless, you can still use array to implement dynamic data structures. The trick is to create a new larger array to replace the current array if the current array cannot hold new elements in the list. Initially, an array, say data of Object[] type, is created with a default size. When inserting a new element into the array, first ensure there is enough room in the array. If not, create a new array with the size as twice as the current one. Copy the elements from the current array to the new array. The new array now becomes the current array.
  • 907.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Array List Animation https://liveexample.pearsoncmg.com/dsanimation/ArrayList eBook.html
  • 908.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Insertion Before inserting a new element at a specified index, shift all the elements after the index to the right and increase the list size by 1. e0 0 1 … i i+1 k-1 Before inserting e at insertion point i e1 … ei ei+1 … … ek-1 data.length -1 Insertion point e e0 0 1 … i i+1 After inserting e at insertion point i, list size is incremented by 1 e1 … e ei … … ek-1 data.length -1 e inserted here ek ek k ei-1 ei-1 k+1 k ei+1 i+2 …shift… Add Method Animation
  • 909.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Deletion To remove an element at a specified index, shift all the elements after the index to the left by one position and decrease the list size by 1. e0 0 1 … i i+1 k-1 Before deleting the element at index i e1 … ei ei+1 … … ek-1 data.length -1 Delete this element e0 0 1 … i After deleting the element, list size is decremented by 1 e1 … … … ek data.length -1 ek k ei-1 ei-1 k-1 ei+1 k-2 ek-1 …shift… Remove Method Animation
  • 910.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Implementing MyArrayList MyArrayList<E> -data: E[] -size: int +MyArrayList() +MyArrayList(objects: E[]) +trimToSize(): void -ensureCapacity(): void -checkIndex(index: int): void «interface» MyList<E> Creates a default array list. Creates an array list from an array of objects. Trims the capacity of this array list to the list’s current size. Doubles the current array size if needed. Throws an exception if the index is out of bounds in the list. Array for storing elements in this array list. The number of elements in the array list. MyArrayList TestMyArrayList
  • 911.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Linked Lists Since MyArrayList is implemented using an array, the methods get(int index) and set(int index, Object o) for accessing and modifying an element through an index and the add(Object o) for adding an element at the end of the list are efficient. However, the methods add(int index, Object o) and remove(int index) are inefficient because it requires shifting potentially a large number of elements. You can use a linked structure to implement a list to improve efficiency for adding and removing an element anywhere in a list.
  • 912.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Linked List Animation https://liveexample.pearsoncmg.com/dsanimation/LinkedLi steBook.html
  • 913.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Nodes in Linked Lists A linked list consists of nodes. Each node contains an element, and each node is linked to its next neighbor. Thus a node can be defined as a class, as follows: element head next Node 1 element next Node 2 … element null Node n tail class Node<E> { E element; Node<E> next; public Node(E o) { element = o; } }
  • 914.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Adding Three Nodes (1 of 4) The variable head refers to the first node in the list, and the variable tail refers to the last node in the list. If the list is empty, both are null. For example, you can create three nodes to store three strings in a list, as follows: Step 1: Declare head and tail: The list is empty now Node<String> head = null; Node<String> tail = null;
  • 915.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Adding Three Nodes (2 of 4) Step 2: Create the first node and insert it to the list: head "Chicago" next: null tail After the first node is inserted inserted head = new Node<>("Chicago"); tail = head;
  • 916.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Adding Three Nodes (3 of 4) Step 3: Create the second node and insert it to the list: tail.next = new Node<>("Denver"); head "Chicago" next "Denver" next: null tail tail = tail.next; head "Chicago" next "Denver" next: null tail
  • 917.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Adding Three Nodes (4 of 4) Step 4: Create the third node and insert it to the list: head "Chicago" next "Dallas" next: null tail "Denver" next tail.next = new Node<>("Dallas"); head "Chicago" next "Dallas" next: null tail "Denver" next tail = tail.next;
  • 918.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Traversing All Elements in the List Each node contains the element and a data field named next that points to the next node. If the node is the last in the list, its pointer data field next contains the value null. You can use this property to detect the last node. For example, you may write the following loop to traverse all the nodes in the list. Node<E> current = head; while (current != null) { System.out.println(current.element); current = current.next; }
  • 919.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved MyLinkedList MyLinkedList<E> -head: Node<E> -tail: Node<E> -size: int +MyLinkedList() +MyLinkedList(elements: E[]) +addFirst(e: E): void +addLast(e: E): void +getFirst(): E +getLast(): E +removeFirst(): E +removeLast(): E 1 m Node<E> element: E next: Node<E> Link 1 «interface» MyList<E> Creates a default linked list. Creates a linked list from an array of elements. Adds an element to the head of the list. Adds an element to the tail of the list. Returns the first element in the list. Returns the last element in the list. Removes the first element from the list. Removes the last element from the list. The head of the list. The tail of the list. The number of elements in the list. MyLinkedList TestMyLinkedList
  • 920.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Implementing addFirst(E e) public void addFirst(E e) { Node<E> newNode = new Node<>(e); newNode.next = head; head = newNode; size++; if (tail == null) tail = head; } addFirst Animation head e0 next … A new node to be inserted here ei next ei+1 next tail … ek null e next New node inserted here (a) Before a new node is inserted. (b) After a new node is inserted. e0 next … ei next ei+1 next tail … ek null e next head
  • 921.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Implementing addLast(E e) public void addLast(E e) { if (tail == null) { head = tail = new Node<>(e); } else { tail.next = new Node<>(e); tail = tail.next; } size++; } addLast Animation head e0 next … ei next ei+1 next tail … ek null e null New node inserted here (a) Before a new node is inserted. (b) After a new node is inserted. head e0 next … ei next ei+1 next tail … ek next A new node to be inserted here e null
  • 922.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Implementing add(int index, E e) public void add(int index, E e) { if (index == 0) addFirst(e); else if (index >= size) addLast(e); else { Node<E> current = head; for (int i = 1; i < index; i++) current = current.next; Node<E> temp = current.next; current.next = new Node<>(e); (current.next).next = temp; size++; } } Add(index, e) Animation current head e0 next … A new node to be inserted here ei next temp ei+1 next tail … ek null e null (a) Before a new node is inserted. current head e0 next … A new node is inserted in the list ei next temp ei+1 next tail … ek null e next (b) After a new node is inserted.
  • 923.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Implementing removeFirst() public E removeFirst() { if (size == 0) return null; else { Node<E> temp = head; head = head.next; size--; if (head == null) tail = null; return temp.element; } } removeFirst Animation head e0 next … Delete this node ei next ei+1 next tail … ek null (a) Before the node is deleted. (b) After the first node is deleted e1 next … ei next ei+1 next tail … ek null e1 next head
  • 924.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Implementing removeLast() public E removeLast() { if (size == 0) return null; else if (size == 1) { Node<E> temp = head; head = tail = null; size = 0; return temp.element; } else { Node<E> current = head; for (int i = 0; i < size - 2; i++) current = current.next; Node temp = tail; tail = current; tail.next = null; size--; return temp.element; } } addLast Animation head e0 next … Delete this node ek-2 next ek-1 next tail ek null (a) Before the node is deleted. (b) After the last node is deleted e1 next current head e0 next … ek-2 next ek-1 null e1 next tail
  • 925.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Implementing remove(int index) public E remove(int index) { if (index < 0 || index >= size) return null; else if (index == 0) return removeFirst(); else if (index == size - 1) return removeLast(); else { Node<E> previous = head; for (int i = 1; i < index; i++) { previous = previous.next; } Node<E> current = previous.next; previous.next = current.next; size--; return current.element; } } remove Animation previous head element next … Node to be deleted element next element next tail … element null element next (a) Before the node is deleted. current previous head element next … element next element next tail … element null (b) After the node is deleted. current.next current.next
  • 926.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Time Complexity for ArrayList and LinkedList Methods MyArrayList/ArrayList MyLinkedList/LinkedList add(e: E) O of 1 O of 1 add(index: int, e: E) O of n O of n clear() O of 1 O of 1 contains(e: E) O of n O of n get(index: int) O of 1 O of n indexOf(e: E) O of n O of n isEmpty() O of 1 O of 1 lastIndexOf(e: E) O of n O of n remove(e: E) O of n O of n size() O of 1 O of 1 remove(index: int) O of n O of n set(index: int, e: E) O of n O of n addFirst(e: E) O of n O of 1 removeFirst() O of n O of 1   1 O   1 O   O n   O n   1 O   1 O   O n   O n   1 O   O n   O n   O n   1 O   1 O   O n   O n   O n   O n   1 O   1 O   O n   O n   O n   O n   O n   1 O   O n   1 O
  • 927.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Circular Linked Lists A circular, singly linked list is like a singly linked list, except that the pointer of the last node points back to the first node. element head next Node 1 element next Node 2 … element next Node n tail
  • 928.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Doubly Linked Lists A doubly linked list contains the nodes with two pointers. One points to the next node and the other points to the previous node. These two pointers are conveniently called a forward pointer and a backward pointer. So, a doubly linked list can be traversed forward and backward. element head next Node 1 element next Node 2 … element null Node n tail null previous previous
  • 929.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Circular Doubly Linked Lists A circular, doubly linked list is doubly linked list, except that the forward pointer of the last node points to the first node and the backward pointer of the first pointer points to the last node. element head next Node 1 element next Node 2 … element next Node n tail previous previous previous
  • 930.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Stacks A stack can be viewed as a special type of list, where the elements are accessed, inserted, and deleted only from the end, called the top, of the stack. Data1 Data2 Data1 Data1 Data2 Data3 Data1 Data2 Data3 Data1 Data2 Data3 Data1 Data2 Data1
  • 931.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Queues A queue represents a waiting list. A queue can be viewed as a special type of list, where the elements are inserted into the end (tail) of the queue, and are accessed and deleted from the beginning (head) of the queue. Data1 Data2 Data1 Data1 Data2 Data3 Data1 Data2 Data3 Data2 Data3 Data1 Data3 Data2 Data3
  • 932.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Stack Animation https://liveexample.pearsoncmg.com/dsanimation/StackeB ook.html
  • 933.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Queue Animation https://liveexample.pearsoncmg.com/dsanimation/Queuee Book.html
  • 934.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Implementing Stacks and Queues Using an array list to implement Stack Use a linked list to implement Queue Since the insertion and deletion operations on a stack are made only at the end of the stack, using an array list to implement a stack is more efficient than a linked list. Since deletions are made at the beginning of the list, it is more efficient to implement a queue using a linked list than an array list. This section implements a stack class using an array list and a queue using a linked list.
  • 935.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Design of the Stack and Queue Classes • There are two ways to design the stack and queue classes: – Using inheritance: You can define the stack class by extending the array list class, and the queue class by extending the linked list class. – Using composition: You can define an array list as a data field in the stack class, and a linked list as a data field in the queue class.
  • 936.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Composition is Better Both designs are fine, but using composition is better because it enables you to define a complete new stack class and queue class without inheriting the unnecessary and inappropriate methods from the array list and linked list.
  • 937.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved MyStack and MyQueue GenericStack<E> -list: java.util.ArrayList<E> +GenericStack() +getSize(): int +peek(): E +pop(): E +push(o: E): void +isEmpty(): boolean Creates an empty stack. Returns the number of elements in this stack. Returns the top element in this stack. Returns and removes the top element in this stack. Adds a new element to the top of this stack. Returns true if the stack is empty. An array list to store elements. GenericStack GenericQueue<E> -list: LinkedList<E> +enqueue(e: E): void +dequeue(): E +getSize(): int Adds an element to this queue. Removes an element from this queue. Returns the number of elements from this queue. GenericQueue
  • 938.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example: Using Stacks and Queues Write a program that creates a stack using MyStack and a queue using MyQueue. It then uses the push (enqueu) method to add strings to the stack (queue) and the pop (dequeue) method to remove strings from the stack (queue). TestStackQueue
  • 939.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Priority Queue A regular queue is a first-in and first-out data structure. Elements are appended to the end of the queue and are removed from the beginning of the queue. In a priority queue, elements are assigned with priorities. When accessing elements, the element with the highest priority is removed first. A priority queue has a largest-in, first-out behavior. For example, the emergency room in a hospital assigns patients with priority numbers; the patient with the highest priority is treated first. MyPriorityQueue TestPriorityQueue
  • 940.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.
  • 941.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introduction to Java Programming and Data Structures Thirteenth Edition Chapter 25 Binary Search Trees Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 942.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives 25.1 To become familiar with binary search trees (§25.2). 25.2 To represent binary trees using linked data structures (§25.3). 25.3 To search an element in binary search tree (§25.4). 25.4 To insert an element into a binary search tree (§25.5). 25.5 To traverse elements in a binary tree (§25.6). 25.6 To design and implement the Tree interface and the BST class (§25.7). 25.7 To delete elements from a binary search tree (§25.8). 25.8 To display binary tree graphically (§25.9). 25.9 To create iterators for traversing a binary tree (§25.10). 25.10 To implement Huffman coding for compressing data using a binary tree (§25.11).
  • 943.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Binary Trees A list, stack, or queue is a linear structure that consists of a sequence of elements. A binary tree is a hierarchical structure. It is either empty or consists of an element, called the root, and two distinct binary trees, called the left subtree and right subtree. 60 55 100 57 67 107 45 G F R M T A (A) (B)
  • 944.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved See How a Binary Search Tree Works https://liveexample.pearsoncmg.com/dsanimation/BSTeBook.html
  • 945.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Binary Tree Terms The root of left (right) subtree of a node is called a left (right) child of the node. A node without children is called a leaf. A special type of binary tree called a binary search tree is often useful. A binary search tree (with no duplicate elements) has the property that for every node in the tree the value of any node in its left subtree is less than the value of the node and the value of any node in its right subtree is greater than the value of the node. The binary trees in Figure 25.1 are all binary search trees. This section is concerned with binary search trees.
  • 946.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Representing Binary Trees A binary tree can be represented using a set of linked nodes. Each node contains a value and two links named left and right that reference the left child and right child, respectively, as shown in Figure 25.2. class TreeNode<E> { E element; TreeNode<E> left; TreeNode<E> right; public TreeNode(E o) { element = o; } }
  • 947.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Searching an Element in a Binary Search Tree public boolean search(E element) { TreeNode<E> current = root; // Start from the root while (current != null) if (element < current.element) { current = current.left; // Go left } else if (element > current.element) { current = current.right; // Go right } else // Element matches current.element return true; // Element is found return false; // Element is not in the tree }
  • 948.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Inserting an Element to a Binary Search Tree If a binary tree is empty, create a root node with the new element. Otherwise, locate the parent node for the new element node. If the new element is less than the parent element, the node for the new element becomes the left child of the parent. If the new element is greater than the parent element, the node for the new element becomes the right child of the parent. Here is the algorithm:
  • 949.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Inserting an Element to a Binary Tree
  • 950.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (1 of 20)
  • 951.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (2 of 20)
  • 952.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (3 of 20)
  • 953.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (4 of 20)
  • 954.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (5 of 20)
  • 955.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (6 of 20)
  • 956.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (7 of 20)
  • 957.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (8 of 20)
  • 958.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (9 of 20)
  • 959.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (10 of 20)
  • 960.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (11 of 20)
  • 961.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (12 of 20)
  • 962.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (13 of 20)
  • 963.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (14 of 20)
  • 964.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (15 of 20)
  • 965.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (16 of 20)
  • 966.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (17 of 20)
  • 967.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (18 of 20)
  • 968.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (19 of 20)
  • 969.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Trace Inserting 101 into the following tree (20 of 20)
  • 970.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Inserting 59 into the Tree
  • 971.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Tree Traversal (1 of 3) Tree traversal is the process of visiting each node in the tree exactly once. There are several ways to traverse a tree. This section presents inorder, preorder, postorder, depth-first, and breadth-first traversals. The inorder traversal is to visit the left subtree of the current node first recursively, then the current node itself, and finally the right subtree of the current node recursively. The postorder traversal is to visit the left subtree of the current node first, then the right subtree of the current node, and finally the current node itself.
  • 972.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Tree Traversal (2 of 3) The preorder traversal is to visit the current node first, then the left subtree of the current node recursively, and finally the right subtree of the current node recursively.
  • 973.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Tree Traversal (3 of 3) The breadth-first traversal is to visit the nodes level by level. First visit the root, then all children of the root from left to right, then grandchildren of the root from left to right, and so on. For example, in the tree in Figure 25.2, the inorder is 45 55 57 59 60 67 100 101 107. The postorder is 45 59 57 55 67 101 107 100 60. The preorder is 60 55 45 57 59 100 67 107 101. The breadth-first traversal is 60 55 100 45 57 67 107 59 101.
  • 974.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The Tree Interface The Tree interface defines common operations for trees. «interface» Tree<E> +search(e: E): boolean +insert(e: E): boolean +delete(e: E): boolean +inorder(): void +preorder(): void +postorder(): void +getSize(): int +isEmpty(): boolean +clear(): void Override the add, isEmpty, remove, containsAll, addAll, removeAll, retainAll, toArray(), and toArray(T[]) methods defined in Collection using default methods. Returns true if the specified element is in the tree. Returns true if the element is added successfully. Returns true if the element is removed from the tree successfully. Prints the nodes in inorder traversal. Prints the nodes in preorder traversal. Prints the nodes in postorder traversal. Returns the number of elements in the tree. Returns true if the tree is empty. Removes all elements from the tree. «interface» java.lang.Collection<E> Tree
  • 975.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved The BST Class Let’s define the binary tree class, named BST with A concrete BST class can be defined to extend AbstractTree. BST<E extends Comparable<E>> #root: TreeNode<E> #size: int +BST() +BST(objects: E[]) +path(e: E): java.util.List<TreeNode<E>> 1 m TreeNode<E> Link 0 The root of the tree. The number of nodes in the tree. Creates a default BST. Creates a BST from an array of elements. Returns the path of nodes from the root leading to the node for the specified element. The element may not be in the tree. «interface» Tree<E> BST
  • 976.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Example: Using Binary Trees Write a program that creates a binary tree using BST. Add strings into the binary tree and traverse the tree in inorder, postorder, and preorder. TestBST
  • 977.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Tree After Insertions George Adam Michael Daniel Jones Tom root Peter Inorder: Adam, Daniel George, Jones, Michael, Peter, Tom Postorder: Daniel Adam, Jones, Peter, Tom, Michael, George Preorder: George, Adam, Daniel, Michael, Jones, Tom, Peter
  • 978.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Deleting Elements in a Binary Search Tree (1 of 6) To delete an element from a binary tree, you need to first locate the node that contains the element and also its parent node. Let current point to the node that contains the element in the binary tree and parent point to the parent of the current node. The current node may be a left child or a right child of the parent node. There are two cases to consider:
  • 979.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Deleting Elements in a Binary Search Tree (2 of 6) Case 1: The current node does not have a left child, as shown in this figure (a). Simply connect the parent with the right child of the current node, as shown in this figure (b). parent current No left child Subtree parent Subtree current may be a left or right child of parent Subtree may be a left or right subtree of parent current points the node to be deleted
  • 980.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Deleting Elements in a Binary Search Tree (3 of 6) For example, to delete node 10 in Figure 25.9a. Connect the parent of node 10 with the right child of node 10, as shown in Figure 25.9b. 20 10 40 30 80 root 50 16 27 20 40 30 80 root 50 16 27
  • 981.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Deleting Elements in a Binary Search Tree (4 of 6) Case 2: The current node has a left child. Let rightMost point to the node that contains the largest element in the left subtree of the current node and parentOfRightMost point to the parent node of the rightMost node, as shown in Figure 25.10a. Note that the rightMost node cannot have a right child, but may have a left child. Replace the element value in the current node with the one in the rightMost node, connect the parentOfRightMost node with the left child of the rightMost node, and delete the rightMost node, as shown in Figure 25.10b.
  • 982.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Deleting Elements in a Binary Search Tree (5 of 6) Case 2 diagram parent current . . . rightMost parentOfRightMost parent . . . parentOfRightMost Content copied to current and the node deleted Right subtree Right subtree current current may be a left or right child of parent current points the node to be deleted The content of the current node is replaced by content by the content of the right-most node. The right-most node is deleted. leftChildOfRightMost leftChildOfRightMost
  • 983.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Deleting Elements in a Binary Search Tree (6 of 6) Case 2 example, delete 20 rightMost 20 10 40 30 80 root 50 16 27 16 10 40 30 80 root 50 27 14 14
  • 984.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Examples (1 of 3) Delete this node George Adam Michael Daniel Jones Tom Peter Daniel Adam Michael Jones Tom Peter
  • 985.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Examples (2 of 3) Daniel Adam Michael Jones Tom Peter Delete this node Daniel Michael Jones Tom Peter
  • 986.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Examples (3 of 3) Daniel Michael Jones Tom Peter Delete this node Daniel Jones Tom Peter TestBSTDelete
  • 987.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Binary Tree Time Complexity It is obvious that the time complexity for the inorder, preorder, and postorder is   O n , since each node is traversed only once. The time complexity for search, insertion and deletion is the height of the tree. In the worst case, the height of the tree is   O n .
  • 988.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Tree Visualization BTView BSTAnimation
  • 989.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Iterators An iterator is an object that provides a uniform way for traversing the elements in a container such as a set, list, binary tree, etc. TestBSTWithIterator
  • 990.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Data Compression: Huffman Coding In ASCII, every character is encoded in 8 bits. Huffman coding compresses data by using fewer bits to encode more frequently occurring characters. The codes for characters are constructed based on the occurrence of characters in the text using a binary tree, called the Huffman coding tree. Mississippi M p 1 0 s 0 i 0 1 1 Character Code Frequency M 000 1 P 001 2 s 01 4 i 1 4 000101011010110010011 21 bits
  • 991.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Constructing Huffman Tree (1 of 3) To construct a Huffman coding tree, use a greedy algorithm as follows: • Begin with a forest of trees. Each tree contains a node for a character. The weight of the node is the frequency of the character in the text. • Repeat this step until there is only one tree: Choose two trees with the smallest weight and create a new node as their parent. The weight of the new tree is the sum of the weight of the subtrees.
  • 992.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Constructing Huffman Tree (2 of 3) Mississippi weight: 1 ‘M’ weight: 4 ‘s’ weight: 4 ‘i’ weight: 2 ‘p’ weight: 1 ‘M’ weight: 4 ‘s’ weight: 4 ‘i’ weight: 2 ‘p’ weight: 3 weight: 1 ‘M’ weight: 4 ‘s’ weight: 4 ‘i’ weight: 2 ‘p’ weight: 3 weight: 7 weight: 1 ‘M’ weight: 4 ‘s’ weight: 4 ‘i’ weight: 2 ‘p’ weight: 3 weight: 7 weight: 11 0 1 1 1 0 0
  • 993.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Constructing Huffman Tree (3 of 3) HuffmanCode
  • 994.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.
  • 995.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Introduction to Java Programming and Data Structures Thirteenth Edition Chapter 26 AVL Trees Copyright © 2024 Pearson Education, Inc. All Rights Reserved
  • 996.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Objectives 26.1 To know what an AVL tree is (§26.1). 26.2 To understand how to rebalance a tree using the LL rotation, LR rotation, RR rotation, and RL rotation (§26.2). 26.3 To know how to design the AVLTree class (§26.3). 26.4 To insert elements into an AVL tree (§26.4). 26.5 To implement node rebalancing (§26.5). 26.6 To delete elements from an AVL tree (§26.6). 26.7 To implement the AVLTree class (§26.7). 26.8 To test the AVLTree class (§26.8). 26.9 To analyze the complexity of search, insert, and delete operations in AVL trees (§26.9).
  • 997.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Why AVL Tree? The search, insertion, and deletion time for a binary tree is dependent on the height of the tree. In the worst case, the height is   O n . If a tree is perfectly balanced, i.e., a complete binary tree, its height is . Can we maintain a perfectly balanced tree? Yes. But it will be costly to do so. The compromise is to maintain a well-balanced tree, i.e., the heights of two subtrees for every node are about the same.
  • 998.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved What Is an AVL Tree? AVL trees are well-balanced. AVL trees were invented by two Russian computer scientists G. M. Adelson-Velsky and E. M. Landis in 1962. In an AVL tree, the difference between the heights of two subtrees for every node is 0 or 1. It can be shown that the maximum height of an AVL tree is   O logn .
  • 999.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved AVL Tree Animation https://liveexample.pearsoncmg.com/dsanimation/AVLTree.html
  • 1000.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Balance Factor/Left-Heavy/Right-Heavy The process for inserting or deleting an element in an AVL tree is the same as in a regular binary search tree. The difference is that you may have to rebalance the tree after an insertion or deletion operation. The balance factor of a node is the height of its right subtree minus the height of its left subtree. A node is said to be balanced if its balance factor is 1, 0, or 1.  A node is said to be left-heavy if its balance factor is 1.  A node is said to be right-heavy if its balance factor is +1.
  • 1001.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Balancing Trees If a node is not balanced after an insertion or deletion operation, you need to rebalance it. The process of rebalancing a node is called a rotation. There are four possible rotations.
  • 1002.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved LL Imbalance and LL Rotation LL Rotation: An LL imbalance occurs at a node A such that A has a balance factor 2  and a left child B with a balance factor 1 or 0.  This type of imbalance can be fixed by performing a single right rotation at A. A -2 B -1 or 0 T2 T3 T1 h+1 h h T2’s height is h or h+1 A 0 or -1 B 0 or 1 T2 T3 T1 h+1 h h
  • 1003.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved RR Imbalance and RR Rotation RR Rotation: An RR imbalance occurs at a node A such that A has a balance factor +2 and a right child B with a balance factor +1 or 0. This type of imbalance can be fixed by performing a single left rotation at A. A +2 B +1 or 0 T2 T3 T1 h+1 h h T2’s height is h or h+1 A 0 or +1 B 0 or -1 T2 T3 T1 h+1 h h
  • 1004.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved LR Imbalance and LR Rotation LR Rotation: An LR imbalance occurs at a node A such 2  and a left child B with a balance factor +1. Assume B’s right child is C. This type of imbalance can be fixed by performing a double rotation (first a single left rotation at B and then a single right rotation at A). A -2 C -1, 0, or 1 T3 T4 T2 h h h B +1 T1 h T2 and T3 may have different height, but at least one' must have height of h. C 0 A 0 or 1 T3 T4 T2 h h h B 0 or -1 T1 h
  • 1005.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved RL Imbalance and RL Rotation RL Rotation: An RL imbalance occurs at a node A such that A has a balance factor +2 and a right child B with a balance factor 1.  Assume B’s left child is C. This type of imbalance can be fixed by performing a double rotation (first a single right rotation at B and then a single left rotation at A). A +2 C 0, -1, or 1 T3 T4 T2 h h h B -1 T1 h T2 and T3 may have different height, but at least one' must have height of h. C 0 B 0 or 1 T3 T4 T2 h h h A 0 or -1 T1 h
  • 1006.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Designing Classes for AVL Trees An AVL tree is a binary tree. So you can define the AVL Tree class to extend the BST class. AVLTree TestAVLTree
  • 1007.
    Copyright © 2024Pearson Education, Inc. All Rights Reserved Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.