Answer:
Only the first assignment statement is part of the if statement. Use
braces to group both assignment statements into a block statement.
Comparing Values: Relational Operators
Relational operators compare values
Java
Math Notation
Description
>
>
Greater than
>=
≥
Greater than or equal
<
<
Less than
<=
≤
Less than or equal
==
=
Equal
!=
≠
Not equal
The == denotes equality testing:
a = 5; // Assign 5 to a
if (a == 5) . . . // Test whether a equals 5
Relational operators have lower precedence than arithmetic operators:
amount + fee <= balance
Comparing Floating-Point Numbers
Consider this code:
double r = Math.sqrt(2);
double d = r * r -2;
if (d == 0)
System.out.println("sqrt(2)squared minus 2 is 0");
else
System.out.println("sqrt(2)squared minus 2 is not 0 but " + d);
It prints: sqrt(2)squared minus 2 is not 0 but 4.440892098500626E-16
Comparing Floating-Point Numbers
To avoid roundoff errors, don't use == to compare floating-point
numbers
To compare floating-point numbers test whether they are close enough: |x
- y| ≤ ε
final double EPSILON = 1E-14;
if (Math.abs(x - y) <= EPSILON)
// x is approximately equal to y
ε is a small number such as 10-14
Comparing Strings
To test whether two strings are equal to each other, use equals method:
if (string1.equals(string2)) . . .
Don't use == for strings!
if (string1 == string2) // Not useful
== tests identity, equals tests equal contents
Case insensitive test:
if (string1.equalsIgnoreCase(string2))
Comparing Strings
string1.compareTo(string2) < 0 means: string1 comes before string2 in the dictionary
string1.compareTo(string2) > 0 means: string1 comes after string2 in the dictionary
string1.compareTo(string2) == 0 means: string1 and string2 are equal
"car" comes before "cargo"
All uppercase letters come before lowercase: "Hello" comes before "car"
Lexicographic Comparison
Syntax 5.2 Comparisons
Comparing Objects
== tests for identity, equals for identical content
Rectangle box1 = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box1;
Rectangle box3 = new Rectangle(5, 10, 20, 30);
box1 != box3,
but box1.equals(box3)
box1 == box2
Caveat: equals must be defined for the class
Object Comparison
Testing for null
null reference refers to no object:
String middleInitial = null; // Not set
if ( . . . )
middleInitial = middleName.substring(0, 1);
Which of the following comparisons are syntactically incorrect? Which of them
are syntactically correct, but logically questionable?
String a = "1";
String b = "one";
double x = 1;
double y = 3 * (1.0 / 3);
a == "1"
a == null
a.equals("")
a == b
a == x
x == y
x - y == null
x.equals(y)
Answer:
Syntactically incorrect: e, g, h. Logically questionable: a, d, f.
Multiple Alternatives: Sequences of Comparisons
if (condition1)
statement1;
else if (condition2)
statement2;
. . .
else
statement4;
The first matching condition is executed
Order matters:
if (richter >= 0) // always passes
r = "Generally not felt by people";
else if (richter >= 3.5) // not tested
r = "Felt by many people, no destruction";
. . .
Don't omit else:
if (richter >= 8.0)
r = "Most structures fall";
if (richter >= 7.0) // omitted else--ERROR
r = "Many buildings destroyed"
ch05/quake/Earthquake.java
ch05/quake/EarthquakeRunner.java
Program Run:
Enter a magnitude on the Richter scale: 7.1
Many buildings destroyed
Multiple Alternatives: Nested Branches
Branch inside another branch:
if (condition1)
{
if (condition1a)
statement1a;
else
statement1b;
}
else
statement2;
Tax Schedule
If your filing status is Single
If your filing status is Married
Tax Bracket
Percentage
Tax Bracket
Percentage
$0 . . . $32,000
10%
$0 . . . $64,000
10%
Amount over $32,000
25%
Amount over $64,000
25%
Nested Branches
Compute taxes due, given filing status and income figure:
Branch on the filing status
For each filing status, branch on income level
The two-level decision process is reflected in two levels of if
statements
We say that the income test is nested inside the test for filing status
ch05/tax/TaxReturn.java
ch05/tax/TaxCalculator.java
Program Run:
Please enter your income: 50000
Are you married? (Y/N) N
Tax: 11211.5
Self Check 5.5
The if/else/else statement for the earthquake strength first tested for
higher values, then descended to lower values. Can you reverse that order?
Answer:
Yes, if you also reverse the comparisons:
if (richter < 3.5)
r = "Generally not felt by people";
else if (richter < 4.5)
r = "Felt by many people, no destruction";
else if (richter < 6.0)
r = "Damage to poorly constructed buildings";
.. .
Self Check 5.6
Some people object to higher tax rates for higher incomes, claiming that you
might end up with less money after taxes when you get a raise for working hard.
What is the flaw in this argument?
Answer:
The higher tax rate is only applied on the income in the higher bracket. Suppose
you are single and make $31,900. Should you try to get a $200 raise? Absolutely:
you get to keep 90 percent of the first $100 and 75 percent of the next $100.
Using Boolean Expressions: The boolean Type
George Boole (1815-1864): pioneer in the study of logic
value of expression amount < 1000 is true or false
boolean type: one of true or false
Using Boolean Expressions: Predicate Method
A predicate method returns a boolean value:
public boolean isOverdrawn()
{
return balance < 0; // Returns true or false
}
Use in conditions:
if (harrysChecking.isOverdrawn())
Useful predicate methods in Character class:
isDigit
isLetter
isUpperCase
isLowerCase
if (Character.isUpperCase(ch)) . . .
Useful predicate methods in Scanner class: hasNextInt() and hasNextDouble():
if (in.hasNextInt()) n = in.nextInt();
Using Boolean Expressions: The Boolean Operators
&& and
|| or
! not
if (0 < amount && amount < 1000) . . .
if (input.equals("S") || input.equals("M")) . . .
if (!input.equals("S")) . . .
&& and || Operators
Boolean Operators
Truth Tables
A
B
A && B
true
true
true
true
false
false
false
Any
false
A
B
A || B
true
Any
true
false
true
true
false
false
false
A
! A
true
false
false
true
Using Boolean Variables
private boolean married;
Set to truth value:
married = input.equals("M");
Use in conditions:
if (married) . . . else . . .
if (!married) . . .
Also called flag
It is considered gauche to write a test such as
if (married == true) . . . // Don't
Just use the simpler test
if (married) . . .
Self Check 5.7
When does the statement
system.out.println (x > 0 || x < 0);
print false?
Answer:
When x is zero.
Self Check 5.8
Rewrite the following expression, avoiding the comparison with false:
if (Character.isDigit(ch) == false) . . .
Answer:if (!Character.isDigit(ch)) . . .
Code Coverage
Black-box testing: test functionality without consideration of internal
structure of implementation
White-box testing: take internal structure into account when designing tests
Code coverage: measure of how many parts of a program have been tested
Make sure that each part of your program is exercised at least once by one test
case
E.g., make sure to execute each branch in at least one test case
Include boundary test cases: legal values that lie at the boundary of the set of
acceptable inputs
Tip: write first test cases before program is written completely → gives
insight into what program should do
Self Check 5.9
How many test cases do you need to cover all branches of the getDescription
method of the Earthquake class?
Answer:
7.
Self Check 5.10
Give a boundary test case for the EarthquakeRunner program. What output
do you expect?
Answer:
An input of 0 should yield an output of "Generally not felt by people".
(If the output is "Negative numbers are not allowed", there
is an error in the program.)