0% found this document useful (0 votes)
55 views69 pages

Selection and Encapsulation

(1) The document discusses various Java control structures including sequence, selection, loop, subprogram, and asynchronous control. (2) Selection structures like if-else statements allow different code to execute depending on certain conditions. (3) Logical and relational operators are used to form boolean expressions that evaluate to true or false and are used in control structures like if-else statements.

Uploaded by

kkotesh
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views69 pages

Selection and Encapsulation

(1) The document discusses various Java control structures including sequence, selection, loop, subprogram, and asynchronous control. (2) Selection structures like if-else statements allow different code to execute depending on certain conditions. (3) Logical and relational operators are used to form boolean expressions that evaluate to true or false and are used in control structures like if-else statements.

Uploaded by

kkotesh
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 69

Chapter 4

Selection and Encapsulation


1

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.

What are the possibilities. . .

Flow of Control
There are 5 general types of Java control structures:
Sequence (by default)

Selection (also called branch or decision)


Loop (also called repetition or iteration) Subprogram Asynchronous
4

Structures Definitions

A sequence is a series of statements that executes one after another


Selection executes different statements depending on certain conditions Loop repeats statements while certain conditions are met A subprogram breaks the program into smaller units Asynchronous control handles events that originate outside the program, such as button clicks
5

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

...

SUBPROGRAM1 a meaningful collection of SEQUENCE, SELECTION, LOOP, SUBPROGRAM

ASYNCHRONOUS CONTROL

EVENTHANDLER EVENT a subprogram executed when an event occurs

10

Java Primitive Data Types


primitive

integral

boolean

floating point

byte char

short

int

long

float

double

11

boolean Data Type

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

Boolean expression means an expression whose value is true or false


An expression is any valid combination of operators and operands Each expression has a value Use of parentheses is encouraged to make grouping clear Otherwise, use precedence chart to determine order
13

Type,
boolean char byte short

Size(bits), and Range


1 16 8 16 true or false \u0000 to \uFFFF -128 to +127 -32,768 to +32,767

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

Character Sets: ASCII, Unicode

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

Right Digit Left Digit(s)

Partial ASCII Character Set


0 1 2

( 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

Relational operators w/Strings?


Remember that strings are reference types
myString = Today; yourString = Today;

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 = Texas; yourState = Maryland;

EXPRESSION myState.equals(yourState) 0<myState.compareTo(yourState)

VALUE false true

myState.equals(Texas)
0>myState.compareTo(texas)

true
true
23

More String Methods


Method Name toLowerCase Parameter Type none Returns Operation Performed Returns a new identical string, except the characters are all lowercase. Returns a new identical string, except the characters are all uppercase.
24

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

What is the value of each expression?


100 grade
(grade >= 60) (number > 0)

-13 number

27 hour
? ?

(hour >= 0 && hour < 24)


(hour == 12 || hour == 0)

?
?
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

What is the value?


int age, height; age = 25; height = 70;

EXPRESSION

VALUE
? ?
28

!(age < 10) !(height > 60)

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

Write an expression for each

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

Need Precedence Chart


int number; double x;

number != 0 && x < 1 / number

/ < != &&

has highest priority next priority next priority next priority

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

Our Example Revisited


int number; double x;

(number != 0) && (x < 1/ number)


is evaluated first and has value false

Because operator is &&, the entire expression will have value false; do to short-circuiting the right side is not evaluated in Java
38

What can go wrong here?


int average; int total; int counter;
. . . // Calculate total

average = total / counter;

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

if-else control structure Provides two-way selection

true

expression expression

false

statement1A

statement1B

42

Style when using blocks


if(Expression) {
if branch

} 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

What happens if you omit braces?


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;

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

and assign value 5.00 to shipCost


Either way, calculate totalBill

46

These braces cannot be omitted


if (purchase > 100.00) { discountRate = .25; shipCost = 10.00; } else { discountRate = .15; shipCost = 5.00; } totalBill = purchase *(1.0 - discountRate) + shipCost;
47

No braces if branch is a single statement


if (lastInitial <= K)
volume = 1; else volume = 2; System.out.println(Look it up in volume # + volume + of NYC phone book);

48

if is a selection statement
Execute or skip statement?

expression

true

false

statement

49

if (Expression) statement

NOTE: statement can be a single statement, a null statement, or a block


50

Example

If taxCode has value T, increase price by adding taxRate times price to it


if (taxCode == T) price = price + taxRate * price;

51

The statements in an if form


can be any kind of statement, including another selection structure or repetition structure

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

Writing Nested if statements

Given an int variable number, describe it as Positive, Negative, or Zero on System.out.

57

One possible answer


if (number > 0)
System.out.println(Positive); else if (number < 0) System.out.println(Positive); else System.out.println(Zero);

58

In the absence of braces,


an else is always paired with the closest preceding if that doesnt already have an else paired with it

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);

WHY? The compiler ignores indentation


and pairs the else with the second if
60

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

double myNumber; double yourNumber;


. . . if (Math.abs(myNumber - yourNumber) < 0.00001) System.out.println(Close enough!);
62

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

Encapsulated vs. Exposed Implementation


External code

Can be changed without affecting external code Encapsulated

Changes can affect external code

Exposed
65

Reuse of Vehicle Class


Vehicle Class

Vehicle Use Scheduling Program

Vehicle Maintenance Scheduling Program

Vehicle Tax Accounting Program


66

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

You might also like