Java
Java
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 1
Objectives
● To understand computer basics, programs, and operating systems (§§1.2–1.4).
● To describe the relationship between Java and the World Wide Web (§1.5).
● To understand the meaning of Java language specification, API, JDK, and IDE
(§1.6).
● To write a simple Java program (§1.7).
● To display output on the console (§1.7).
● To explain the basic syntax of a Java program (§1.7).
● To create, compile, and run Java programs (§1.8).
● To use sound Java programming style and document programs properly (§1.9).
● To explain the differences between syntax errors, runtime errors, and logic
errors (§1.10).
● To develop Java programs using NetBeans (§1.11).
● To develop Java programs using Eclipse (§1.12).
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 2
What is a Computer?
A computer consists of a CPU, memory, hard disk, floppy disk,
monitor, printer, and communication devices.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 3
CPU
The central processing unit (CPU) is the brain of a computer. It
retrieves instructions from memory and executes them. The CPU
speed is measured in megahertz (MHz), with 1 megahertz equaling 1
million pulses per second. The speed of the CPU has been improved
continuously. If you buy a PC now, you can get an Intel Pentium 4
Processor at 3 gigahertz (1 gigahertz is 1000 megahertz).
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 4
Memory
Memory is to store data and program instructions for CPU to
execute. A memory unit is an ordered sequence of bytes, each holds
eight bits. A program and its data must be brought to memory before
they can be executed. A memory byte is never empty, but its initial
content may be meaningless to your program. The current content of
a memory byte is lost whenever new information is placed in it.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 5
How Data is Stored?
Data of various kinds, such as numbers,
characters, and strings, are encoded as a
series of bits (zeros and ones). Computers
use zeros and ones because digital devices
have two stable states, which are referred to
as zero and one by convention. The
programmers need not to be concerned about
the encoding and decoding of data, which is
performed automatically by the system based
on the encoding scheme. The encoding
scheme varies. For example, character ‘J’ is
represented by 01001010 in one byte. A
small number such as three can be stored in a
single byte. If computer needs to store a
large number that cannot fit into a single
byte, it uses a number of adjacent bytes. No
two data can share or split a same byte. A
byte is the minimum storage unit.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 6
Storage Devices
Memory is volatile, because information is lost when the power is
off. Programs and data are permanently stored on storage devices
and are moved to memory when the computer actually uses them.
There are three main types of storage devices:Disk drives (hard disks
and floppy disks), CD drives (CD-R and CD-RW), and Tape drives.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 7
Output Devices: Monitor
The monitor displays information (text and graphics). The resolution
and dot pitch determine the quality of the display.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 8
Communication Devices
A DSL (digital subscriber line) uses a phone line and can transfer data in a
speed 20 times faster than a regular modem.
A cable modem uses the TV cable line maintained by the cable company. A
cable modem is as fast as a DSL.
Network interface card (NIC) is a device to connect a computer to a local
area network (LAN).
The LAN is commonly used in business, universities, and government
organizations. A typical type of NIC, called 10BaseT, can transfer data at
10 mbps (million bits per second).
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 9
Programs
Computer programs, known as software, are instructions to
the computer.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 10
Programming Languages
Machine Language Assembly Language High-Level Language
1101101010011010
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 11
Programming Languages
Machine Language Assembly Language High-Level Language
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 12
Programming Languages
Machine Language Assembly Language High-Level Language
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 13
Popular High-Level Languages
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 14
Interpreting/Compiling Source Code
A program written in a high-level language is called
a source program or source code. Because a
computer cannot understand a source program, a
source program must be translated into machine
code for execution. The translation can be done
using another programming tool called an
interpreter or a compiler.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 15
Interpreting Source Code
An interpreter reads one statement from the source
code, translates it to the machine code or virtual
machine code, and then executes it right away, as
shown in the following figure. Note that a statement
from the source code may be translated into several
machine instructions.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 16
Compiling Source Code
A compiler translates the entire source code into a
machine-code file, and the machine-code file is then
executed, as shown in the following figure.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 17
Operating Systems
The operating system (OS) is a
program that manages and controls
a computer’s activities. The
popular operating systems for
general-purpose computers
are Microsoft Windows, Mac
OS, and Linux. Application
programs, such as a Web
browser or a word processor,
cannot run unless an
operating system is installed
and running on the computer.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 18
Why Java?
The answer is that Java enables users to develop and
deploy applications on the Internet for servers, desktop
computers, and small hand-held devices. The future of
computing is being profoundly influenced by the Internet,
and Java promises to remain a big part of that future. Java
is the Internet programming language.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 19
Java, Web, and Beyond
● Java can be used to develop standalone
applications (desktop applications).
● Java can be used to develop applications
running from a browser.
● Java can also be used to develop applications
for hand-held devices.
● Java can be used to develop applications for
Web servers.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 20
Java’s History
● James Gosling and Sun Microsystems
● Oak
● Java, May 20, 1995, Sun World
● HotJava
– The first Java-enabled Web browser
● Early History Website:
[Link]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 21
JDK Versions
● JDK 1.02 (1995)
● JDK 1.1 (1996)
● JDK 1.2 (1998)
● JDK 1.3 (2000)
● JDK 1.4 (2002)
● JDK 1.5 (2004) a. k. a. JDK 5 or Java 5
● JDK 1.6 (2006) a. k. a. JDK 6 or Java 6
● JDK 1.7 (2011) a. k. a. JDK 7 or Java 7
● JDK 1.8 (2014) a. k. a. JDK 8 or Java 8
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 22
JDK Editions
● Java Standard Edition (J2SE)
– J2SE can be used to develop client-side standalone
applications or applets.
● Java Enterprise Edition (J2EE)
– J2EE can be used to develop server-side applications
such as Java servlets, Java ServerPages, and Java
ServerFaces.
● Java Micro Edition (J2ME).
– J2ME can be used to develop applications for mobile
devices such as cell phones.
This book uses J2SE to introduce Java
programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 23
Popular Java IDEs
● NetBeans
● Eclipse
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 24
A Simple Java Program
Listing 1.1
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
[Link]("Welcome to Java!");
}
} Animatio
n
Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 25
Creating and Editing Using NotePad
To use NotePad, type
notepad [Link]
from the DOS prompt.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 26
Creating and Editing Using WordPad
To use WordPad, type
write [Link]
from the DOS prompt.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 27
Creating, Compiling, and
Running Programs
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 28
Compiling Java Source Code
You can port a source program to any machine with appropriate
compilers. The source program must be recompiled, however, because
the object program can only run on a specific machine. Nowadays
computers are networked to work together. Java was designed to run
object programs on any platform. With Java, you write the program
once, and compile the source program into a special type of object
code, known as bytecode. The bytecode can then run on any computer
with a Java Virtual Machine, as shown below. Java Virtual Machine is
a software that interprets Java bytecode.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 29
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 30
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 31
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 32
Two More Simple Examples
Animatio
n
WelcomeWithThreeMessages Run
Animatio
n
ComputeExpression Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 33
Companion
Website Compiling and Running Java
from the Command Window
● Set path to JDK bin directory
– set path=c:\Program Files\java\jdk1.8.0\bin
● Set classpath to include the current directory
– set classpath=.
● Compile
– javac [Link]
● Run
– java Welcome
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 34
Compiling and Running Java
Companion
Website from TextPad
● See Supplement II.A on the Website for details
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 35
Anatomy of a Java Program
● Class name
● Main method
● Statements
● Statement terminator
● Reserved words
● Comments
● Blocks
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 36
Class Name
Every Java program must have at least one class.
Each class has a name. By convention, class names
start with an uppercase letter. In this example, the
class name is Welcome.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 37
Main Method
Line 2 defines the main method. In order to run a
class, the class must contain a method named main.
The program is executed from the main method.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 38
Statement
A statement represents an action or a sequence of actions.
The statement [Link]("Welcome to Java!") in
the program in Listing 1.1 is a statement to display the
greeting "Welcome to Java!“.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 39
Statement Terminator
Every statement in Java ends with a semicolon (;).
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 40
Reserved words
Reserved words or keywords are words that have a
specific meaning to the compiler and cannot be used for
other purposes in the program. For example, when the
compiler sees the word class, it understands that the word
after class is the name for the class.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 41
Blocks
A pair of braces in a program forms a block that groups
components of a program.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 42
Special Symbols
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 43
{ …}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 49
Appropriate Comments
Include a summary at the beginning of the program
to explain what the program does, its key features,
its supporting data structures, and any unique
techniques it uses.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 50
Naming Conventions
● Choose meaningful and descriptive names.
● Class names:
– Capitalize the first letter of each word in the
name. For example, the class name
ComputeExpression.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 51
Proper Indentation and Spacing
● Indentation
– Indent two spaces.
● Spacing
– Use blank line to separate segments of the code.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 52
Block Styles
Use end-of-line style for braces.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 53
Programming Errors
● Syntax Errors
– Detected by the compiler
● Runtime Errors
– Causes the program to abort
● Logic Errors
– Produces incorrect result
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 54
Syntax Errors
public class ShowSyntaxErrors {
public static main(String[] args) {
[Link]("Welcome to Java);
}
}
ShowSyntaxErrors Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 55
Runtime Errors
public class ShowRuntimeErrors {
public static void main(String[] args) {
[Link](1 / 0);
}
}
ShowRuntimeErrors Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 56
Logic Errors
public class ShowLogicErrors {
public static void main(String[] args) {
[Link]("Celsius 35 is Fahrenheit degree ");
[Link]((9 / 5) * 35 + 32);
}
}
ShowLogicErrors Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 57
Chapter 2 Elementary Programming
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 1
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 2
Objectives
● To write Java programs to perform simple computations (§2.2).
● To obtain input from the console using the Scanner class (§2.3).
● To use identifiers to name variables, constants, methods, and classes (§2.4).
● To use variables to store data (§§2.5–2.6).
● To program with assignment statements and assignment expressions (§2.6).
● To use constants to store permanent data (§2.7).
● To name classes, methods, variables, and constants by following their naming conventions (§2.8).
● To explore Java numeric primitive data types: byte, short, int, long, float, and double (§2.9.1).
● To read a byte, short, int, long, float, or double value from the keyboard (§2.9.2).
● To perform operations using operators +, -, *, /, and % (§2.9.3).
● To perform exponent operations using [Link](a, b) (§2.9.4).
● To write integer literals, floating-point literals, and literals in scientific notation (§2.10).
● To write and evaluate numeric expressions (§2.11).
● To obtain the current system time using [Link]() (§2.12).
● To use augmented assignment operators (§2.13).
● To distinguish between postincrement and preincrement and between postdecrement and predecrement (§2.14).
● To cast the value of one type to another type (§2.15).
● To describe the software development process and apply it to develop the loan payment program (§2.16).
● To write a program that converts a large amount of money into smaller units (§2.17).
● To avoid common errors and pitfalls in elementary programming (§2.18).
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 3
Introducing Programming with an
Example
Listing 2.1 Computing the Area of a Circle
This program computes the area of the circle.
Animatio
ComputeArea
n
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 4
animation
// Assign a radius
radius = 20;
// Compute area
area = radius * radius * 3.14159;
// Display results
[Link]("The area for the circle of radius " +
radius + " is " + area);
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 5
animation
// Display results
[Link]("The area for the circle of radius " +
radius + " is " + area);
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 6
animation
// Compute area
area = radius * radius * 3.14159;
// Display results
[Link]("The area for the circle of radius " +
radius + " is " + area);
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 7
animation
// Display results
[Link]("The area for the circle of radius " +
radius + " is " + area);
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 8
animation
// Compute area
area = radius * radius * 3.14159; print a message to the
console
// Display results
[Link]("The area for the circle of radius " +
radius + " is " + area);
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 9
Reading Input from the Console
1. Create a Scanner object
import [Link]; // Scanner is in the [Link]
package
Scanner input = new Scanner([Link]);
2. Use the method nextDouble() to obtain to a double
value. For example,
[Link]("Enter a double value: ");
Scanner input = new Scanner([Link]);
double d = [Link]();
Animatio
n
ComputeAreaWithConsoleInput ComputeAverage
Run Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 10
The information for the classes in an imported
package is not read in at compile time or
runtime unless the class is used in the program.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 11
Identifiers
● Identifiers are the names that identify the elements such
as classes, methods, and variables in a program.
● 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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 12
For example, $2, ComputeArea, area, radius, and
print are legal identifiers,
whereas
Note
Since Java is case sensitive, area, Area, and AREA
are all different identifiers.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 13
Variables
// Compute the first area
radius = 1.0;
area = radius * radius * 3.14159;
[Link]("The area is “ +
area + " for radius "+radius);
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 14
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;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 15
Assignment Statements
x = 1; // Assign 1 to x;
radius = 1.0; // Assign 1.0 to radius;
a = 'A'; // Assign 'A' to a;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 16
Declaring and Initializing
in One Step
● int x = 1;
● double d = 1.4;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 17
Named Constants
final datatype CONSTANTNAME = VALUE;
PI=3;
final int SIZE = 3;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 18
Naming Conventions
● 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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 19
Naming Conventions, cont.
● 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
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 20
Numerical Data Types
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 21
Reading Numbers from the Keyboard
Scanner input = new Scanner([Link]);
int value = [Link]();
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 22
Numeric Operators
A= d (/) * b + r (%)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 23
Integer Division
+, -, *, /, and %
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 24
Problem: Displaying Time
Write a program that obtains minutes and
remaining seconds from seconds.
DisplayTime Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 25
NOTE
Calculations involving floating-point numbers are
approximated because these numbers are not stored
with complete accuracy.
For example,
[Link](1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
displays 0.5000000000000001, not 0.5, and
[Link](1.0 - 0.9);
displays 0.09999999999999998, not 0.1.
Integers are stored precisely. Therefore, calculations
with integers yield a precise integer result.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 26
Exponent Operations
[Link]([Link](2, 3));
// Displays 8.0
[Link]([Link](4, 0.5));
// Displays 2.0
[Link]([Link](2.5, 2));
// Displays 6.25
[Link]([Link](2.5, -2));
// Displays 0.16
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 27
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;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 28
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 -231 (-2147483648) to 231–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).
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 29
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 30
double vs. float
default
The double type values are more accurate than the
float type values. For example,
[Link]("1.0 / 3.0 is " + 1.0 / 3.0);
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 31
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.
0.12345= 12.345E-2
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 32
Arithmetic Expressions
is translated to
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 33
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 34
Problem: Converting Temperatures
Write a program that converts a Fahrenheit degree
to Celsius using the formula:
FahrenheitToCelsius Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 35
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
Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 36
Augmented Assignment Operators
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 37
Increment and
Decrement Operators
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 38
Increment and
Decrement Operators, cont.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 39
Increment and
Decrement Operators, cont.
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;
Which is equivalent to the following two lines:
k= ++i;
k+=i;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 40
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--;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 41
Numeric Type Conversion
Consider the following statements:
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 42
Conversion Rules
When performing a binary operation involving two
operands of different types, Java automatically
converts the operand based on the following rules:
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 43
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)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 44
Problem: Keeping Two Digits After
Decimal Points
Write a program that displays the sales tax with two
digits after the decimal point.
SalesTax Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 45
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
ComputeLoan Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 47
Problem: Monetary Units
ComputeChange Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 48
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
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 49
Common Error 1:
Undeclared/Uninitialized Variables
and Unused Variables
double interestRate = 0.05;
double interest = interestrate * 45;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 50
Common Error 2: Integer Overflow
[Link](1.0 - 0.9);
Round-off Errors=(1/3)-0.333333
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 52
Common Error 4: Unintended Integer
Division
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 53
Common Pitfall 1: Redundant Input
Objects
Scanner input = new Scanner([Link]);
[Link]("Enter an integer: ");
int v1 = [Link]();
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved.
1
Motivations
If you assigned a negative value for radius in
Listing 2.2, [Link],
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?
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
2
Objectives
▪ To declare boolean variables and write Boolean expressions using relational
operators (§3.2).
▪ To implement selection control using one-way if statements (§3.3).
▪ To implement selection control using two-way if-else statements (§3.4).
▪ To implement selection control using nested if and multi-way if statements
(§3.5).
▪ To avoid common errors and pitfalls in if statements (§3.6).
▪ To generate random numbers using the [Link]() method (§3.7).
▪ To program using selection statements for a variety of examples
(SubtractionQuiz, BMI, ComputeTax) (§§3.7–3.9).
▪ To combine conditions using logical operators (&&, ||, and !) (§3.10).
▪ To program using selection statements with combined conditions (LeapYear,
Lottery) (§§3.11–3.12).
▪ To implement selection control using switch statements (§3.13).
▪ To write expressions using the conditional expression (§3.14).
▪ To examine the rules governing operator precedence and associativity (§3.15).
▪ To apply common techniques to debug errors (§3.16).
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved.
3
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
4
Relational Operators
Java Mathematics Name Example Result
Operator Symbol (radius is 5)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
5
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
7
Note
if i > 0 { if (i > 0) {
[Link]("i is positive"); [Link]("i is positive");
} }
(a) Wrong (b) Correct
if (i > 0) { if (i > 0)
[Link]("i is positive"); Equivalent [Link]("i is positive");
}
(a) (b)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
8
Simple if Demo
SimpleIfDemo Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
9
The Two-way if Statement
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
10
if-else Example
if (radius >= 0) {
area = radius * radius * 3.14159;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
11
Multiple Alternative if Statements
(a) (b)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
12
Multi-Way if-else Statements
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
13
animation
Trace if-else statement
Suppose score is 70.0 The condition is false
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
14
animation
Trace if-else statement
Suppose score is 70.0 The condition is false
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
15
animation
Trace if-else statement
Suppose score is 70.0 The condition is true
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
16
animation
Trace if-else statement
Suppose score is 70.0 grade is C
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
17
animation
Trace if-else statement
Suppose score is 70.0 Exit the if statement
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
18
Note
The else clause matches the most recent if clause in the
same block.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
19
Note, cont.
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)
[Link]("A");
}
else
[Link]("B");
This statement prints B.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
20
Common Errors
Adding a semicolon at the end of an if clause is a common
mistake.
if (radius >= 0); Wrong
{
area = radius*radius*PI;
[Link](
"The area for the circle of radius " +
radius + " is " + area);
}
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
21
TIP
if (number % 2 == 0) Equivalent
even = true; boolean even
else = number % 2 == 0;
even = false;
(a) (b)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
22
CAUTION
if (even == true) Equivalent if (even)
[Link]( [Link](
"It is even."); "It is even.");
(a) (b)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
23
Generating Random Numbers
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
24
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 Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
25
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
ComputeAndInterpretBMI Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
26
Problem: Computing Taxes
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
27
Problem: Computing Taxes, cont.
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 Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
28
Logical Operators
Operator Name Description
|| or logical disjunction
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
29
Truth Table for Operator !
true false !(age > 18) is false, because (age > 18) is true.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
30
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
true false false (age > 18) && (weight > 140) is false, because (weight
true true true (age > 18) && (weight >= 140) is true, because both
false true true (age > 34) || (weight <= 140) is true, because (age > 34)
true
true false
true
true true
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
32
Truth Table for Operator ^
p1 p2 p1 ^ p2 Example (assume age = 24, weight = 140)
false false false (age > 34) ^ (weight > 140) is false, because (age > 34) is false
false true true (age > 34) ^ (weight >= 140) is true, because (age > 34) is false
true false true (age > 14) ^ (weight > 140) is true, because (age > 14) is
TestBooleanOperators Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
34
Examples
[Link]("Is " + number + " divisible by 2 and 3? " +
((number % 2 == 0) && (number % 3 == 0)));
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
35
Companion
Website
The & and | Operators
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
36
Companion
Website
The & and | Operators
If x is 1, what is x after this
expression?
(x > 1) & (x++ < 10)
LeapYear Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
38
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 Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
39
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: [Link]("Errors: invalid status");
[Link](1);
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
40
switch Statement Flow Chart
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
41
switch Statement Rules
The switch-expression
must yield a value of char, switch (switch-expression) {
byte, short, int or String
type and must always be case value1: statement(s)1;
enclosed in parentheses. break;
case value2: statement(s)2;
The value1, ..., and valueN must break;
have the same data type as the …
value of the switch-expression.
The resulting statements in the case valueN: statement(s)N;
case statement are executed when break;
the value in the case statement default: statement(s)-for-default;
matches the value of the switch-
}
expression. Note that value1, ...,
and valueN are constant
expressions, meaning that they
cannot contain variables in the
expression, such as 1 + x.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
42
switch Statement Rules
The keyword break is optional, switch (switch-expression) {
but it should be used at the end of
case value1: statement(s)1;
each case in order to terminate the
remainder of the switch break;
statement. If the break statement case value2: statement(s)2;
is not present, the next case
statement will be executed. break;
…
case valueN: statement(s)N;
The default case, which is break;
optional, can be used to perform default: statement(s)-for-default;
actions when none of the
specified cases matches the
}
switch-expression.
When the value in a case statement matches the value
of the switch-expression, the statements starting from
this case are executed until either a break statement or
the end of the switch statement is reached.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
43
animation
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
44
animation
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
45
animation
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
46
animation
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
47
animation
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
48
animation
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
49
animation
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
50
Problem: Chinese Zodiac
Write a program that prompts the user to enter a year
and displays the animal for the year.
ChineseZodiac Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
51
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
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
52
Conditional Operator
if (num % 2 == 0)
[Link](num + “is even”);
else
[Link](num + “is odd”);
[Link](
(num % 2 == 0)? num + “is even” :
num + “is odd”);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
53
Conditional Operator, cont.
boolean-expression ? exp1 : exp2
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
54
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)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
55
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
56
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))
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
57
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
(1) inside parentheses first
3 + 4 * 4 > 5 * 7 – 1
(2) multiplication
3 + 16 > 5 * 7 – 1
(3) multiplication
3 + 16 > 35 – 1
(4) addition
19 > 35 – 1
(5) subtraction
19 > 34
(6) greater than
false
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
58
Companion
Website
Operand Evaluation Order
Supplement III.A, “Advanced discussions on
how an expression is evaluated in the JVM.”
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
59
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
60
Debugger
Debugger is a program that facilitates debugging.
You can use a debugger to
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
61
Companion
Website Debugging in NetBeans
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
62
Companion
Website Debugging in Eclipse
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
63
Chapter 4 Mathematical Functions,
Characters, and Strings
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
1
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
2
Objectives
F To solve mathematics problems by using the methods in the Math class (§4.2).
F To represent characters using the char type (§4.3).
F To encode characters using ASCII and Unicode (§4.3.1).
F To represent special characters using the escape sequences (§4.4.2).
F To cast a numeric value to a character and cast a character to an integer (§4.3.3).
F To compare and test characters using the static methods in the Character class (§4.3.4).
F To introduce objects and instance methods (§4.4).
F To represent strings using the String objects (§4.4).
F To return the string length using the length() method (§4.4.1).
F To return a character in the string using the charAt(i) method (§4.4.2).
F To use the + operator to concatenate strings (§4.4.3).
F To read strings from the console (§4.4.4).
F To read a character from the console (§4.4.5).
F To compare strings using the equals method and the compareTo methods (§4.4.6).
F To obtain substrings (§4.4.7).
F To find a character or a substring in a string using the indexOf method (§4.4.8).
F To program using characters and strings (GuessBirthday) (§4.5.1).
F To convert a hexadecimal character to a decimal value (HexDigit2Dec) (§4.5.2).
F To revise the lottery program using strings (LotteryUsingStrings) (§4.5.3).
F To format output using the [Link] method (§4.6).
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
3
Mathematical Functions
Java provides many useful methods in the Math
class for performing common mathematical
functions.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
4
The Math Class
F Class constants:
– PI
–E
F Class methods:
– Trigonometric Methods
– Exponent Methods
– Rounding Methods
– min, max, abs, and random Methods
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
5
Trigonometric Methods
F sin(double a) Examples:
F cos(double a)
[Link](0) returns 0.0
F tan(double a) [Link]([Link] / 6)
returns 0.5
F acos(double a) [Link]([Link] / 2)
returns 1.0
F asin(double a)
[Link](0) returns 1.0
F atan(double a) [Link]([Link] / 6)
returns 0.866
[Link]([Link] / 2)
Radians returns 0
toRadians(90)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
6
Exponent Methods
F exp(double a) Examples:
Returns e raised to the power of a.
[Link](1) returns 2.71
F log(double a)
[Link](2.71) returns 1.0
Returns the natural logarithm of a.
[Link](2, 3) returns 8.0
F log10(double a) [Link](3, 2) returns 9.0
Returns the 10-based logarithm of [Link](3.5, 2.5) returns
a. 22.91765
[Link](4) returns 2.0
F pow(double a, double b)
[Link](10.5) returns 3.24
Returns a raised to the power of b.
F sqrt(double a)
Returns the square root of a.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
7
Rounding Methods
F double ceil(double x)
x rounded up to its nearest integer. This integer is returned as a double
value.
F double floor(double x)
x is rounded down to its nearest integer. This integer is returned as a
double value.
F 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.
F int round(float x)
Return (int)[Link](x+0.5).
F long round(double x)
Return (long)[Link](x+0.5).
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
8
Rounding Methods Examples
[Link](2.1) returns 3.0
[Link](2.0) returns 2.0
[Link](-2.0) returns –2.0
[Link](-2.1) returns -2.0
[Link](2.1) returns 2.0
[Link](2.0) returns 2.0
[Link](-2.0) returns –2.0
[Link](-2.1) returns -3.0
[Link](2.1) returns 2.0
[Link](2.0) returns 2.0
[Link](-2.0) returns –2.0
[Link](-2.1) returns -2.0
[Link](2.5) returns 2.0
[Link](-2.5) returns -2.0
[Link](2.6f) returns 3
[Link](2.0) returns 2
[Link](-2.0f) returns -2
[Link](-2.6) returns -3
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
9
min, max, and abs
F max(a, b)and min(a, b) Examples:
Returns the maximum or
minimum of two parameters. [Link](2, 3) returns 3
F abs(a) [Link](2.5, 3) returns
Returns the absolute value of the 3.0
parameter. [Link](2.5, 3.6)
F random() returns 2.5
Returns a random double value [Link](-2) returns 2
in the range [0.0, 1.0). [Link](-2.1) returns
2.1
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
10
The random Method
Generates a random double value greater than or equal to 0.0 and less
than 1.0 (0 <= [Link]() < 1.0).
Examples:
In general,
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
11
Case Study: Computing Angles
of a Triangle
x2, y2
A = acos((a * a - b * b - c * c) / (-2 * b * c))
a B = acos((b * b - a * a - c * c) / (-2 * a * c))
B
c C = acos((c * c - b * b - a * a) / (-2 * a * b))
C
A x3, y3
b
x1, y1
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
12
Character Data Type
Four hexadecimal digits.
char letter = 'A'; (ASCII)
char numChar = '4'; (ASCII)
char letter = '\u0041'; (Unicode)
char numChar = '\u0034'; (Unicode)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
14
ASCII Code for Commonly Used
Characters
Characters Code Value in Decimal Unicode Value
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
15
Escape Sequences for Special Characters
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
16
Appendix B: ASCII Character Set
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
17
ASCII Character Set, cont.
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
18
Casting between char and
Numeric Types
int i = 'a'; // Same as int i = (int)'a';
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
19
Comparing and Testing
Characters
if (ch >= 'A' && ch <= 'Z')
[Link](ch + " is an uppercase letter");
else if (ch >= 'a' && ch <= 'z')
[Link](ch + " is a lowercase letter");
else if (ch >= '0' && ch <= '9')
[Link](ch + " is a numeric character");
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
20
Methods in the Character Class
Method Description
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
21
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 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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
22
Simple Methods for String Objects
Method Description
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
23
Simple Methods for String Objects
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
[Link](arguments).
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
24
Getting String Length
String message = "Welcome to Java";
[Link]("The length of " + message + " is "
+ [Link]());
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
25
Getting Characters from a String
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
26
Converting Strings
"Welcome".toLowerCase() returns a new string, welcome.
"Welcome".toUpperCase() returns a new string,
WELCOME.
" Welcome ".trim() returns a new string, Welcome.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
27
String Concatenation
String s3 = [Link](s2); or String s3 = s1 + s2;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
28
Reading a String from the Console
Scanner input = new Scanner([Link]);
[Link]("Enter three words separated by spaces: ");
String s1 = [Link]();
String s2 = [Link]();
String s3 = [Link]();
[Link]("s1 is " + s1);
[Link]("s2 is " + s2);
[Link]("s3 is " + s3);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
29
Reading a Character from the
Console
Scanner input = new Scanner([Link]);
[Link]("Enter a character: ");
String s = [Link]();
char ch = [Link](0);
[Link]("The character entered is " + ch);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
30
Comparing Strings
Method Description
OrderTwoCities Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
31
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, Returns this string’s substring that begins at the specified beginIndex and
endIndex) 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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
32
Finding a Character or a Substring
in a String
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, Returns the index of the last occurrence of ch before fromIndex in this
fromIndex) 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, Returns the index of the last occurrence of string s before fromIndex.
fromIndex) Returns -1 if not matched.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
33
Finding a Character or a Substring
in a String
int k = [Link](' ');
String firstName = [Link](0, k);
String lastName = [Link](k + 1);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
34
Conversion between Strings and
Numbers
int intValue = [Link](intString);
double doubleValue = [Link](doubleString);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
35
Problem: Guessing Birthday
The program can guess your birth date. Run
to see how it works.
GuessBirthday Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
36
Mathematics Basis for the Game
19 is 10011 in binary. 7 is 111 in binary. 23 is 11101 in binary
10000
10000 00110 1000
10 10 100
+ 1 + 1 + 1
10011 00111 11101
19 7 23
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
37
Case Study: Converting a
Hexadecimal Digit to a Decimal Value
Write a program that converts a hexadecimal digit
into a decimal value.
HexDigit2Dec Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
38
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 Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
39
Formatting Output
Use the printf statement.
[Link](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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
40
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;
items
double amount = 45.56;
[Link]("count is %d and amount is %f", count, amount);
FormatDemo Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
42
Chapter 5 Loops
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved.
1
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:
[Link]("Welcome to Java!");
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
2
Opening Problem
Problem:
[Link]("Welcome to Java!");
[Link]("Welcome to Java!");
[Link]("Welcome to Java!");
[Link]("Welcome to Java!");
[Link]("Welcome to Java!");
[Link]("Welcome to Java!");
100
times
…
…
…
[Link]("Welcome to Java!");
[Link]("Welcome to Java!");
[Link]("Welcome to Java!");
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
3
Introducing while Loops
int count = 0;
while (count < 100) {
[Link]("Welcome to Java");
count++;
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
4
Objectives
▪ To write programs for executing statements repeatedly using a while loop
(§5.2).
▪ To follow the loop design strategy to develop loops (§§5.2.1–5.2.3).
▪ To control a loop with a sentinel value (§5.2.4).
▪ To obtain large input from a file using input redirection rather than typing
from the keyboard (§5.2.5).
▪ To write loops using do-while statements (§5.3).
▪ To write loops using for statements (§5.4).
▪ To discover the similarities and differences of three types of loop statements
(§5.5).
▪ To write nested loops (§5.6).
▪ To learn the techniques for minimizing numerical errors (§5.7).
▪ To learn loops from a variety of examples (GCD, FutureTuition,
Dec2Hex) (§5.8).
▪ To implement program control with break and continue (§5.9).
▪ To write a program that displays prime numbers (§5.11).
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved.
5
while Loop Flow Chart
int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
[Link]("Welcome to Java!");
Statement(s); count++;
} }
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
6
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
7
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
8
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
9
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
10
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
11
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
12
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
13
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
14
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
15
Problem: Repeat Addition Until Correct
RepeatAdditionQuiz Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
16
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 Run
GuessNumber Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
17
Problem: An Advanced Math Learning Tool
SubtractionQuizLoop Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
18
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
19
Caution
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;
}
[Link](sum);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
20
do-while Loop
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
21
do-while Loop
TestDoWhile
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
22
for Loops
for (initial-action; loop- int i;
continuation-condition; action- for (i = 0; i < 100; i++) {
after-each-iteration) { [Link](
// loop body;
Statement(s); "Welcome to Java!");
} }
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
23
for Loops
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
24
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
25
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
26
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
27
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
28
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
29
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
30
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
31
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
32
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
33
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
34
Note
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; [Link](i++));
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
36
Caution
Adding a semicolon at the end of the for clause before
the loop body is a common mistake, as shown below:
Logic
Error
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
37
Caution, cont.
Similarly, the following loop is also wrong:
int i=0;
while (i < 10); Logic Error
{
[Link]("i is " + i);
i++;
}
In the case of the do loop, the following semicolon is
needed to end the loop.
int i=0;
do {
[Link]("i is " + i);
i++;
} while (i<10); Correct
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
38
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) { Equivalent for ( ; loop-continuation-condition; )
// Loop body // Loop body
} }
(a) (b)
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 CheckPoint
Question 5.12.2 in Section 5.12 for such a case ):
for (initial-action; initial-action;
loop-continuation-condition; Equivalent while (loop-continuation-condition) {
action-after-each-iteration) { // Loop body;
// Loop body; action-after-each-iteration;
} }
(a) (b)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
39
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
40
Nested Loops
Problem: Write a program that uses nested for
loops to print a multiplication table.
MultiplicationTable Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
41
Minimizing Numerical Errors
Numeric errors involving floating-point
numbers are inevitable. This section discusses
how to minimize such errors through an
example.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
42
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 Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
43
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 Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
44
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
...
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
45
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 hn, hn-1, hn-2, ... , h2, h1, and h0 such that
Dec2Hex Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
46
Using break and continue
You can use break in a loop to You can use the continue
immediately terminate the loop. keyword in a loop, it ends the
current iteration and program
control goes to the end of the
loop body.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
47
Using break and continue
Examples for using the break and continue
keywords:
[Link]
TestBreak Run
[Link]
TestContinue Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
48
break
public class TestBreak {
public static void main(String[] args) {
int sum = 0;
int number = 0;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
49
continue
public class TestContinue {
public static void main(String[] args) {
int sum = 0;
int number = 0;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
50
Break and continue
➢ The continue statement is always inside a loop.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
51
Break and continue
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
52
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.
low high
String s a b c d e f g n h g f e d c b a
Palindrome Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
53
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 Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
54
Chapter 6 Methods
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 1
Opening Problem
Find the sum of integers from 1 to 10, from 20 to 30, and
from 35 to 45, respectively.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 2
Problem
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
[Link]("Sum from 1 to 10 is " + sum);
sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
[Link]("Sum from 20 to 30 is " + sum);
sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
[Link]("Sum from 35 to 45 is " + sum);
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 3
Problem
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
[Link]("Sum from 1 to 10 is " + sum);
sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
[Link]("Sum from 20 to 30 is " + sum);
sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
[Link]("Sum from 35 to 45 is " + sum);
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 4
Solution
public static int sum(int i1, int i2) {
int sum = 0;
for (int i = i1; i <= i2; i++)
sum += i;
return sum;
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 7
Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 8
Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 9
Method Signature
Method signature is the combination of the method name and the
parameter list.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 10
Formal Parameters
The variables defined in the method header/declaration
are known as formal parameters.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 11
Actual Parameters
When a method is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 12
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 13
Calling Methods
Testing the max method
This program demonstrates calling a method max
to return the largest of the int values
Animatio
n
TestMax
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 14
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 15
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 16
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 17
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 18
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 19
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 20
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 21
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 22
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 23
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 24
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 25
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.
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 26
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 [Link] (e.g., [Link]).
Notes:
●The syntax to invoke an instance method is
[Link](arguments).
●A method may have many arguments or no arguments.
●For example, the charAt(index) method has one argument, but the
length() method has no arguments. Recall that the syntax to invoke
a static method is [Link](arguments).
●For example, the pow method in the Math class can be invoked
using [Link](2, 2.5).
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 27
Call Stacks
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 28
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 29
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 30
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 31
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 32
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 33
animation
Declare result
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 34
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 35
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 36
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 37
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 38
void Method Example
This type of method does not return a value. The method
performs some actions.
TestVoidMethod
TestReturnGradeMethod
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 39
Passing Parameters
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
[Link](message);
}
Increment
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 41
Pass by Value
TestPassByValue
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 42
Pass by Value, cont.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 43
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
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 44
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
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 45
Overloading Methods
Overloading the max Method
● Overloading methods enables you to define the methods
with the same name as long as their signatures are
different.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 46
Ambiguous Invocation
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 47
Ambiguous Invocation
public class AmbiguousOverloading {
public static void main(String[] args) {
[Link](max(1, 2));
// 1 and 2 are two int literals, so there is no
//error to use both methods
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 50
Scope of Local Variables, cont.
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 51
Scope of Local Variables, cont.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 52
Scope of Local Variables, cont.
// 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;
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 53
Scope of Local Variables, cont.
// With errors
public static void incorrectMethod() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
int x = 0;
x += i;
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 54
Method Abstraction
You can think of the method body as a black box
that contains the detailed implementation for the
method.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 55
Benefits of Methods
• Write a method once and reuse it anywhere.
• Information hiding. Hide the implementation
from the user.
• Reduce complexity.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 56
Case Study: Generating Random
Characters
Computer programs process numerical data and characters.
You have seen many examples that involve numerical data.
It is also important to understand characters and how to
process them.
As introduced in Section 2.9, 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 <= [Link]() < 1.0, you
have to add 1 to 65535.)
(int)([Link]() * (65535 + 1))
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 57
Case Study: Generating Random
Characters, cont.
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' + [Link]() * ((int)'z' - (int)'a' + 1)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 58
Case Study: Generating Random
Characters, cont.
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' + [Link]() * ((int)'z' - (int)'a' + 1)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 59
Case Study: Generating Random
Characters, cont.
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' + [Link]() * ('z' - 'a' + 1)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 61
The RandomCharacter Class
// [Link]: 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 + [Link]() * (ch2 - ch1 + 1));
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 62
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 63
PrintCalender Case Study
Let us use the PrintCalendar example to demonstrate the
stepwise refinement approach.
PrintCalendar
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 64
Design Diagram
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 65
Design Diagram
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 66
Design Diagram
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 67
Design Diagram
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 68
Design Diagram
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 69
Design Diagram
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 70
Design Diagram
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 71
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:
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 72
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 73
Benefits of Stepwise Refinement
Simpler Program
Reusing Methods
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 74
Chapter 7 Single-Dimensional
Arrays
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 1
Opening Problem
Read one hundred numbers, compute their
average, and find out how many numbers are
above the average.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 2
Objectives
● To describe why arrays are necessary in programming (§7.1).
● To declare array reference variables and create arrays (§§7.2.1–7.2.2).
● To obtain array size using [Link] and know default values in an array (§7.2.3).
● To access array elements using indexes (§7.2.4).
● To declare, create, and initialize an array using an array initializer (§7.2.5).
● To program common array operations (displaying arrays, summing all elements, finding the
minimum and maximum elements, random shuffling, and shifting elements) (§7.2.6).
● To simplify programming using the foreach loops (§7.2.7).
● To apply arrays in application development (AnalyzeNumbers, DeckOfCards) (§§7.3–7.4).
● To copy contents from one array to another (§7.5).
● To develop and invoke methods with array arguments and return values (§§7.6–7.8).
● To define a method with a variable-length argument list (§7.9).
● To search elements using the linear (§7.10.1) or binary (§7.10.2) search algorithm.
● To sort an array using the selection sort approach (§7.11).
● To use the methods in the [Link] class (§7.12).
● To pass arguments to the main method from the command line (§7.13).
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 3
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 4
Declaring Array Variables
● datatype[] arrayRefVar;
Example:
double[] myList;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 5
Creating Arrays
arrayRefVar = new datatype[arraySize];
Example:
myList = new double[10];
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 6
Declaring and Creating
in One Step
● datatype[] arrayRefVar = new
datatype[arraySize];
double[] myList = new double[10];
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 7
The Length of an Array
Once an array is created, its size is fixed. It cannot be
changed. You can find its size using
[Link]
For example,
[Link] returns 10
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 8
Default Values
When an array is created, its elements are
assigned the default value of
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 9
Indexed Variables
The array elements are accessed through the index. The
array indices are 0-based, i.e., it starts from 0 to
[Link]-1. In the example in Figure 6.1,
myList holds ten double values and the indices are
from 0 to 9.
arrayRefVar[index];
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 10
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].
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 11
Array Initializers
● Declaring, creating, initializing in one step:
double[] myList = {1.9, 2.9, 3.4, 3.5};
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 12
Declaring, creating, initializing
Using the Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 13
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;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 15
animation
Trace Program with Arrays
i becomes 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 16
animation
Trace Program with Arrays
i (=1) is less than 5
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 17
animation
Trace Program with Arrays
After this line is executed, value[1] is 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 18
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 19
animation
Trace Program with Arrays
i (= 2) is less than 5
public class Test {
public static void main(String[]
args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] +
values[4];
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 20
animation
Trace Program with Arrays
After this line is executed,
values[2] is 3 (2 + 1)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 21
animation
Trace Program with Arrays
After this, i becomes 3.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 22
animation
Trace Program with Arrays
i (=3) is still less than 5.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 23
animation
Trace Program with Arrays
After this line, values[3] becomes 6 (3 + 3)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 24
animation
Trace Program with Arrays
After this, i becomes 4
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 25
animation
Trace Program with Arrays
i (=4) is still less than 5
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 26
animation
Trace Program with Arrays
After this, values[4] becomes 10 (4 + 6)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 27
animation
Trace Program with Arrays
After i++, i becomes 5
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 28
animation
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 29
animation
Trace Program with Arrays
After this line, values[0] is 11 (1 + 10)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 30
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)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 31
Initializing arrays with input values
Double[] mylist= new double[10];
[Link] input = new [Link]([Link]);
[Link]("Enter " + [Link] + " values: ");
for (int i = 0; i < [Link]; i++)
{
[Link](“please enter the elements value
mylist[”+i+”]”);
myList[i] = [Link]();
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 32
Initializing arrays with random values
A+ [Link]() * b
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 33
Printing arrays
//output:
Mylist[0]=2 mylist[1]=
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 34
Summing all elements
double total = 0;
for (int i = 0; i < [Link]; i++) {
total += myList[i];
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 35
Finding the largest element
double max = myList[0];
for (int i = 1; i < [Link]; i++) {
if (myList[i] > max)
max = myList[i];
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 36
Random shuffling
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 37
Shifting Elements
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 38
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:
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 39
Opening Problem
Read one hundred numbers, compute their
average, and find out how many numbers are
above the average.
Animatio
n
AnalyzeNumbers
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 40
Problem: Deck of Cards
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:
Animatio
n
DeckOfCards Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 41
Problem: Deck of Cards, cont.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 42
Problem: Deck of Cards, cont.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 45
Companion
Website
Problem: Lotto Numbers
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 46
Copying Arrays
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;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 47
Copying Arrays
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new
int[[Link]];
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 48
The arraycopy Utility
arraycopy(sourceArray, src_pos,
targetArray, tar_pos, length);
Example:
[Link](sourceArray, 0,
targetArray, 0, [Link]);
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 49
Passing Arrays to Methods
public static void printArray(int[] array) {
for (int i = 0; i < [Link]; i++) {
[Link](array[i] + " ");
}
}
Anonymous array
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 50
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 51
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 54
Swap Methods (Cont.)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 55
Call Stack
TestPassArray Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 59
Example, cont.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 60
Returning an Array from a Method
public static int[] reverse(int[] list) {
int[] result = new int[[Link]];
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 61
animation
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 0
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 62
animation
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 0
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 63
animation
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 0
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 64
animation
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 65
animation
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 66
animation
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 67
animation
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 2 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 68
animation
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 2 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 69
animation
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 2 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 70
animation
return result;
}
list 1 2 3 4 5 6
result 0 0 0 3 2 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 71
animation
return result;
}
list 1 2 3 4 5 6
result 0 0 0 3 2 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 72
animation
return result;
}
list 1 2 3 4 5 6
result 0 0 0 3 2 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 73
animation
return result;
}
list 1 2 3 4 5 6
result 0 0 4 3 2 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 74
animation
return result;
}
list 1 2 3 4 5 6
result 0 0 4 3 2 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 75
animation
return result;
}
list 1 2 3 4 5 6
result 0 0 4 3 2 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 76
animation
return result;
}
list 1 2 3 4 5 6
result 0 5 4 3 2 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 77
animation
return result;
}
list 1 2 3 4 5 6
result 0 5 4 3 2 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 78
animation
return result;
}
list 1 2 3 4 5 6
result 0 5 4 3 2 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 79
animation
return result;
}
list 1 2 3 4 5 6
result 6 5 4 3 2 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 80
animation
return result;
}
list 1 2 3 4 5 6
result 6 5 4 3 2 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 81
animation
return result;
}
list 1 2 3 4 5 6
result 6 5 4 3 2 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 82
animation
return result;
}
list 1 2 3 4 5 6
list2
result 6 5 4 3 2 1
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 83
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 Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 84
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 85
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 86
animation
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 87
animation
Linear Search Animation
[Link]
[Link]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 88
From Idea to Solution
/** The method for finding a key in the list */
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < [Link]; i++)
if (key == list[i])
return i;
return -1;
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 90
Binary Search, cont.
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 91
animation
Binary Search
Key List
8 1 2 3 4 6 7 8 9
8 1 2 3 4 6 7 8 9
8 1 2 3 4 6 7 8 9
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 92
animation
Binary Search Animation
[Link]
[Link]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 93
Binary Search, cont.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 94
Binary Search, cont.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 95
Binary Search, cont.
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 96
From Idea to Soluton
/** Use binary search to find the key in the list */
public static int binarySearch(int[] list, int key) {
int low = 0;
int high = [Link] - 1;
return -1 - low;
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 97
The [Link] 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 [Link] class. For example, the
following code searches the keys in an array of numbers and an array of
characters.
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
[Link]("Index is " +
[Link](list, 11)); Return is 4
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 98
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 99
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 100
animation
Selection Sort Animation
[Link]
[Link]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 101
From Idea to Solution
for (int i = 0; i < [Link]; i++) {
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
//as it may be in the right position
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}
...
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 102
for (int i = 0; i < listSize; 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..listSize-1]
}
Expand
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i+1; j < [Link]; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 103
for (int i = 0; i < listSize; 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..listSize-1]
}
Expand
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i; j < [Link]; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 104
for (int i = 0; i < listSize; 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..listSize-1]
}
Expand
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 105
Wrap it in a Method
/** The method for sorting the numbers */
public static void selectionSort(double[] list) {
for (int i = 0; i < [Link]; i++) {
// Find the minimum in the list[i..[Link]-1]
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < [Link]; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 106
The [Link] Method
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 107
The [Link](list) Method
The [Link](list) method can be used to return a string
representation for the list.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 108
Pass Arguments to Invoke the Main
Method
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 109
Main Method Is Just a Regular Method
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 110
Command-Line Parameters
class TestMain {
public static void main(String[] args) {
...
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 111
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 112
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
Calculator java Calculator 2 - 3
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 113
Chapter 8 Multidimensional Arrays
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 1
Motivations
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 2
Motivations
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 3
Objectives
❑ To give examples of representing data using two-dimensional arrays
(§8.1).
❑ 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).
❑ To program common operations for two-dimensional arrays (displaying
arrays, summing all elements, finding the minimum and maximum
elements, and random shuffling) (§8.3).
❑ To pass two-dimensional arrays to methods (§8.4).
❑ To write a program for grading multiple-choice questions using
two-dimensional arrays (§8.5).
❑ To solve the closest-pair problem using two-dimensional arrays (§8.6).
❑ To check a Sudoku solution using two-dimensional arrays (§8.7).
❑ To use multidimensional arrays (§8.8).
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 4
Declare/Create Two-dimensional Arrays
// Declare array ref var
dataType[][] refVar;
// Alternative syntax
dataType refVar[][] = new dataType[10][10];
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 5
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;
double[][] x;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 6
Two-dimensional Array Illustration
[Link]? 5 [Link]? 4
matrix[0].length? 5 array[0].length? 3
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 7
Declaring, Creating, and Initializing Using
Shorthand Notations
You can also use an array initializer to declare, create and
initialize a two-dimensional array. For example,
int[][] array = {
int[][] array = new int[4][3];
{1, 2, 3}, array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
{4, 5, 6}, Same as array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
{7, 8, 9}, array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
{10, 11, 12} array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
};
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 8
Lengths of Two-dimensional
Arrays
int[][] x = new int[3][4];
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 9
Lengths of Two-dimensional
Arrays, cont.
int[][] array = { [Link]
{1, 2, 3}, array[0].length=3
{4, 5, 6}, array[1].length=3
{7, 8, 9}, array[2].length=3
{10, 11, 12} array[3].length=3
};
array[4].length ArrayIndexOutOfBoundsException
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 10
Ragged Arrays
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}, [Link] is 5
{2, 3, 4, 5}, matrix[0].length is 5
{3, 4, 5}, matrix[1].length is 4
matrix[2].length is 3
{4, 5}, matrix[3].length is 2
{5} matrix[4].length is 1
};
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 11
Ragged Arrays, cont.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 12
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)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 13
Initializing arrays with input values
[Link] input = new Scanner([Link]);
[Link]("Enter " + [Link] + " rows and " +
matrix[0].length + " columns: ");
for (int row = 0; row < [Link]; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = [Link]();
}
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 14
Initializing arrays with random values
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 15
Printing arrays
for (int row = 0; row < [Link]; row++) {
for (int column = 0; column < matrix[row].length; column++) {
[Link](" matrix["+row+"]["+column+"]=“+
matrix[row][column] + " ");
}
[Link]();
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 16
Summing all elements
int total = 0;
for (int row = 0; row < [Link]; row++) {
for (int column = 0; column < matrix[row].length; column++) {
total += matrix[row][column];
}
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 17
Summing elements by column
for (int column = 0; column < matrix[0].length; column++) {
int total = 0;
for (int row = 0; row < [Link]; row++)
total += matrix[row][column];
[Link]("Sum for column " + column + " is "
+ total);
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 18
Random shuffling
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
int i1 = (int)([Link]() * [Link]);
int j1 = (int)([Link]() * 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;
}
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 19
Passing Tow-Dimensional Arrays to
Methods
PassTwoDimensionalArray Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 20
Problem: Grading
Multiple-Choice Test
Students’ answer Objective: write a
program that grades
multiple-choice test.
PassTwoDimensionalArray Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 21
Problem: Grading Multiple-Choice Test
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 22
Problem: Finding Two Points
Nearest to Each Other
[Link]
[Link]/dsanimation/Clos
[Link]
PassTwoDimensionalArray Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 23
Problem: Finding Two Points Nearest to Each Other
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 24
Problem: Finding Two Points Nearest to Each Other
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 25
What is Sudoku?
[Link]
m/dsanimation/[Link]
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 26
Every row contains the numbers 1 to 9
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 27
Every column contains the numbers 1 to 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
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 28
Every 3×3 box contains the numbers 1 to 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
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 29
Checking Whether a Solution Is Correct
CheckSudokuSolution Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 30
Sudoku
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 31
Sudoku
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 32
Multidimensional Arrays
Occasionally, you will need to represent
n-dimensional data structures. In Java, you can
create n-dimensional arrays for any integer n.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 33
Multidimensional Arrays
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}}
};
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 34
Multidimensional Arrays
A two-dimensional array consists of an array of one-dimensional arrays.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 35
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 Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 36
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
[Link]. 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.
Weather Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 37
Problem: Guessing Birthday
Listing 4.3, [Link], 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 Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 38
Chapter 18 Recursion
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 1
Motivations
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 2
Motivations
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 3
Objectives
❑ To describe what a recursive method is and the benefits of using recursion
(§18.1).
❑ To develop recursive methods for recursive mathematical functions
(§§18.2–18.3).
❑ To explain how recursive method calls are handled in a call stack (§§18.2–18.3).
❑ To solve problems using recursion (§18.4).
❑ To use an overloaded helper method to derive a recursive method (§18.5).
❑ To implement a selection sort using recursion (§18.5.1).
❑ To implement a binary search using recursion (§18.5.2).
❑ To get the directory size using recursion (§18.6).
❑ To solve the Tower of Hanoi problem using recursion (§18.7).
❑ To draw fractals using recursion (§18.8).
❑ To discover the relationship and difference between recursion and iteration
(§18.9).
❑ To know tail-recursive methods and why they are desirable (§18.10).
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 4
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
n! = n * (n-1)!
0! = 1
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 5
Computing Factorial
class FactorialExample2
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[]){
int i,fact=1;
int number=4;//It is the number to calculate factori
al
fact = factorial(number);
[Link]("Factorial of "+number+" is: "+
fact);
}
} Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 6
animation
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 7
animation
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 8
animation
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 9
animation
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * (2 * factorial(1))
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 10
animation
Computing Factorial
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)))
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 11
animation
Computing Factorial
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)))
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 12
animation
Computing Factorial
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)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 13
animation
Computing Factorial
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
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 14
animation
Computing Factorial
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)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 15
animation
Computing Factorial
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
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 16
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 17
animation
Executes factorial(3)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 18
animation
Executes factorial(2)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 19
animation
Executes factorial(1)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 20
animation
Executes factorial(0)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 21
animation
returns 1
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 22
animation
returns factorial(0)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 23
animation
returns factorial(1)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 24
animation
returns factorial(2)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 25
animation
returns factorial(3)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 26
animation
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 27
factorial(4) Stack Trace
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 28
Other Examples, Fibonacci Numbers
f(0) = 0;
f(n) = f(n-1)+ f(n-2);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 29
Fibonacci Numbers
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
ComputeFibonacci Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 30
Computing Fibonacci Numbers
class Fibonacci{
static int fib(int n){
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return( fib(n-1)+fib(n-2));
}
public static void main(String args[]){
int i,f=1;
int number=4; //It is the index to calculate its
fibonacci
f = fib(number);
[Link]("Fibonacci of"+number+" is: "+f);
} Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 31
Fibonnaci Numbers, cont.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 32
Characteristics of Recursion
All recursive methods have the following characteristics:
– 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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 33
Problem Solving Using Recursion
Let us consider a simple problem of printing a message for
n times. You can break the problem into two subproblems:
one is to print the message one time and the other is to print
the message for n-1 times. The second problem is the same
as the original problem with a smaller size. The base case
for the problem is n==0. You can solve this problem using
recursion as follows:
nPrintln(“Welcome”, 5);
public static void nPrintln(String message, int times) {
if (times >= 1) {
[Link](message);
nPrintln(message, times - 1);
} // The base case is times == 0
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 34
Problem Solving Using Recursion
public class Main {
public static void nPrintln(String message, int times) {
if (times >= 1) {
[Link](message);
nPrintln(message, times - 1);
}
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 35
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 ([Link]() <= 1) // Base case
return true;
else if ([Link](0) != [Link]([Link]() - 1)) // Base case
return false;
else
return isPalindrome([Link](1, [Link]() - 1));
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 36
Recursive Helper Methods
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, [Link]() - 1);
}
public static boolean isPalindrome(String s, int low, int high) {
if (high <= low) // Base case
return true;
else if ([Link](low) != [Link](high)) // Base case
return false;
else
return isPalindrome(s, low + 1, high - 1);
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 37
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
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 38
Recursive Selection Sort
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 39
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
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 40
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 = [Link] - 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;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 42
Directory Size
The size of the directory can be defined recursively as
follows:
DirectorySize Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 43
Tower of Hanoi
▪ 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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 44
Tower of Hanoi, cont.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 45
Solution to Tower of Hanoi
The Tower of Hanoi problem can be decomposed into three
subproblems.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 46
Solution to Tower of Hanoi
❑ 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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 47
Solution to Tower of Hanoi
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 48
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
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 49
Approach 2: Euclid’s algorithm
// Get absolute value of m and n;
t1 = [Link](m); t2 = [Link](n);
// r is the remainder of t1 divided by t2;
r = t1 % t2;
while (r != 0) {
t1 = t2;
t2 = r;
r = t1 % t2;
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 50
Approach 3: Recursive Method
gcd(m, n) = n if m % n = 0;
gcd(m, n) = gcd(n, m % n); otherwise;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 51
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 52
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).
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 53
Sierpinski Triangle Solution
SierpinskiTriangle Run
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 54
Recursion vs. Iteration
Advantage:
Recursion is an alternative form of program
control. It is essentially repetition without a loop.
Disadvantage:
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 55
Advantages of Using Recursion
Recursion is good for solving the problems that are
inherently recursive.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 56
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.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 57
Computing Tail Recursive Factorial
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved. 58