More Related Content
Similar to 02slide_accessible.pptx
Similar to 02slide_accessible.pptx (20)
More from MattMarino13 (20)
02slide_accessible.pptx
- 1. Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 2
Elementary Programming
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
- 2. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations
In the preceding chapter, you learned how to create,
compile, and run a Java program. Starting from this
chapter, you will learn how to solve practical problems
programmatically. Through these problems, you will learn
Java primitive data types and related subjects, such as
variables, constants, data types, operators, expressions,
and input and output.
- 3. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (1 of 2)
2.1 To write Java programs to perform simple computations (§2.2).
2.2 To obtain input from the console using the Scanner class (§2.3).
2.3 To use identifiers to name variables, constants, methods, and classes (§2.4).
2.4 To use variables to store data (§§2.5–2.6).
2.5 To program with assignment statements and assignment expressions (§2.6).
2.6 To use constants to store permanent data (§2.7).
2.7 To name classes, methods, variables, and constants by following their naming
conventions (§2.8).
2.8 To explore Java numeric primitive data types: byte, short, int, long, float, and
double (§2.9).
2.9 To read a byte, short, int, long, float, or double value from the keyboard (§2.9.1).
2.10 To perform operations using operators +, , , , and
* / %
(§2.9.2).
2.11 To perform exponent operations using Math.pow(a, b) (§2.9.3).
2.12 To write integer literals, floating-point literals, and literals in scientific notation (§2.10).
2.13 To use JShell to quickly test Java code (§2.11).
- 4. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (2 of 2)
2.14 To write and evaluate numeric expressions (§2.12).
2.15 To obtain the current system time using System.currentTimeMillis() (§2.13).
2.16 To use augmented assignment operators (§2.14).
2.17 To distinguish between postincrement and preincrement and between
postdecrement and predecrement (§2.15).
2.18 To cast the value of one type to another type (§2.16).
2.19 To describe the software development process and apply it to develop the loan
payment program (§2.17).
2.20 To write a program that converts a large amount of money into smaller units (§2.18).
2.21 To avoid common errors and pitfalls in elementary programming (§2.19).
- 5. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introducing Programming With an
Example
Listing 2.1 Computing the Area of a Circle
This program computes the area of the circle.
ComputeArea Note: Clicking the green button displays
the source code with interactive
animation. You can also run the code in
a browser. Internet connection is
needed for this button.
- 6. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (1 of 5)
- 7. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (2 of 5)
- 8. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (3 of 5)
- 9. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (4 of 5)
- 10. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace a Program Execution (5 of 5)
- 11. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Reading Input From the Console
1. Create a Scanner object
Scanner input = new Scanner(System.in);
2. Use the method nextDouble() to obtain to a double
value. For example,
System.out.print("Enter a double value: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();
ComputeAreaWithConsoleInput ComputeAverage
- 12. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Implicit Import and Explicit Import
java.util.* ; // Implicit import
java.util.Scanner; // Explicit Import
No performance difference
- 13. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Identifiers
• An identifier is a sequence of characters that consist of
letters, digits, underscores (_), and dollar signs ($).
• An identifier must start with a letter, an underscore (_), or
a dollar sign ($). It cannot start with a digit.
• An identifier cannot be a reserved word. (See Appendix
A, “Java Keywords,” for a list of reserved words).
• An identifier cannot be true, false, or null.
• An identifier can be of any length.
- 14. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Variables
// Compute the first area
radius = 1.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ + area + "
for radius "+radius);
// Compute the second area
radius = 2.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ + area + "
for radius "+radius);
- 15. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Declaring Variables
int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;
- 16. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Assignment Statements
x = 1; // Assign 1 to x;
radius = 1.0; // Assign 1.0 to radius;
a = 'A'; // Assign 'A' to a;
- 17. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Declaring and Initializing in One Step
• int x = 1;
• double d = 1.4;
- 18. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Named Constants
final datatype CONSTANTNAME = VALUE;
final double PI = 3.14159;
final int SIZE = 3;
- 19. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Naming Conventions (1 of 2)
• Choose meaningful and descriptive names.
• Variables and method names:
– Use lowercase. If the name consists of several words,
concatenate all in one, use lowercase for the first
word, and capitalize the first letter of each subsequent
word in the name. For example, the variables radius
and area, and the method computeArea.
- 20. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Naming Conventions (2 of 2)
• Class names:
– Capitalize the first letter of each word in the name.
For example, the class name ComputeArea.
• Constants:
– Capitalize all letters in constants, and use
underscores to connect words. For example, the
constant PI and MAX_VALUE
- 21. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Numerical Data Types
Name Range Storage Size
byte
negative 2 to the power 7 to 2 to the power 7 minus 1 left parenthesis negative 128 to 127 right parenthesis.
8-bit signed
short
negative 2 to the power 15 to 2 to the power 15 minus 1 left parenthesis (negative 32768 to 32767 right parenthesis.
16-bit signed
int
negative 2 to the power 31 to 2 to the power 31 minus 1 left parenthesis negative 2147483648 to 2147483647 right parenthesis.
32-bit signed
long negative 2 to the power 63 to 2 to the power 63 minus 1 left parenthesis that is,
negative 9223372036854775808 to 9223372036854775807 right parenthesis.
64-bit signed
float
negative range, negative -3.4028235 E + 38 to negative 1.4 E minus 45, positive range, 1.4 E minus 45 to 3.4028235 E + 38.
32-bit IEEE 754
double
negative range, negative 1.7976931348623157 E + 308 to negative 4.9 E minus 324, positive range, 4.9 E minus 324 to 1.7976931348623157 E + 308.
64-bit IEEE 754
7 7
2 to 2 1 128 to 127
15 15
2 to 2 1 32768 to 32767
31 31
2 to 2 1 2147483648 to 2147483647
63 63
2 to 2 1
i.e., 9223372036854775808 to 9223372036854775807
Negative range:
3.4028235E 38 to 1.4E 45
Positive range:
1.4E 45 to 3.4028235E 38
Negative range:
1.7976931348623157E 308 to 4.9E 324
Positive range:
4.9E 324 to 1.7976931348623157E 308
- 22. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Reading Numbers From the Keyboard
Scanner input = new Scanner(System.in);
int value = input.nextInt();
Method Description
nextByte() reads an integer of the byte type.
nextShort() reads an integer of the short type.
nextInt() reads an integer of the int type.
nextLong() reads an integer of the long type.
nextFloat() reads a number of the float type.
nextDouble() reads a number of the double type.
- 23. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Numeric Operators
Name Meaning Example Result
+ Addition 34 + 1 35
The symbol of minus
Subtraction 34.0 minus 0.1
33.9
* Multiplication 300 times 30
9000
division slash
Division
1.0 divided by 2.0.
0.5
symbol of modulo remainder
Remainder
20 modulo remainder 3
2
34.0 0.1
300 * 30
/ 1.0 / 2.0
% 20 % 3
- 24. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Integer Division
+, ,
*, /, and %
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
5 % 2 yields 1 (the remainder of the division)
- 25. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Remainder Operator
Remainder is very useful in programming. For example, an
even number % 2 is always 0 and an odd number % 2 is
always 1. So you can use this property to determine
whether a number is even or odd. Suppose today is
Saturday and you and your friends are going to meet in 10
days. What day is in 10 days? You can find that day is
Tuesday using the following expression:
- 26. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Displaying Time
Write a program that obtains minutes and remaining
seconds from seconds.
DisplayTime
- 27. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Note
Calculations involving floating-point numbers are
approximated because these numbers are not stored
with complete accuracy. For example,
System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
displays 0.5000000000000001, not 0.5, and
System.out.println(1.0 - 0.9);
displays 0.09999999999999998, not 0.1. Integers are
stored precisely. Therefore, calculations with integers
yield a precise integer result.
- 28. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Exponent Operations
System.out.println(Math.pow(2, 3));
// Displays 8.0
System.out.println(Math.pow(4, 0.5));
// Displays 2.0
System.out.println(Math.pow(2.5, 2));
// Displays 6.25
System.out.println(Math.pow(2.5, -2));
// Displays 0.16
- 29. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Number Literals
A literal is a constant value that appears directly in the
program. For example, 34, 1,000,000, and 5.0 are literals
in the following statements:
int i = 34;
long x = 1000000;
double d = 5.0;
- 30. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Integer Literals
An integer literal can be assigned to an integer variable as
long as it can fit into the variable. A compilation error would
occur if the literal were too large for the variable to hold.
For example, the statement byte b = 1000 would cause a
compilation error, because 1000 cannot be stored in a
variable of the byte type.
An integer literal is assumed to be of the int type, whose
value is between
31 31
2 2147483648 to 2 1 2147483647 .
To denote an integer literal of the long type, append it with
the letter L or l. L is preferred because l (lowercase L) can
easily be confused with 1 (the digit one).
- 31. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Floating-Point Literals
Floating-point literals are written with a decimal point. By
default, a floating-point literal is treated as a double type
value. For example, 5.0 is considered a double value, not a
float value. You can make a number a float by appending
the letter f or F, and make a number a double by appending
the letter d or D. For example, you can use 100.2f or 100.2F
for a float number, and 100.2d or 100.2D for a double
number.
- 32. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
double versus float
The double type values are more accurate than the float
type values. For example,
System.out.println("1.0 / 3.0 is " + 1.0 /
3.0);
displays
16 digits
3
1 0.3333333333 33333
.0 / 3.0 is
System.out.println("1.0F / 3.0F is " + 1.0F
/ 3.0F);
displays
7 digits
0.33333334
1.0 / 3.0 is
F F
- 33. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Scientific Notation
Floating-point literals can also be specified in scientific
notation, for example, 1.23456e+2, same as 1.23456e2, is
equivalent to 123.456, and
1.23456e 2 is equivalent to
0.0123456. E (or e) represents an exponent and it can be
either in lowercase or uppercase.
- 34. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
JShell
JShell is a command line interactive tool introduced in Java
9. JShell enables you to type a single Java statement and
get it executed to see the result right away without having
to write a complete class. This feature is commonly known
as REPL (Read-Evaluate-Print Loop), which evaluates
expressions and executes statements as they are entered
and shows the result immediately.
- 35. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Arithmetic Expressions
10 5
3 4 4 9
9( )
5
y a b c
x x
x x y
is translated to
3 4 * / 5 10 * 5 * / 9 * 4 / 9 /
x y a b c x x x y
- 36. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
How to Evaluate an Expression
Though Java has its own way to evaluate an expression
behind the scene, the result of a Java expression and its
corresponding arithmetic expression are the same.
Therefore, you can safely apply the arithmetic rule for
evaluating a Java expression.
3 + 4 * 4 + 5 * (4 + 3) - 1
3 + 4 * 4 + 5 * 7 – 1
3 + 16 + 5 * 7 – 1
3 + 16 + 35 – 1
19 + 35 – 1
54 - 1
53
(1) inside parentheses
first
(2) multiplication
(3) multiplication
(4) addition
(6) subtraction
(5) addition
- 37. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Converting Temperatures
Write a program that converts a Fahrenheit degree to
Celsius using the formula:
5
32
9
celsius fahrenheit
Note: you have to write
celsius 5.0 / 9 * fahrenheit 32
FahrenheitToCelsius
- 38. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Displaying Current Time
Write a program that displays current time in GMT in the
format hour:minute:second such as 1:45:19.
The currentTimeMillis method in the System class returns
the current time in milliseconds since the midnight, January
1, 1970 GMT. (1970 was the year when the Unix operating
system was formally introduced.) You can use this method
to obtain the current time, and then compute the current
second, minute, and hour as follows.
ShowCurrentTime
- 39. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Augmented Assignment Operators
Operator Name Example Equivalent
+= Addition assignment i += 8 i = i + 8
negative = Subtraction assignment i minus = 8 I = I minus 8
*= Multiplication assignment i *= 8 i = i * 8
forward slash =
Division assignment I forward slash = 8 I = I over 8
%= Remainder assignment i %= 8 i = i % 8
i -= 8 i= i - 8
/ = i / = 8 i= i / 8
- 40. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Increment and Decrement Operators (1 of 3)
Operator Name Description Example (assume i = 1)
++var preincrement Increment var by 1, and use
the new var value in the
statement
int j = ++i;
// j is 2, i is 2
var++ postincrement Increment var by 1, but use
the original var value in the
statement
int j = i++;
// j is 1, i is 2
dash dash variable;
predecrement Decrement var by 1, and use
the new var value in the
statement
int j = --i;
// j is 0, i is 0
variable dash dash;
postdecrement Decrement var by 1, and use
the original var value in the
statement
int j = i--;
// j is 1, i is 0
-- var
var --
- 41. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Increment and Decrement Operators (2 of 3)
int i = 10;
int newNum = 10 * i++; int newNum = 10 * i;
i = i + 1;
Same effect as
int i = 10;
int newNum = 10 * (++i); i = i + 1;
int newNum = 10 * i;
Same effect as
- 42. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Increment and Decrement Operators (3 of 3)
Using increment and decrement operators makes
expressions short, but it also makes them complex and
difficult to read. Avoid using these operators in expressions
that modify multiple variables, or the same variable for
multiple times such as this: int k = ++i + i.
- 43. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Assignment Expressions and
Assignment Statements
Prior to Java 2, all the expressions can be used as
statements. Since Java 2, only the following types of
expressions can be statements:
variable op= expression; // Where op is +, , *, /, or %
++variable;
variable++;
variable;
variable ;
- 44. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Numeric Type Conversion
Consider the following statements:
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
- 45. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Conversion Rules
When performing a binary operation involving two
operands of different types, Java automatically converts the
operand based on the following rules:
1. If one of the operands is double, the other is converted
into double.
2. Otherwise, if one of the operands is float, the other is
converted into float.
3. Otherwise, if one of the operands is long, the other is
converted into long.
4. Otherwise, both operands are converted into int.
- 46. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Type Casting
Implicit casting
double d = 3; (type widening)
Explicit casting
int i = (int)3.0; (type narrowing)
int i = (int)3.9; (Fraction part is truncated)
What is wrong? int x = 5 / 2.0;
byte, short, int, long, float, double
range increases
- 47. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Keeping Two Digits After
Decimal Points
Write a program that displays the sales tax with two digits
after the decimal point.
SalesTax
- 48. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Casting in an Augmented Expression
In Java, an augmented expression of the form x1 op= x2 is
implemented as x1 = (T)(x1 op x2), where T is the type for
x1. Therefore, the following code is correct.
int sum = 0;
sum += 4.5; // sum becomes 4 after this statement
sum += 4.5 is equivalent to sum = (int)(sum + 4.5).
- 49. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Software Development Process
- 50. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Requirement Specification
- 51. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
System Analysis
- 58. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Computing Loan Payments
This program lets the user enter the interest rate, number of
years, and loan amount, and computes monthly payment
and total payment.
12
1
1
1
numberOfYears
loanAmount monthlyInterestRate
monthlyPayment
monthlyInterestRate
ComputeLoan
- 59. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Monetary Units
This program lets the user enter the amount in decimal
representing dollars and cents and output a report listing
the monetary equivalent in single dollars, quarters, dimes,
nickels, and pennies. Your program should report
maximum number of dollars, then the maximum number of
quarters, and so on, in this order.
ComputeChange
- 60. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Common Errors and Pitfalls
• Common Error 1: Undeclared/Uninitialized Variables and
Unused Variables
• Common Error 2: Integer Overflow
• Common Error 3: Round-off Errors
• Common Error 4: Unintended Integer Division
• Common Error 5: Redundant Input Objects
• Common Pitfall 1: Redundant Input Objects
- 61. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Common Error 1: Undeclared/Uninitialized
Variables and Unused Variables
double interestRate = 0.05;
double interest = interestrate * 45;
- 62. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Common Error 2: Integer Overflow
int value = 2147483647 + 1;
// value will actually be 2147483648
- 63. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Common Error 3: Round-off Errors
System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
System.out.println(1.0 - 0.9);
- 64. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Common Error 4: Unintended Integer
Division
int number1 = 1;
int number2 = 2;
double average = (number1 + number2) / 2;
System.out.println(average);
(a)
int number1 = 1;
int number2 = 2;
double average = (number1 + number2) / 2.0;
System.out.println(average);
(b)
- 65. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Common Pitfall 1: Redundant Input
Objects
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int v1 = input.nextInt();
Scanner input1 = new Scanner(System.in);
System.out.print("Enter a double value: ");
double v2 = input1.nextDouble();
- 66. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
- 67. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 3
Selections
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
- 68. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations
If you assigned a negative value for radius in Listing 2.2,
ComputeAreaWithConsoleInput.java, the program would
print an invalid result. If the radius is negative, you don't
want the program to compute the area. How can you deal
with this situation?
- 69. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (1 of 2)
3.1 To declare boolean variables and write Boolean
expressions using relational operators (§3.2).
3.2 To implement selection control using one-way if statements
(§3.3).
3.3 To implement selection control using two-way if-else
statements (§3.4).
3.4 To implement selection control using nested if and multi-
way if statements (§3.5).
3.5 To avoid common errors and pitfalls in if statements (§3.6).
3.6 To generate random numbers using the Math.random()
method (§3.7).
- 70. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (2 of 2)
3.7 To program using selection statements for a variety of
examples (SubtractionQuiz, BMI, ComputeTax) (§§3.7–3.9).
3.8 To combine conditions using logical operators (&&, ||, and !)
(§3.10).
3.9 To program using selection statements with combined
conditions (LeapYear, Lottery) (§§3.11–3.12).
3.10 To implement selection control using switch statements and
expressions (§3.13).
3.11 To write expressions using the conditional expression (§3.14).
3.12 To examine the rules governing operator precedence and
associativity (§3.15).
3.13 To apply common techniques to debug errors (§3.16).
- 71. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The boolean Type and Operators
Often in a program you need to compare two values, such
as whether i is greater than j. Java provides six comparison
operators (also known as relational operators) that can be
used to compare two values. The result of the comparison
is a Boolean value: true or false.
boolean b = (1 > 2);
- 72. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Relational Operators
Java
Operator
Mathematics
Symbol
Name Example
(radius is 5)
Result
< < less than radius < 0 false
<=
Less than or equal to
less than or equal to radius <= 0 false
> > greater than radius > 0 true
>=
Greater than or equal to
greater than or equal to radius >= 0 true
== = equal to radius == 0 false
!=
Not equal to
not equal to radius != 0 true
- 73. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: A Simple Math Learning Tool
This example creates a program to let a first grader
practice additions. The program randomly generates two
single-digit integers number1 and number2 and displays a
question such as “What is 7 + 9?” to the student. After the
student types the answer, the program displays a message
to indicate whether the answer is true or false.
AdditionQuiz
- 74. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
One-Way if Statements
- 75. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Note
if i > 0 {
System.out.println("i is positive");
}
(a) Wrong (b) Correct
if (i > 0) {
System.out.println("i is positive");
}
if (i > 0) {
System.out.println("i is positive");
}
(a)
Equivalent
(b)
if (i > 0)
System.out.println("i is positive");
- 76. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Simple if Demo
Write a program that prompts the user to enter an integer.
If the number is a multiple of 5, print HiFive. If the number
is divisible by 2, print HiEven.
SimpleIfDemo
- 77. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Two-Way if Statement
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
- 78. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
if-else Example
if (radius >= 0) {
area = radius * radius * 3.14159;
System.out.println("The area for the “
+ “circle of radius " + radius +
" is " + area);
}
else {
System.out.println("Negative input");
}
- 79. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Multiple Alternative if Statements
if (score >= 90.0)
System.out.print("A");
else
if (score >= 80.0)
System.out.print("B");
else
if (score >= 70.0)
System.out.print("C");
else
if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
(a)
Equivalent
if (score >= 90.0)
System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
(b)
This is better
- 80. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Multi-Way if-else Statements
- 81. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace if-else Statement (1 of 5)
- 82. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace if-else Statement (2 of 5)
- 83. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace if-else Statement (3 of 5)
- 84. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace if-else Statement (4 of 5)
- 85. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace if-else Statement (5 of 5)
- 86. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Note (1 of 2)
The else clause matches the most recent if clause in the
same block.
- 87. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Note (2 of 2)
Nothing is printed from the preceding statement. To force the else
clause to match the first if clause, you must add a pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
This statement prints B.
- 88. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Common Errors
Adding a semicolon at the end of an if clause is a common mistake.
This mistake is hard to find, because it is not a compilation error or
a runtime error, it is a logic error.
This error often occurs when you use the next-line block style.
- 89. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
TIP
if (number % 2 == 0)
even = true;
else
even = false;
(a)
Equivalent boolean even
= number % 2 == 0;
(b)
- 90. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
CAUTION
if (even == true)
System.out.println(
"It is even.");
(a)
Equivalent if (even)
System.out.println(
"It is even.");
(b)
- 91. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: An Improved Math Learning
Tool
This example creates a program to teach a first grade child
how to learn subtractions. The program randomly
generates two single-digit integers number1 and number2
with number1 >= number2 and displays a question such as
“What is
9 2?” to the student. After the student types the
answer, the program displays whether the answer is correct.
SubtractionQuiz
- 92. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Body Mass Index
Body Mass Index (BMI) is a measure of health on
weight. It can be calculated by taking your weight in
kilograms and dividing by the square of your height in
meters. The interpretation of BMI for people 16 years or
older is as follows:
BMI Interpretation
BMI < 18.5 Underweight
18.5 <= BMI < 25.0 Normal
25.0 <= BMI < 30.0 Overweight
30.0 <= BMI Obese
ComputeAndInterpretBMI
- 93. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Computing Taxes (1 of 2)
The US federal personal income tax is calculated based on
the filing status and taxable income. There are four filing
statuses: single filers, married filing jointly, married filing
separately, and head of household. The tax rates for 2009
are shown below.
Marginal
Tax Rate Single
Married Filing Jointly or
Qualifying Widow(er)
Married Filing
Separately Head of Household
10% $0 - $8,350 $0 - $16,700 $0 - $8,350 $0 - $11,950
15% $8,351 - $33,950 $16,701 - $67,900 $8,351 - $33,950 $11,951 - $45,500
25% $33,951 - $82,250 $67,901 - $137,050 $33,951 - $68,525 $45,501 - $117,450
28% $82,251 - $171,550 $137,051 - $208,850 $68,526 - $104,425 $117,451 - $190,200
33% $171,551 - $372,950 $208,851 - $372,950 $104,426 - $186,475 $190,201 - $372,950
35% $372,951+ $372,951+ $186,476+ $372,951+
- 94. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Computing Taxes (2 of 2)
if (status == 0) {
// Compute tax for single filers
}
else if (status == 1) {
// Compute tax for married file jointly
// or qualifying widow(er)
}
else if (status == 2) {
// Compute tax for married file separately
}
else if (status == 3) {
// Compute tax for head of household
}
else {
// Display wrong status
} ComputeTax
- 95. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Logical Operators
Operator Name Description
! not logical negation
&& and logical conjunction
|| or logical disjunction
^ exclusive or logical exclusion
- 96. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Truth Table for Operator !
p !p Example (assume age = 24, weight = 140)
true false !(age > 18) is false, because (age > 18) is true.
false true !(weight == 150) is true, because (weight == 150) is false.
- 97. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Truth Table for Operator &&
p1 p2 p1 && p2 Example (assume age = 24, weight = 140)
false false false
(age <= 18) && (weight < 140) is false,
because both conditions are both false.
false true false Blank
true false false
(age > 18) && (weight > 140) is false, because
(weight > 140) is false.
true true true
(age > 18) && (weight >= 140) is true, because
both (age > 18) and (weight >= 140) are true.
- 98. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Truth Table for Operator ||
p1 p2 p1 || p2 Example (assume age = 24, weight = 140)
false false false Blank
false true true
(age > 34) || (weight <= 140) is true, because
(age > 34) is false, but (weight <= 140) is true.
true false true
(age > 14) || (weight >= 150) is false, because
(age > 14) is true.
true true true Blank
- 99. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Truth Table for Operator ^
p1 p2 p1 ^ p2 Example (assume age = 24, weight = 140)
false false false
(age > 34) ^ (weight > 140) is true, because
(age > 34) is false and (weight > 140) is false.
false true true
(age > 34) ^ (weight >= 140) is true, because
(age > 34) is false but (weight >= 140) is true.
true false true
(age > 14) ^ (weight > 140) is true, because
(age > 14) is true and (weight > 140) is false.
true true false Blank
- 100. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Examples (1 of 2)
Here is a program that checks whether a number is
divisible by 2 and 3, whether a number is divisible by 2 or
3, and whether a number is divisible by 2 or 3 but not both:
TestBooleanOperators
- 101. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Examples (2 of 2)
System.out.println("Is " + number + " divisible by 2 and 3? " +
((number % 2 == 0) && (number % 3 == 0)));
System.out.println("Is " + number + " divisible by 2 or 3? " +
((number % 2 == 0) || (number % 3 == 0)));
System.out.println("Is " + number +
" divisible by 2 or 3, but not both? " +
((number % 2 == 0) ^ (number % 3 == 0)));
TestBooleanOperators
- 102. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The & and | Operators (1 of 2)
Supplement III.B, “The & and | Operators”
- 103. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The & and | Operators (2 of 2)
If x is 1, what is x after this expression?
(x > 1) & (x++ < 10)
If x is 1, what is x after this expression?
(1 > x) && ( 1 > x++)
How about (1 == x) | (10 > x++)?
(1 == x) || (10 > x++)?
- 104. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Determining Leap Year?
This program first prompts the user to enter a year as an
int value and checks if it is a leap year.
A year is a leap year if it is divisible by 4 but not by 100, or
it is divisible by 400.
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
LeapYear
- 105. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Lottery
Write a program that randomly generates a lottery of a two-
digit number, prompts the user to enter a two-digit number,
and determines whether the user wins according to the
following rule:
• If the user input matches the lottery in exact order, the
award is $10,000.
• If the user input matches the lottery, the award is $3,000.
• If one digit in the user input matches a digit in the lottery,
the award is $1,000.
Lottery
- 106. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
switch Statements
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(1);
}
- 107. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
switch Statement Flow Chart
- 108. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
switch Statement Rules (1 of 2)
- 109. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
switch Statement Rules (2 of 2)
- 110. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace switch Statement (1 of 7)
- 111. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace switch Statement (2 of 7)
- 112. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace switch Statement (3 of 7)
- 113. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace switch Statement (4 of 7)
- 114. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace switch Statement (5 of 7)
- 115. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace switch Statement (6 of 7)
- 116. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace switch Statement (7 of 7)
- 117. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Chinese Zodiac
Write a program that prompts the user to enter a year and
displays the animal for the year.
ChineseZodiac
- 118. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
118
JDK 14 Arrow Operator (->)
Forgetting a break statement when it is needed is a common
error. To avoid this type of errors, JDK 14 introduced a new
arrow operator (->). You can use the arrow operator to replace
the colon operator (:). With the arrow operator, there is no
need to use the break statement. When a case is matched, the
matching statement(s) are executed, and the switch statement
is finished.
int day = 1;
switch (day) {
case 1 -> System.out.print(1 + " ");
case 2 -> System.out.print(2 + " ");
case 3 -> System.out.print(3 + " ");
}
- 119. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
119
JDK 14 switch Expression
Java 14 also introduced switch expressions. A switch expression
returns a value. Here is an example:
int day = 1;
System.out.println(
switch (day) {
case 1 -> 1 + " ";
case 2 -> 2 + " ";
case 3 -> 3 + " ";
default -> " ";
}
);
The switch expression in this example returns a string. A
switch expression must cover all cases, while a switch
statement does not have to cover all cases. In the preceding
example, the default clause is to required to cover the
integers not listed in the cases.
- 120. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
120
JDK 14 switch Combining Cases
In Java 14, the cases can be combined. For example, the
preceding code can be simplified as follows:
int day = 1;
System.out.println(
switch (day) {
case 1, 2, 3 -> day + " ";
default -> " ";
}
);
case 1, 2, 3 means case 1, case 2, or case 3.
- 121. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
121
The yield Keyword
In Java 14, the cases can be combined. For example, the
preceding code can be simplified as follows:
int day = 1;
System.out.println(
switch (day) {
case 1, 2, 3 -> day + " ";
default -> " ";
}
);
case 1, 2, 3 means case 1, case 2, or case 3.
- 122. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
122
The yield Keyword
If the result for a matching case in a switch expression is not a
simple value, you need to use the yield keyword to return the
value. Here is an example,
int year = 2000;
int month = 2;
System.out.println(
switch (month) {
case 2 -> {
if (isLeapYear(year))
yield "29 days";
else
yield "28 days";
}
default -> " ";
}
);
- 123. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Conditional Operators
if (x > 0)
y = 1
else
y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
(boolean-expression) ? expression1 : expression2
Ternary operator
Binary operator
Unary operator
- 124. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Conditional Operator (1 of 2)
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);
System.out.println(
(num % 2 == 0)? num + “is even” :
num + “is odd”);
- 125. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Conditional Operator (2 of 2)
boolean-expression ? exp1 : exp2
- 126. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Operator Precedence
• var++, var--
• +, - (Unary plus and minus), ++var,--var
• (type) Casting
• ! (Not)
• *, /, % (Multiplication, division, and remainder)
• +, - (Binary addition and subtraction)
• <, <=, >, >= (Relational operators)
• ==, !=; (Equality)
• ^ (Exclusive OR)
• && (Conditional AND) Short-circuit AND
• || (Conditional OR) Short-circuit OR
• =, +=, -=, *=, /=, %= (Assignment operator)
- 127. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Operator Precedence and Associativity
The expression in the parentheses is evaluated first.
(Parentheses can be nested, in which case the expression
in the inner parentheses is executed first.) When evaluating
an expression without parentheses, the operators are
applied according to the precedence rule and the
associativity rule.
If operators with the same precedence are next to each
other, their associativity determines the order of evaluation.
All binary operators except assignment operators are left-
associative.
- 128. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Operator Associativity
When two operators with the same precedence are
evaluated, the associativity of the operators determines
the order of evaluation. All binary operators except
assignment operators are left-associative.
a b c d
is equivalent to ((a b) c) d
Assignment operators are right-associative. Therefore,
the expression
a b c 5
is equivalent to a (b (c 5))
- 129. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Example
Applying the operator precedence and associativity rule,
the expression 3 4 * 4 5 * (4 3) 1
is evaluated as
follows:
3 + 4 * 4 > 5 * (4 + 3) - 1
3 + 4 * 4 > 5 * 7 – 1
3 + 16 > 5 * 7 – 1
3 + 16 > 35 – 1
19 > 35 – 1
19 > 34
false
(1) inside parentheses first
(2) multiplication
(3) multiplication
(4) addition
(5) subtraction
(6) greater than
- 130. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Operand Evaluation Order
Supplement III.A, “Advanced discussions on how an
expression is evaluated in the JVM.”
- 131. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Debugging
Logic errors are called bugs. The process of finding and
correcting errors is called debugging. A common approach
to debugging is to use a combination of methods to narrow
down to the part of the program where the bug is located.
You can hand-trace the program (i.e., catch errors by
reading the program), or you can insert print statements in
order to show the values of the variables or the execution
flow of the program. This approach might work for a short,
simple program. But for a large, complex program, the
most effective approach for debugging is to use a debugger
utility.
- 132. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Debugger
Debugger is a program that facilitates debugging. You can
use a debugger to
• Execute a single statement at a time.
• Trace into or stepping over a method.
• Set breakpoints.
• Display variables.
• Display call stack.
• Modify variables.
- 133. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Debugging in NetBeans
Supplement II.E, Learning Java Effectively with NetBeans
- 134. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Debugging in Eclipse
Supplement II.G, Learning Java Effectively with Eclipse
- 135. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
- 136. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 4
Mathematical Functions,
Characters, and Strings
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
- 137. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations
Suppose you need to estimate the area enclosed by four
cities, given the GPS locations (latitude and longitude) of
these cities, as shown in the following diagram. How would
you write a program to solve this problem? You will be able
to write such a program after completing this chapter.
- 138. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (1 of 2)
4.1 To solve mathematics problems by using the methods in the Math class
(§4.2).
4.2 To represent characters using the char type (§4.3).
4.3 To encode characters using ASCII and Unicode (§4.3.1).
4.4 To represent special characters using the escape sequences (§4.4.2).
4.5 To cast a numeric value to a character and cast a character to an integer
(§4.3.3).
4.6 To compare and test characters using the static methods in the Character
class (§4.3.4).
4.7 To introduce objects and instance methods (§4.4).
4.8 To represent strings using the String objects (§4.4).
4.9 To return the string length using the length() method (§4.4.1).
4.10 To return a character in the string using the charAt(i) method (§4.4.2).
4.11 To use the + operator to concatenate strings (§4.4.3).
- 139. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (2 of 2)
4.12 To return an uppercase string or a lowercase string and to trim a string
(§4.4.4).
4.13 To read strings from the console (§4.4.4).
4.14 To read a character from the console (§4.4.5).
4.15 To compare strings using the equals method and the compareTo
methods (§4.4.6).
4.16 To obtain substrings (§4.4.7).
4.17 To find a character or a substring in a string using the indexOf method
(§4.4.8).
4.18 To program using characters and strings (GuessBirthday) (§4.5.1).
4.19 To convert a hexadecimal character to a decimal value (HexDigit2Dec)
(§4.5.2).
4.20 To revise the lottery program using strings (LotteryUsingStrings)
(§4.5.3).
4.21 To format output using the System.out.printf method (§4.6).
4.22 To form multi-line strings using text blocks (§4.7).
- 140. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Mathematical Functions
Java provides many useful methods in the Math class for
performing common mathematical functions.
- 141. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The Math Class
• Class constants:
– PI
– E
• Class methods:
– Trigonometric Methods
– Exponent Methods
– Rounding Methods
– min, max, abs, and random Methods
- 142. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trigonometric Methods
• sin(double a)
• cos(double a)
• tan(double a)
• acos(double a)
• asin(double a)
• atan(double a)
Radians
toRadians(90)
Examples:
Math.sin(0) returns 0.0
Math.sin(Math.PI / 6)
returns 0.5
Math.sin(Math.PI / 2)
returns 1.0
Math.cos(0) returns 1.0
Math.cos(Math.PI / 6)
returns 0.866
Math.cos(Math.PI / 2)
returns 0
- 143. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Exponent Methods
• exp(double a)
Returns e raised to the power of a.
• log(double a)
Returns the natural logarithm of a.
• log10(double a)
Returns the 10-based logarithm of
a.
• pow(double a, double b)
Returns a raised to the power of b.
• sqrt(double a)
Returns the square root of a.
Examples:
Math.exp(1) returns 2.71
Math.log(2.71) returns 1.0
Math.pow(2, 3) returns 8.0
Math.pow(3, 2) returns 9.0
Math.pow(3.5, 2.5) returns
22.91765
Math.sqrt(4) returns 2.0
Math.sqrt(10.5) returns 3.24
- 144. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Rounding Methods
• double ceil(double x)
x rounded up to its nearest integer. This integer is returned as a
double value.
• double floor(double x)
x is rounded down to its nearest integer. This integer is returned as a
double value.
• double rint(double x)
x is rounded to its nearest integer. If x is equally close to two
integers, the even one is returned as a double.
• int round(float x)
Return (int)Math.floor(x+0.5).
• long round(double x)
Return (long)Math.floor(x+0.5).
- 145. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Rounding Methods Examples
Math.ceil(2.1) returns 3.0
Math.ceil(2.0) returns 2.0
Math.ceil(-2.0) returns –2.0
Math.ceil(-2.1) returns -2.0
Math.floor(2.1) returns 2.0
Math.floor(2.0) returns 2.0
Math.floor(-2.0) returns –2.0
Math.floor(-2.1) returns -3.0
Math.rint(2.1) returns 2.0
Math.rint(2.0) returns 2.0
Math.rint(-2.0) returns –2.0
Math.rint(-2.1) returns -2.0
Math.rint(2.5) returns 2.0
Math.rint(-2.5) returns -2.0
Math.round(2.6f) returns 3
Math.round(2.0) returns 2
Math.round(-2.0f) returns -2
Math.round(-2.6) returns -3
- 146. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
min, max, and abs
• max(a, b) and min(a, b)
Returns the maximum or
minimum of two parameters.
• abs(a)
Returns the absolute value of
the parameter.
• random()
Returns a random double value
in the range [0.0, 1.0).
Examples:
Math.max(2, 3) returns 3
Math.max(2.5, 3) returns
3.0
Math.min(2.5, 3.6)
returns 2.5
Math.abs(-2) returns 2
Math.abs(-2.1) returns
2.1
- 147. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The random Method
Generates a random double value greater than or equal to
0.0 and less than 1.0 (0 <= Math.random() < 1.0).
Examples:
(int)(Math.random() * 10)
Returns a random integer
between 0 and 9.
50 + (int)(Math.random() * 50)
Returns a random integer
between 50 and 99.
In general,
a + Math.random() * b
Returns a random number between
a and a + b, excluding a + b.
- 148. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Computing Angles of a
Triangle
A
B
C
a
b
c
A = acos((a * a - b * b - c * c) / (-2 * b * c))
B = acos((b * b - a * a - c * c) / (-2 * a * c))
C = acos((c * c - b * b - a * a) / (-2 * a * b))
x1, y1
x2, y2
x3, y3
Write a program that prompts the user to enter the x- and
y-coordinates of the three corner points in a triangle and
then displays the triangle’s angles.
ComputeAngles
- 149. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Character Data Type
NOTE: The increment and decrement operators can also be
used on char variables to get the next or preceding Unicode
character. For example, the following statements display
character b.
char ch = 'a';
System.out.println(++ch);
- 150. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Unicode Format
Java characters use Unicode, a 16-bit encoding scheme
established by the Unicode Consortium to support the
interchange, processing, and display of written texts in the
world’s diverse languages. Unicode takes two bytes,
preceded by u, expressed in four hexadecimal numbers
that run from 'u0000' to 'uFFFF'. So, Unicode can
represent 65535 + 1 characters.
- 151. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
ASCII Code for Commonly Used
Characters
Characters Code Value in Decimal Unicode Value
'0' to '9' 48 to 57 u0030 to u0039
'A' to 'Z' 65 to 90 u0041 to u005A
'a' to 'z' 97 to 122 u0061 to u007A
- 152. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Escape Sequences for Special
Characters
Escape Sequence Name Unicode Code Decimal Value
b Backspace u0008 8
t Tab u0009 9
n Linefeed u000A 10
f Formfeed u000C 12
r Carriage Return u000D 13
Backslash u005C 92
” Double Quote u0022 34
- 153. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Appendix B: ASCII Character Set (1 of 2)
ASCII Character Set is a subset of the Unicode from u0000 to u007f
TABLE B.1 ASCII Character Set in the Decimal Index
Blank
0 1 2 3 4 5 6 7 8 9
0 nul soh stx etx eot enq ack bel bs ht
1 nl vt ff cr so si dle dcl dc2 dc3
2 dc4 nak syn etb can em sub esc fs gs
3 rs us sp ! “ # $ % & ‘
4 ( ) * + , - . / 0 1
5 2 3 4 5 6 7 8 9 : ;
6 < = > ? @ A B C D E
7 F G H I J K L M N O
8 P Q R S T U V W X Y
9 Z [ ] ^ _ ` a b c
10 d e f g h i j k l m
11 n o p q r s t u v w
12 x y z { | } ~ del
Blank Blank
- 154. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Appendix B: ASCII Character Set (2 of 2)
ASCII Character Set is a subset of the Unicode from u0000 to u007f
TABLE B.2 ASCII Character Set in the Hexadecimal Index
Blank
0 1 2 3 4 5 6 7 8 9 A B C D E F
0 nul soh stx etx eot enq ack bel bs ht nl vt ff cr so si
1 dle dcl dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us
2 sp ! “ # $ % & ‘ ( ) * + , - . /
3 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
4 @ A B C D E F G H I J K L M N O
5 P Q R S T U V W X Y Z [ ] ^ _
6 ‘ a b c d e f g h i j k l m n o
7 p q r s t u v w x y z { | } ~ del
- 155. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Casting between char and Numeric
Types
int i = 'a'; // Same as int i = (int)'a';
char c = 97; // Same as char c = (char)97;
- 156. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Comparing and Testing Characters
if (ch >= 'A' && ch <= 'Z')
System.out.println(ch + " is an uppercase letter");
else if (ch >= 'a' && ch <= 'z')
System.out.println(ch + " is a lowercase letter");
else if (ch >= '0' && ch <= '9')
System.out.println(ch + " is a numeric character");
- 157. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Methods in the Character Class
Method Description
isDigit(ch) Returns true if the specified character is a digit.
isLetter(ch) Returns true if the specified character is a letter.
isLetterOfDigit(ch) Returns true if the specified character is a letter or
digit.
isLowerCase(ch) Returns true if the specified character is a
lowercase letter.
isUpperCase(ch) Returns true if the specified character is an
uppercase letter.
toLowerCase(ch) Returns the lowercase of the specified character.
toUpperCase(ch) Returns the uppercase of the specified character.
- 158. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
The String Type
The char type only represents one character. To represent a string
of characters, use the data type called String. For example,
String message = "Welcome to Java";
String is actually a predefined class in the Java library just like the
System class and Scanner class. The String type is not a primitive
type. It is known as a reference type. Any Java class can be used
as a reference type for a variable. Reference data types will be
thoroughly discussed in Chapter 9, “Objects and Classes.” For the
time being, you just need to know how to declare a String variable,
how to assign a string to the variable, how to concatenate strings,
and to perform simple operations for strings.
- 159. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Simple Methods for String Objects (1 of 2)
Method Description
length() Returns the number of characters in this string.
charAt(index) Returns the character at the specified index from this string.
concat(s1) Returns a new string that concatenates this string with
string s1.
toUpperCase() Returns a new string with all letters in uppercase.
toLowerCase() Returns a new string with all letters in lowercase.
trim() Returns a new string with whitespace characters trimmed
on both sides.
- 160. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Simple Methods for String Objects (2 of 2)
Strings are objects in Java. The methods in the preceding
table can only be invoked from a specific string instance.
For this reason, these methods are called instance
methods. A non-instance method is called a static
method. A static method can be invoked without using an
object. All the methods defined in the Math class are static
methods. They are not tied to a specific object instance.
The syntax to invoke an instance method is
referenceVariable.methodName(arguments).
- 161. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Getting String Length
String message = "Welcome to Java";
System.out.println("The length of " + message + " is "
+ message.length());
- 162. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Getting Characters from a String
String message = "Welcome to Java";
System.out.println("The first character in message is "
+ message.charAt(0));
- 163. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Converting Strings
"Welcome".toLowerCase() returns a new string, welcome.
"Welcome".toUpperCase() returns a new string,
WELCOME.
" Welcome ".trim() returns a new string, Welcome.
- 164. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
String Concatenation
String s3 = s1.concat(s2); or String s3 = s1 + s2;
// Three strings are concatenated
String message = "Welcome " + "to " + "Java";
// String Chapter is concatenated with number 2
String s = "Chapter" + 2; // s becomes Chapter2
// String Supplement is concatenated with character B
String s1 = "Supplement" + 'B'; // s1 becomes SupplementB
- 165. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Reading a String From the Console
Scanner input = new Scanner(System.in);
System.out.print("Enter three words separated by
spaces: ");
String s1 = input.next();
String s2 = input.next();
String s3 = input.next();
System.out.println("s1 is " + s1);
System.out.println("s2 is " + s2);
System.out.println("s3 is " + s3);
- 166. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Reading a Character From the Console
Scanner input = new Scanner(System.in);
System.out.print("Enter a character: ");
String s = input.nextLine();
char ch = s.charAt(0);
System.out.println("The character entered is " + ch);
- 167. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Comparing Strings
Method Description
equals(s1) Returns true if this string is equal to string s1.
equalsIgnoreCase(s1) Returns true if this string is equal to string s1;
it is case insensitive.
compareTo(s1) Returns an integer greater than 0, equal to 0,
or less than 0 to indicate whether this string is
greater than, equal to, or less than s1.
compareToIgnoreCase(s1) Same as compareTo except that the
comparison is case insensitive.
startsWith(prefix) Returns true if this string starts with the
specified prefix.
endsWith(suffix) Returns true if this string ends with the
specified suffix.
OrderTwoCities
- 168. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Obtaining Substrings
Method Description
substring(beginIndex) Returns this string’s substring that begins with the
character at the specified beginIndex and extends to
the end of the string, as shown in Figure 4.2.
substring(beginIndex,
endIndex)
Returns this string’s substring that begins at the specified
beginIndex and extends to the character at index
endIndex – 1, as shown in Figure 9.6. Note that the
character at endIndex is not part of the substring.
- 169. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Finding a Character or a Substring in a
String (1 of 2)
Method Description
indexOf(ch) Returns the index of the first occurrence of ch in the string.
Returns -1 if not matched.
indexOf(ch, fromIndex) Returns the index of the first occurrence of ch after
fromIndex in the string. Returns -1 if not matched.
indexOf(s) Returns the index of the first occurrence of string s in this
string. Returns -1 if not matched.
indexOf(s, fromIndex) Returns the index of the first occurrence of string s in this string
after fromIndex. Returns -1 if not matched.
lastIndexOf(ch) Returns the index of the last occurrence of ch in the string.
Returns -1 if not matched.
lastIndexOf(ch, fromIndex) Returns the index of the last occurrence of ch before
fromIndex in this string. Returns -1 if not matched.
lastIndexOf(s) Returns the index of the last occurrence of string s. Returns -1
if not matched.
lastIndexOf(s, fromIndex) Returns the index of the last occurrence of string s before
fromIndex. Returns -1 if not matched.
- 170. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Finding a Character or a Substring in a
String (2 of 2)
int k = s.indexOf(' ');
String firstName = s.substring(0, k);
String lastName = s.substring(k + 1);
- 171. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Conversion between Strings and
Numbers
int intValue = Integer.parseInt(intString);
double doubleValue = Double.parseDouble(doubleString);
String s = number + "";
- 172. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Guessing Birthday
The program can guess your birth date. Run to see how it
works.
GuessBirthday
- 173. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Mathematics Basis for the Game
19 is 10011 in binary. 7 is 111 in binary. 23 is 11101 in
binary
10000
10
+ 1
10011
00110
10
+ 1
00111
19 7
10000
1000
100
+ 1
11101
23
- 174. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Converting a Hexadecimal
Digit to a Decimal Value
Write a program that converts a hexadecimal digit into a
decimal value.
HexDigit2Dec
- 175. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Revising the Lottery
Program Using Strings
A problem can be solved using many different approaches.
This section rewrites the lottery program in Listing 3.7 using
strings. Using strings simplifies this program.
LotteryUsingStrings
- 176. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Formatting Output
Use the printf statement.
System.out.printf(format, items);
Where format is a string that may consist of substrings and
format specifiers. A format specifier specifies how an item
should be displayed. An item may be a numeric value,
character, boolean value, or a string. Each specifier begins
with a percent sign.
- 177. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Frequently-Used Specifiers
Specifier Output Example
%b a boolean value true or false
%c a character 'a'
%d a decimal integer 200
%f a floating-point number 45.460000
%e a number in standard
scientific notation
4.556000e+01
%s a string "Java is cool"
int count = 5;
double amount = 45.56;
System.out.printf("count is %d and amount is %f", count, amount);
display count is 5 and amount is 45.560000
items
- 178. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
FormatDemo
The example gives a program that uses printf to display a
table.
FormatDemo
- 179. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
179
Text blocks became a standard feature since Java 15. It
enables you to form a multi-line string. Here is an example of a
text block:
String tb = """
Java
Python
C++""";
System.out.println(tb);
The code displays three
lines
Java
Python
C++
A text block contains multiple line. The first line starts with
three double quotation marks (""") followed by space
characters. The last line ends with three double quotation
marks (""").
Text Blocks
- 180. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
180
You can use indentation in a text block. To achieve this, the
compiler first removes the maximum left common space
characters for all lines. For example, the maximum common
left space characters for all lines in the following text block is
2, because there are two leading space characters before
“Java”.
String tb = """
Java
Python
C++""";
After removing two leading space
characters from each line, the resulting
string is
Java
Python
C++
After removing the maximum common left space characters,
the indentation of the text block is preserved.
Indentation in Text Blocks
- 181. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
181
Indentation in Text Blocks: ending """
Note if the ending """ is on a separate line by itself, its
leading spaces are counted in the maximum common left
space. For example, in the following code,
String tb = """
Java
Python
C++
""";
The maximum common left space is 0, because
there are no space before the ending """. The
resulting string will be
Java
Python
C++
- 182. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
182
Right Trailing Space
The right trailing space are trimmed by default. If you want to
keep right trailing space, use s. For example, the following
code keep three right space characters after “Python”.
String tb = """
Java
Python s
C++""";
Note that there are two spaces
after Python and before s.
Including s, there will be three
spaces after “Python”.
- 183. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
183
Escape Characters
You used s escape character for a space. You can also use
other escape characters in needed. For example, for the
following text block:
String tb = """
Java
tPythonn
C++""";
The resulting string is
Java
Python
C++
The space before “Python” is due to the tab character (t). The
space line after “Python” is due to the new line character “n”.
- 184. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
184
""" in Text Block as Literal
If you need to put """ into the text block, you can use """. For
example, for the following text block:
String tb = """
Java"""
Python
C++""";
The resulting string is
Java"""
Python
C++
- 185. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
185
New String Methods
As part of the new feature on text blocks, several new String
methods are introduced. You can use the stripIndent() to
remove the maximum common left space from a multi-line
string in the same way as a text block is processed.
You can use the formatted(args) method to format a string.
For example, for the following code:
String tb = """
Product: %s
Price: $%.2f""".formatted("Salt", 4.52);
The resulting string is
Produce: Salt
Price: $4.52
- 186. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
- 187. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 5
Loops
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
- 188. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Motivations
Suppose that you need to print a string (e.g., "Welcome to
Java!") a hundred times. It would be tedious to have to
write the following statement a hundred times:
System.out.println("Welcome to Java!");
So, how do you solve this problem?
- 189. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Opening Problem
Problem:
- 190. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introducing while Loops
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java");
count++;
}
- 191. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (1 of 2)
5.1 To write programs for executing statements repeatedly
using a while loop (§5.2).
5.2 To write loops for the guessing number problem (§5.3).
5.3 To follow the loop design strategy to develop loops (§5.4).
5.4 To control a loop with a sentinel value (§5.4).
5.5 To obtain large input from a file using input redirection
rather than typing from the keyboard (§5.5).
5.6 To write loops using do-while statements (§5.6).
5.7 To write loops using for statements (§5.7).
- 192. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives (2 of 2)
5.8 To discover the similarities and differences of three types of
loop statements (§5.8).
5.9 To write nested loops (§5.9).
5.10 To learn the techniques for minimizing numerical errors
(§5.10).
5.11 To learn loops from a variety of examples (GCD,
FutureTuition, Dec2Hex) (§5.11).
5.12 To implement program control with break and continue
(§5.12).
5.13 To process characters in a string using a loop in a case
study for checking palindrome (§5.13).
5.14 To write a program that displays prime numbers (§5.14).
- 193. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
while Loop Flow Chart
- 194. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (1 of 9)
- 195. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (2 of 9)
- 196. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (3 of 9)
- 197. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (4 of 9)
- 198. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (5 of 9)
- 199. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (6 of 9)
- 200. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (7 of 9)
- 201. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (8 of 9)
- 202. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace while Loop (9 of 9)
- 203. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Repeat Addition Until Correct
Recall that Listing 3.1 AdditionQuiz.java gives a program
that prompts the user to enter an answer for a question on
addition of two single digits. Using a loop, you can now
rewrite the program to let the user enter a new answer until
it is correct.
RepeatAdditionQuiz
- 204. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Guessing Numbers
Write a program that randomly generates an integer
between 0 and 100, inclusive. The program prompts the
user to enter a number continuously until the number
matches the randomly generated number. For each user
input, the program tells the user whether the input is too
low or too high, so the user can choose the next input
intelligently. Here is a sample run:
GuessNumberOneTime
GuessNumber
- 205. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: An Advanced Math Learning
Tool
The Math subtraction learning tool program generates just
one question for each run. You can use a loop to generate
questions repeatedly. This example gives a program that
generates five questions and reports the number of the
correct answers after a student answers all five questions.
SubtractionQuizLoop
- 206. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Ending a Loop with a Sentinel Value
Often the number of times a loop is executed is not
predetermined. You may use an input value to signify the
end of the loop. Such a value is known as a sentinel
value.
Write a program that reads and calculates the sum of an
unspecified number of integers. The input 0 signifies the
end of the input.
SentinelValue
- 207. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Caution (1 of 3)
Don’t use floating-point values for equality checking in a
loop control. Since floating-point values are approximations
for some values, using them could result in imprecise
counter values and inaccurate results. Consider the
following code for computing 1 + 0.9 + 0.8 + ... + 0.1:
double item = 1; double sum = 0;
while (item != 0) { // No guarantee item will be 0
sum += item;
item −= 0.1;
}
System.out.println(sum);
- 208. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
do-while Loop
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
- 210. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (1 to 10)
- 211. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (2 to 10)
- 212. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (3 to 10)
- 213. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (4 to 10)
- 214. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (5 to 10)
- 215. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (6 to 10)
- 216. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (7 to 10)
- 217. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (8 to 10)
- 218. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (9 to 10)
- 219. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace for Loop (10 to 10)
- 220. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Note (1 of 2)
The initial-action in a for loop can be a list of zero or more
comma-separated expressions. The action-after-each-
iteration in a for loop can be a list of zero or more comma-
separated statements. Therefore, the following two for loops
are correct. They are rarely used in practice, however.
for (int i = 1; i < 100; System.out.println(i++));
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
// Do something
}
- 221. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Note (2 of 2)
If the loop-continuation-condition in a for loop is omitted, it
is implicitly true. Thus the statement given below in (a),
which is an infinite loop, is correct. Nevertheless, it is better
to use the equivalent loop in (b) to avoid confusion:
for ( ; ; ) {
// Do something
}
(a)
Equivalent while (true) {
// Do something
}
(b)
- 222. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Caution (2 of 3)
Adding a semicolon at the end of the for clause before the
loop body is a common mistake, as shown below:
- 223. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Caution (3 of 3)
Similarly, the following loop is also wrong:
In the case of the do loop, the following semicolon is needed to
end the loop.
- 224. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Which Loop to Use?
The three forms of loop statements, while, do-while, and for, are
expressively equivalent; that is, you can write a loop in any of these
three forms. For example, a while loop in (a) in the following figure can
always be converted into the following for loop in (b):
while (loop-continuation-condition) {
// Loop body
}
(a)
Equivalent
(b)
for ( ; loop-continuation-condition; ) {
// Loop body
}
A for loop in (a) in the following figure can generally be converted into
the following while loop in (b) except in certain special cases (see
Review Question 3.19 for one of them):
for (initial-action;
loop-continuation-condition;
action-after-each-iteration) {
// Loop body;
}
(a)
Equivalent
(b)
initial-action;
while (loop-continuation-condition) {
// Loop body;
action-after-each-iteration;
}
- 225. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Recommendations
Use the one that is most intuitive and comfortable for you.
In general, a for loop may be used if the number of
repetitions is known, as, for example, when you need to
print a message 100 times. A while loop may be used if the
number of repetitions is not known, as in the case of
reading the numbers until the input is 0. A do-while loop
can be used to replace a while loop if the loop body has to
be executed before testing the continuation condition.
- 226. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Nested Loops
Problem: Write a program that uses nested for loops to
print a multiplication table.
MultiplicationTable
- 227. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Minimizing Numerical Errors
Numeric errors involving floating-point numbers are
inevitable. This section discusses how to minimize such
errors through an example.
Here is an example that sums a series that starts with 0.01
and ends with 1.0. The numbers in the series will increment
by 0.01, as follows: 0.01 + 0.02 + 0.03 and so on.
TestSum
- 228. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Finding the Greatest Common
Divisor
Problem: Write a program that prompts the user to enter two
positive integers and finds their greatest common divisor.
Solution: Suppose you enter two integers 4 and 2, their
greatest common divisor is 2. Suppose you enter two integers
16 and 24, their greatest common divisor is 8. So, how do you
find the greatest common divisor? Let the two input integers
be n1 and n2. You know number 1 is a common divisor, but it
may not be the greatest commons divisor. So you can check
whether k (for k = 2, 3, 4, and so on) is a common divisor for
n1 and n2, until k is greater than n1 or n2.
GreatestCommonDivisor
- 229. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Predicting the Future Tuition
Problem: Suppose that the tuition for a university is
$10,000 this year and tuition increases 7% every year.
In how many years will the tuition be doubled?
FutureTuition
- 230. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Predicating the Future Tuition
double tuition = 10000; int year = 0 // Year 0
tuition = tuition * 1.07; year++; // Year 1
tuition = tuition * 1.07; year++; // Year 2
tuition = tuition * 1.07; year++; // Year 3
...
- 231. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Converting Decimals to
Hexadecimals
Hexadecimals are often used in computer systems
programming (see Appendix F for an introduction to number
systems). How do you convert a decimal number to a
hexadecimal number? To convert a decimal number d to a
hexadecimal number is to find the hexadecimal digits
1 2 2 1 0
, , , , , , and
n n n
h h h h h h
such that
1 2 2 1 0
1 2 2 1 0
16 16 16 16 16 16
n n n
n n n
d h h h h h h
These hexadecimal digits can be found by successively
dividing d by 16 until the quotient is 0. The remainders are
0 1 2 2 1
, , , , , , and .
n n n
h h h h h h
Dec2Hex
- 232. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Monte Carlo Simulation
The Monte Carlo simulation refers to a technique that uses random
numbers and probability to solve problems. This method has a wide
range of applications in computational mathematics, physics,
chemistry, and finance. This section gives an example of using the
Monto Carlo simulation for estimating .
x
y
1
-1
1
-1
circleArea / squareArea / 4.
can be approximated as
4 * numberOfHits / numberOfTrials
MonteCarloSimulation
- 233. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Using break and continue
Examples for using the break and continue keywords:
• TestBreak.java
TestBreak
• TestContinue.java
TestContinue
- 234. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
break
public class TestBreak {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
sum += number;
if (sum >= 100)
break;
}
System.out.println("The number is " + number);
System.out.println("The sum is " + sum);
}
}
- 235. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
continue
public class TestContinue {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
if (number == 10 || number == 11)
continue;
sum += number;
}
System.out.println("The sum is " + sum);
}
}
- 236. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Guessing Number Problem Revisited
Here is a program for guessing a number. You can rewrite
it using a break statement.
GuessNumberUsingBreak
- 237. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Checking Palindrome
A string is a palindrome if it reads the same forward and backward. The
words “mom,” “dad,” and “noon,” for instance, are all palindromes.
The problem is to write a program that prompts the user to enter a string
and reports whether the string is a palindrome. One solution is to check
whether the first character in the string is the same as the last character.
If so, check whether the second character is the same as the second-to-
last character. This process continues until a mismatch is found or all the
characters in the string are checked, except for the middle character if
the string has an odd number of characters.
String s
low high
a b c d e f g n h g f e d c b a
Palindrome
- 238. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem: Displaying Prime Numbers
Problem: Write a program that displays the first 50 prime
numbers in five lines, each of which contains 10 numbers. An
integer greater than 1 is prime if its only positive divisor is 1 or
itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8,
and 9 are not.
Solution: The problem can be broken into the following tasks:
• For number = 2, 3, 4, 5, 6, ..., test whether the number is
prime.
• Determine whether a given number is prime.
• Count the prime numbers.
• Print each prime number, and print 10 numbers per line.
PrimeNumber
- 239. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Debugging Loops in IDE Tools
Supplements II.C, II.E, and II.G.
- 240. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Copyright
This work is protected by United States copyright laws and is
provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.
- 241. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Introduction to Java Programming and
Data Structures
Thirteenth Edition
Chapter 6
Methods
Copyright © 2024 Pearson Education, Inc. All Rights Reserved
- 242. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Opening Problem
Find the sum of integers from 1 to 10, from 20 to 30, and
from 35 to 45, respectively.
- 243. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem (1 of 2)
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);
sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
System.out.println("Sum from 20 to 30 is " + sum);
sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
System.out.println("Sum from 35 to 45 is " + sum);
- 244. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Problem (2 of 2)
- 245. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Solution
MethodDemo
- 246. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Objectives
6.1 To define methods with formal parameters (§6.2).
6.2 To invoke methods with actual parameters (i.e., arguments) (§6.2).
6.3 To define methods with a return value (§6.3).
6.4 To define methods without a return value (§6.4).
6.5 To pass arguments by value (§6.5).
6.6 To develop reusable code that is modular, easy to read, easy to debug, and
easy to maintain (§6.6).
6.7 To write a method that converts hexadecimals to decimals (§6.7).
6.8 To use method overloading and understand ambiguous overloading (§6.8).
6.9 To determine the scope of variables (§6.9).
6.10 To apply the concept of method abstraction in software development
(§6.10).
6.11 To design and implement methods using stepwise refinement (§6.11).
- 247. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Defining Methods (1 of 2)
A method is a collection of statements that are grouped
together to perform an operation.
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Define a method Invoke a method
int z = max(x, y);
actual parameters
(arguments)
- 248. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Defining Methods (2 of 2)
A method is a collection of statements that are grouped
together to perform an operation.
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
modifier
return value
type
method
name
formal
parameters
return value
method
body
method
header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters
(arguments)
method
signature
- 249. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Method Signature
Method signature is the combination of the method name
and the parameter list.
- 250. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Formal Parameters
The variables defined in the method header are known as
formal parameters.
- 251. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Actual Parameters
When a method is invoked, you pass a value to the parameter.
This value is referred to as actual parameter or argument.
- 252. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Return Value Type
A method may return a value. The returnValueType is the data type of
the value the method returns. If the method does not return a value, the
returnValueType is the keyword void. For example, the
returnValueType in the main method is void.
- 253. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Calling Methods (1 of 2)
Testing the max method
This program demonstrates calling a method max to return
the largest of the int values
TestMax
- 254. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Calling Methods (2 of 2)
pass the value of i
pass the value of j
- 255. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (1 of 10)
- 256. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (2 of 10)
- 257. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (3 of 10)
- 258. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (4 of 10)
- 259. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (5 of 10)
- 260. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (6 of 10)
- 261. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (7 of 10)
- 262. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (8 of 10)
- 263. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (9 of 10)
- 264. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (10 of 10)
- 265. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
CAUTION
A return statement is required for a value-returning method.
The method shown below in (a) is logically correct, but it
has a compilation error because the Java compiler thinks it
possible that this method does not return any value.
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else if (n < 0)
return –1;
}
(a)
Should be
(b)
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else
return –1;
}
To fix this problem, delete if (n < 0) in (a), so that the
compiler will see a return statement to be reached
regardless of how the if statement is evaluated.
- 266. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Reuse Methods from Other Classes
Note: One of the benefits of methods is for reuse. The max
method can be invoked from any class besides TestMax. If
you create a new class Test, you can invoke the max
method using ClassName.methodName (e.g.,
TestMax.max).
- 268. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (1 of 10)
- 269. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (2 of 10)
- 270. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (3 of 10)
- 271. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (4 of 10)
- 272. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (5 of 10)
- 273. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (6 of 10)
- 274. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (7 of 10)
- 275. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (8 of 10)
- 276. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (9 of 10)
- 277. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (10 of 10)
- 278. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
void Method Example
This type of method does not return a value. The method
performs some actions.
TestVoidMethod
TestReturnGradeMethod
- 279. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Passing Parameters
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
Suppose you invoke the method using
nPrintln(“Welcome to Java”, 5);
What is the output?
Suppose you invoke the method using
nPrintln(“Computer Science”, 15);
What is the output?
Can you invoke the method using
nPrintln(15, “Computer Science”);
- 280. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Pass by Value (1 of 3)
This program demonstrates passing values to the methods.
Increment
- 281. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Pass by Value (2 of 3)
Testing Pass by value
This program demonstrates passing values to the methods.
TestPassByValue
- 282. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Pass by Value (3 of 3)
- 283. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Modularizing Code
Methods can be used to reduce redundant coding and
enable code reuse. Methods can also be used to
modularize code and improve the quality of the program.
GreatestCommonDivisorMethod
PrimeNumberMethod
- 284. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Case Study: Converting Hexadecimals to
Decimals
Write a method that converts a hexadecimal number into a
decimal number.
ABCD
A *16 ^3 B *16 ^ 2 C *16 ^1 D *16 ^0
A *16 B *16 C *16 D
10 *16 11 *16 12 *16 13 ?
Hex2Dec
- 285. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Overloading Methods
Overloading the max Method
public static double max(double num1, double
num2) {
if (num1 > num2)
return num1;
else
return num2;
}
TestMethodOverloading
- 286. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Ambiguous Invocation (1 of 2)
Sometimes there may be two or more possible matches for
an invocation of a method, but the compiler cannot
determine the most specific match. This is referred to as
ambiguous invocation. Ambiguous invocation is a
compile error.
- 287. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Ambiguous Invocation (2 of 2)
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1, 2));
}
public static double max(int num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
}
- 288. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Scope of Local Variables (1 of 6)
A local variable: a variable defined inside a method.
Scope: the part of the program where the variable can be
referenced.
The scope of a local variable starts from its declaration and
continues to the end of the block that contains the variable.
A local variable must be declared before it can be used.
- 289. Copyright © 2024 Pearson Education, Inc. All Rights Reserved
Scope of Local Variables (2 of 6)
You can declare a local variable with the same name
multiple times in different non-nesting blocks in a method,
but you cannot declare a local variable twice in nested
blocks.