Selection and Encapsulation
Selection and Encapsulation
Chapter 4 Topics
Java Control Structures boolean Data Type Using Relational and Logical Operators in Logical Expressions if-else Selection Structure if Selection Structure Nested if Statements Testing and Debugging
2
Flow of Control
means the order in which the computer executes the statements in a program.
Flow of Control
There are 5 general types of Java control structures:
Sequence (by default)
Structures Definitions
SEQUENCE
Statement
Statement
Statement
...
SELECTION (branch)
IF Condition THEN Statement1 ELSE Statement2
Statement1
Statement Condition
Statement2
...
LOOP (repetition)
WHILE Condition DO Statement1
false Condition
...
Statement
SUBPROGRAM(function)
SUBPROGRAM1
...
ASYNCHRONOUS CONTROL
10
integral
boolean
floating point
byte char
short
int
long
float
double
11
Type boolean is a primitive type consisting of just 2 values, the constants true and false
We can declare variables of type boolean
hasFever; // true if has high temperature
isSenior; // true if age is at least 65
boolean
boolean
12
Expressions in Java
Type,
boolean char byte short
int
long
32
64
-2,147,483,648 to +2,147,483,647
-9,233,372,036,854,775,808 to +9,233,372,036,854,775,807
float
double
32
64
+1.4E - 45 to +3.4028235E+38
+4.9E - 324 to +1.7976931348623157E+308
14
Relational Operators
Are used in expressions of form: ExpressionA
temperature B*B - 4.0*A*C one + two two * three number initial
Operator
> >= < <= == !=
ExpressionB
humidity 0.0 0 four 35 Q
15
int
x, y; x = 4; y = 6;
EXPRESSION
x < y x + 2 < y
VALUE
true false
x != y
x + 3 >= y y == x y == x+2
true
true false true
16
Precedence
In an expression with several operators, the operators are executed in their precedence order Operators with the same precedence are executed from left-to-right with rare exceptions explained later
17
Operator Precedence
Highest precedence
() ! unary - unary + ++ -- (pre) * / % + < <= > >= == != && || = ++ --(post)
Lowest precedence
18
ASCII (pronounced ask-key) is a character set in which each character occupies one byte(can represent 256 characters) Unicode is a character set in which each character occupies two bytes(can represent how many characters?) ASCII is a subset of the newer Unicode character set Letters and digits are stored consecutively. Thus A < B, c < d, 1<2, and so on All uppercase letters come before all lowercase 19 letters
( 2 ) 3 * 4 + 5
3
!
, 6
5
#
7
6
$
. 8 /
7
%
8
&
0
1 : ;
3
4 5
6
7 8 9 10 11 12
<
F P Z d n x
=
G Q [ e o y
>
H R \ f p z
?
I S ] g q {
@
J T ^ h r |
A
K U _ I s }
B
L V ` j t ~
C
M W a k u
D
N X b l v
20
E
O Y c m w
myString == yourSring
returns what?
21
String methods
Method Name
equals
Parameter Type
String
Returns
Operation Performed
Tests for equality of string contents. Returns 0 if equal, a positive integer if the string in the parameter comes before the string associated with the method and a negative integer if the parameter comes after it.
22
boolean
compareTo
String
int
String String
myState; yourState;
myState.equals(Texas)
0>myState.compareTo(texas)
true
true
23
String
toUpperCase
none
String
Logical Operators
Java exp.
!p
Logical exp.
NOT p
Meaning
! p is false if p is true ! p is true if p is false p && q is true if both p and q are true. It is false otherwise. p || q is true if either p or q or both are true. It is false otherwise.
25
p && q
p AND q
p || q
p OR q
-13 number
27 hour
? ?
?
?
26
int age; boolean isSenior, hasFever; double temperature; age = 20; temperature = 102.0; isSenior = (age >= 65); // isSenior is ? hasFever = (temperature > 98.6); // hasFever is ?
EXPRESSION
isSenior && hasFever isSenior || hasFever ! isSenior ! hasFever hasFever && (age > 50)
VALUE
? ? ? ? ?
27
EXPRESSION
VALUE
? ?
28
Short-Circuit Evaluation
Java uses short circuit evaluation of logical expressions with operators ! && || this means logical expressions are evaluated left to right and evaluation stops as soon as the final truth value can be determined
29
Short-Circuit Example
int age, height; age = 25; height = 70;
EXPRESSION
(age > 50) && (height > 60)
false
Evaluation can stop now because result of && is only true when both sides are true; it is already determined that the entire expression will be false 30
More Short-Circuiting
int age, height; age = 25; height = 70;
EXPRESSION
(height > 60) || (age > 40) true Evaluation can stop now because result of || is true if one side is true; it is already determined that the entire expression will be true 31
What happens?
int age, weight; age = 25; weight = 145; EXPRESSION (weight < 180) && (age >= 20)
true
Must still be evaluated because truth value of entire expression is not yet known. Why? Result of && is only true if both sides are true 32
What happens?
int age, height; age = 25; height = 70;
EXPRESSION
!(height > 60)||(age > 50) true false Does this part need to be evaluated? 33
taxRate is over 25% and income is less than $20000 temperature is less than or equal to 75 or humidity is less than 70% age is over 21 and age is less than 60 age is 21 or 22
34
Some Answers
(taxRate > .25) && (income < 20000)
(temperature <= 75) || (humidity < .70) (age > 21) && (age < 60) (age == 21) || (age == 22)
35
/ < != &&
What happens if number has value 0? Run Time Error(Division by zero) occurs
36
Short-Circuit Benefits
One Boolean expression can be placed first to guard a potentially unsafe operation in a second Boolean expression
Time is saved in evaluation of complex expressions using operators || and &&
37
Because operator is &&, the entire expression will have value false; do to short-circuiting the right side is not evaluated in Java
38
39
Improved Version
double average, int total; int counter; . . . // calculate total if (counter != 0) { average = (double) total / counter; // cast operator System.out.println(Average is + average); } else System.out.println(None were entered);
40
if-else Statement
if (Expression)
Statement1A
else
Statement1B
NOTE: Statement1A and Statement1B each can be a single statement, a null statement, or a block
41
true
expression expression
false
statement1A
statement1B
42
} else {
} else branch
43
Example
int carDoors, driverAge; float premium, monthlyPayment;
. . .
if ((carDoors == 4) && (driverAge > 24)) { premium = 650.00; System.out.println(Low Risk); } else { premium = 1200.00; System.out.println(High Risk); } monthlyPayment = premium / 12.0 + 5.00;
44
COMPILE ERROR OCCURS The if branch is the single statement following the if
45
Examples
Assign value .25 to discountRate and assign value 10.00 to shipCost if purchase is over 100.00 Otherwise, assign value .15 to discountRate
46
48
if is a selection statement
Execute or skip statement?
expression
true
false
statement
49
if (Expression) statement
Example
51
52
Multiway selection
(also called multiway branching) is a sequence of selection statements, that can be accomplished by using a nested if structure
53
Nested if statements
if (Expression1 ) Statement1 else if (Expression2 ) Statement2
...
else if (ExpressionN ) StatementN else Statement N+1 EXACTLY 1 of these statements will be executed.
54
Nested if statements
Each Expression is evaluated in sequence, until some Expression is found that is true Only the specific Statement following that particular true Expression is executed If no Expression is true, the Statement following the final else is executed
Actually, the final else and final Statement are optional. If omitted, and no Expression is true, then no Statement is executed
AN EXAMPLE 55 ...
Example
if (creditsEarned >= 90) System.out.println(Senior Status);
else if (creditsEarned >= 60) System.out.println(Junior Status); else if (creditsEarned >= 30) System.out.println(Sophomore Status); else System.out.println(Freshman Status);
56
57
58
59
Output is FAIL!!??
double average;
average = 100.0; if (average >= 60.0) if (average < 70.0) System.out.println(Marginal PASS); else System.out.println(FAIL);
Corrected Version
double average; average = 100.0; if (average >= 60.0)
{
if(average < 70.0) System.out.println(Marginal PASS);
} else System.out.println(FAIL);
61
Floating-point values
Do not compare floating-point values for equality Instead, compare them for near-equality
Encapsulation
Class implementation details are hidden from the programmer who uses the class. This is called encapsulation Public methods of a class provide the interface between the application code and the class objects
programmers application code class implementation details
63
Benefits of encapsulation
Protects class contents from being damaged by external code Simplifies the design of large programs by developing parts in isolation from each other Allows modifiability of the class implementation after its initial development
Allows reuse of a class in other applications, and extension of the class to form new related classes
64
Exposed
65
Abstraction
Data abstraction is the separation of the logical representation of an objects range of values from their implementation Control abstraction is the separation of the logical properties of the operations on an object from their implementation
class logical representation and properties class implementation details
67
Testing Vocabulary
Walk-through A verification method in which a team performs a manual simulation of the code or design Inspection A verification method in which one member of a team reads the code or design line by line and the other team members point out errors Execution trace Going through the code with actual values, recording the state of the variables 68
Vocabulary Continued
Test plan A document that specifies how an application is to be tested Test plan implementation Using the test cases specified in a test plan to verify that an application outputs the predicted results
69