SlideShare a Scribd company logo
1 of 52
Chapter 6
Control Statements Continued
Fundamentals of Java
Fundamentals of Java
2
Objectives
 Construct complex Boolean expressions
using the logical operators && (AND), ||
(OR), and ! (NOT).
 Construct truth tables for Boolean
expressions.
 Understand the logic of nested if
statements and extended if statements.
Fundamentals of Java
3
Objectives (cont.)
 Test if statements in a comprehensive
manner.
 Construct nested loops.
 Create appropriate test cases for if
statements and loops.
 Understand the purpose of assertions,
invariants, and loop verification.
Fundamentals of Java
4
Vocabulary
 Arithmetic overflow
 Boundary condition
 Combinatorial explosion
 Complete code coverage
 Equivalence class
 Extended if statement
Fundamentals of Java
5
Vocabulary (cont.)
 Extreme condition
 Input assertion
 Logical operator
 Loop invariant
 Loop variant
 Nested if statement
Fundamentals of Java
6
Vocabulary (cont.)
 Nested loop
 Output assertion
 Quality assurance
 Robust
 Truth table
Fundamentals of Java
7
Logical Operators
 Used in Boolean expressions that control the
behavior of if, while, and for statements
 Three logical operators:
– AND
– OR
– NOT
 Can combine smaller logical expressions into
larger ones
Fundamentals of Java
8
Logical Operators (cont.)
 Truth tables: For complex logical
expressions, shows how value of overall
condition depends on values of operands
– All combinations of values considered
– 2n combinations of true and false for n operands
Fundamentals of Java
9
Logical Operators (cont.)
Table 6-1: Truth tables for three example sentences
Fundamentals of Java
10
Logical Operators (cont.)
Table 6-2: General rules for AND, OR, and NOT
Fundamentals of Java
11
Logical Operators (cont.)
 Can use parentheses with complex
expressions
– If (the sun is shining AND it is 8 a.m.) OR (NOT
your brother is visiting) then let’s go for a walk
else let’s stay at home.
– If the sun is shining AND (it is 8 a.m. OR (NOT
your brother is visiting)) then let’s go for a walk
else let’s stay at home.
 Truth tables would clarify these statements.
Fundamentals of Java
12
Logical Operators (cont.)
 Java’s logical operators:
– AND: &&
– OR: ||
– NOT: !
 Precedence rules:
– ! has same precedence as other unary operators.
– && and || only have higher precedence than the
assignment operators.
 && has higher precedence than ||.
Fundamentals of Java
13
Logical Operators (cont.)
 Example:
Fundamentals of Java
14
Logical Operators (cont.)
 Boolean variables: Can have value of true
or false
– Primitive data type
– Example:
 boolean b1 = true;
if ( b1 ) {
<do something>
}
Fundamentals of Java
15
Logical Operators (cont.)
 Can break down complex Boolean expressions
into a series of simpler ones
 Useful equivalences:
– !(p || q)  !p && !q
– !(p && q) !p || !q
– p || (q && r) (p || q) && (p || r)
– p && (q || r)  (p && q) || (p && r)
Fundamentals of Java
16
Logical Operators (cont.)
 Short-circuit evaluation: JVM may know
result of a Boolean expression before
evaluating all of its parts.
– Stops evaluation as soon as result is known
– Example:
 if( true || false )
 Entire condition is true because first operand of
the Boolean expression is true.
– Second operand not examined at all
Fundamentals of Java
17
Testing if Statements
 Quality assurance: Ongoing process of
making sure that a software product is
developed to the highest standards possible
– Subject to the constraints of time and money
 Test data should try to achieve complete
code coverage.
– Every line in a program executed at least once
Fundamentals of Java
18
Testing if Statements (cont.)
 All sets of test data that exercise a program
in the same manner belong to same
equivalence class.
– Test same paths through the program
 Test data should include cases that assess
program’s behavior under boundary
conditions.
– On or near boundaries between equivalence
classes
Fundamentals of Java
19
Testing if Statements (cont.)
 Test under extreme conditions
– With data at the limits of validity
 Test data validation rules
– Enter values that are valid and invalid.
– Test boundary values between the two.
Fundamentals of Java
20
Nested if Statements
 Placing if statements within other if
statements
 Alternative to using logical operators
Fundamentals of Java
21
Nested if Statements (cont.)
Table 6-6: Truth table for reading a book,
watching TV, or going for a walk
 A nested if statement can be translated to
an equivalent if statement that uses logical
operators.
– The reverse is also true.
Fundamentals of Java
22
Nested if Statements (cont.)
Figure 6-4: Flowchart for reading a book,
watching TV, or going for a walk
Fundamentals of Java
23
Nested if Statements (cont.)
 Example:
Fundamentals of Java
24
Nested if Statements (cont.)
 Extended if statement:
Fundamentals of Java
25
Logical Errors in Nested
if Statements
 Misplaced braces example:
Fundamentals of Java
26
Logical Errors in Nested
if Statements (Cont.)
Table 6-7: Truth table for version 1 and version 2
Fundamentals of Java
27
Logical Errors in Nested
if Statements (cont.)
 If braces removed, Java pairs the else
with closest preceding if.
– Can create logic or syntax errors if not
careful
– Can you spot the error in the following code?
Fundamentals of Java
28
Logical Errors in Nested
if Statements (cont.)
 Better to over-use braces than under-use
 Order of conditions often important in
extended if-else constructs
– Can you spot the logic error?
Fundamentals of Java
29
Logical Errors in Nested
if Statements (cont.)
 Avoiding nested if statements can improve
clarity, as in:
if (90 <= average ) grade is A;
if (80 <= average && average < 90) grade is B;
if (70 <= average && average < 80) grade is C;
if (60 <= average && average < 70) grade is D;
if ( average < 60) grade is F;
Fundamentals of Java
30
Nested Loops
 A loop within another loop
 Example:
Fundamentals of Java
31
Testing Loops
 Loops increase difficulty of testing.
– Often do not iterate some fixed number of times
– Design test data to cover situation where loop
iterates:
 Zero times
 One time
 Multiple times
Fundamentals of Java
32
Testing Loops (cont.)
Table 6-10: Test data for the count divisors program
Fundamentals of Java
33
Testing Loops (cont.)
 Combinatorial Explosion: Creating test
data to verify multiple dependant
components can result in huge amount of
test data.
– Example:
 3 dependent components, each of which requires
5 tests to verify functionality
 Total number of tests to verify entire program is
5*5*5=125.
Fundamentals of Java
34
Testing Loops (cont.)
 Robust program: Tolerates errors in user
inputs and recovers gracefully
 Best and easiest way to write robust
programs is to check user inputs immediately
on entry.
– Reject invalid user inputs.
Fundamentals of Java
35
Loop Verification
 Process of guaranteeing that a loop performs
its intended task
– Independently of testing
 assert statement: Allows programmer to
evaluate a Boolean expression and halt the
program with an error message if the
expression’s value is false
– General form:
 assert <Boolean expression>
Fundamentals of Java
36
Loop Verification (cont.)
 To enable when running the program:
– java -enableassertions AJavaProgram
Example 6.1: Assert that x != 0
Fundamentals of Java
37
Loop Verification (cont.)
Figure 6-6: Failure of an assert statement
Fundamentals of Java
38
Loop Verification: Assertions
with Loops
 Input assertions: State what can be
expected to be true before a loop is entered
 Output assertions: State what can be
expected to be true when the loop is exited
Table 6-12: Sums of the proper divisors of some integers
Fundamentals of Java
39
Loop Verification: Assertions
with Loops (cont.)
 Sum proper divisors of positive integer:
 Input assertions:
– num is a positive integer
– divisorSum == 0
 Output assertion:
– divisorSum is sum of all proper divisors of num
Fundamentals of Java
40
Loop Verification: Invariant and
Variant Assertions
 Loop invariant: Assertion that expresses a
relationship between variables that remains
constant throughout all loop iterations
 Loop variant: Assertion whose truth
changes between the first and final iteration
– Stated so that it guarantees the loop is exited
 Usually occur in pairs
Fundamentals of Java
41
Loop Verification: Invariant and
Variant Assertions (cont.)
Fundamentals of Java
42
Graphics and GUIs: Timers
and Animations
 In animation, slightly different frames are
displayed in order at a rapid rate.
– Produces illusion of continuous movement
 Moving objects have:
– Velocity
 Distance (in pixels) traveled in a given unit of
time
– Direction
Fundamentals of Java
43
Graphics and GUIs: Timers
and Animations (cont.)
Figure 6-7: Representing directions in two dimensions
Fundamentals of Java
44
Graphics and GUIs: Timers
and Animations (cont.)
 Algorithm for animating a graphical object:
 Java provides a timer object to schedule
events at regular intervals.
Fundamentals of Java
45
Graphics and GUIs: Timers
and Animations (cont.)
 Timer for animations is an instance of the
class Timer.
Fundamentals of Java
46
Graphics and GUIs: Timers
and Animations (cont.)
Table 6-15: Some commonly used Timer methods
Fundamentals of Java
47
Design, Testing, and Debugging
Hints
 Most errors involving selection statements
and loops are not syntax errors caught at
compile time.
 The presence or absence of braces can
seriously affect the logic of a selection
statement or loop.
Fundamentals of Java
48
Design, Testing, and Debugging
Hints (cont.)
 When testing programs with if or if-else
statements, use data that force the program
to exercise all logical branches.
 When testing programs with if statements,
formulate equivalence classes, boundary
conditions, and extreme conditions.
 Use an if-else statement rather than two
if statements when the alternative courses
of action are mutually exclusive.
Fundamentals of Java
49
Design, Testing, and Debugging
Hints (cont.)
 When testing a loop, use limit values as well
as typical values.
 Check entry and exit conditions for each loop.
 For a loop with errors, use debugging output
statements to verify the control variable’s
value on each pass through the loop.
– Check value before the loop is initially entered,
after each update, and after the loop is exited.
Fundamentals of Java
50
Summary
 A complex Boolean expression contains one
or more Boolean expressions and the logical
operators && (AND), || (OR), and ! (NOT).
 A truth table can determine the value of any
complex Boolean expression.
 Java uses short-circuit evaluation of complex
Boolean expressions.
Fundamentals of Java
51
Summary (cont.)
 Nested if statements are another way of
expressing complex conditions.
 A nested if statement can be translated to
an equivalent if statement that uses logical
operators.
 An extended or multiway if statement
expresses a choice among several mutually
exclusive alternatives.
Fundamentals of Java
52
Summary (cont.)
 Loops can be nested in other loops.
 Equivalence classes, boundary conditions,
and extreme conditions are important
features used in tests of control structures
involving complex conditions.
 Loops can be verified to be correct by using
assertions, loop variants, and loop invariants.

More Related Content

What's hot

Chapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of JavaChapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of Java
Adan Hubahib
 
9781111530532 ppt ch08
9781111530532 ppt ch089781111530532 ppt ch08
9781111530532 ppt ch08
Terry Yoast
 
9781439035665 ppt ch07
9781439035665 ppt ch079781439035665 ppt ch07
9781439035665 ppt ch07
Terry Yoast
 
9781111530532 ppt ch03
9781111530532 ppt ch039781111530532 ppt ch03
9781111530532 ppt ch03
Terry Yoast
 
9781111530532 ppt ch09
9781111530532 ppt ch099781111530532 ppt ch09
9781111530532 ppt ch09
Terry Yoast
 
Chapter 13 - Recursion
Chapter 13 - RecursionChapter 13 - Recursion
Chapter 13 - Recursion
Adan Hubahib
 
9781111530532 ppt ch04
9781111530532 ppt ch049781111530532 ppt ch04
9781111530532 ppt ch04
Terry Yoast
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
Terry Yoast
 
9781111530532 ppt ch12
9781111530532 ppt ch129781111530532 ppt ch12
9781111530532 ppt ch12
Terry Yoast
 
9781111530532 ppt ch05
9781111530532 ppt ch059781111530532 ppt ch05
9781111530532 ppt ch05
Terry Yoast
 
9781111530532 ppt ch06
9781111530532 ppt ch069781111530532 ppt ch06
9781111530532 ppt ch06
Terry Yoast
 
9781111530532 ppt ch07
9781111530532 ppt ch079781111530532 ppt ch07
9781111530532 ppt ch07
Terry Yoast
 

What's hot (17)

Ppt chapter07
Ppt chapter07Ppt chapter07
Ppt chapter07
 
Ppt chapter02
Ppt chapter02Ppt chapter02
Ppt chapter02
 
Ppt chapter08
Ppt chapter08Ppt chapter08
Ppt chapter08
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
 
Chapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of JavaChapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of Java
 
9781111530532 ppt ch08
9781111530532 ppt ch089781111530532 ppt ch08
9781111530532 ppt ch08
 
9781439035665 ppt ch07
9781439035665 ppt ch079781439035665 ppt ch07
9781439035665 ppt ch07
 
9781111530532 ppt ch03
9781111530532 ppt ch039781111530532 ppt ch03
9781111530532 ppt ch03
 
Abap object-oriented-programming-tutorials
Abap object-oriented-programming-tutorialsAbap object-oriented-programming-tutorials
Abap object-oriented-programming-tutorials
 
9781111530532 ppt ch09
9781111530532 ppt ch099781111530532 ppt ch09
9781111530532 ppt ch09
 
Chapter 13 - Recursion
Chapter 13 - RecursionChapter 13 - Recursion
Chapter 13 - Recursion
 
9781111530532 ppt ch04
9781111530532 ppt ch049781111530532 ppt ch04
9781111530532 ppt ch04
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
 
9781111530532 ppt ch12
9781111530532 ppt ch129781111530532 ppt ch12
9781111530532 ppt ch12
 
9781111530532 ppt ch05
9781111530532 ppt ch059781111530532 ppt ch05
9781111530532 ppt ch05
 
9781111530532 ppt ch06
9781111530532 ppt ch069781111530532 ppt ch06
9781111530532 ppt ch06
 
9781111530532 ppt ch07
9781111530532 ppt ch079781111530532 ppt ch07
9781111530532 ppt ch07
 

Similar to Ppt chapter06

9781111530532 ppt ch04
9781111530532 ppt ch049781111530532 ppt ch04
9781111530532 ppt ch04
Terry Yoast
 
9781111530532 ppt ch05
9781111530532 ppt ch059781111530532 ppt ch05
9781111530532 ppt ch05
Terry Yoast
 
Ap Power Point Chpt3
Ap Power Point Chpt3Ap Power Point Chpt3
Ap Power Point Chpt3
dplunkett
 

Similar to Ppt chapter06 (20)

Ppt chapter04
Ppt chapter04Ppt chapter04
Ppt chapter04
 
Android Application Development - Level 3
Android Application Development - Level 3Android Application Development - Level 3
Android Application Development - Level 3
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
 
Quality Assurance
Quality AssuranceQuality Assurance
Quality Assurance
 
9781111530532 ppt ch04
9781111530532 ppt ch049781111530532 ppt ch04
9781111530532 ppt ch04
 
9781111530532 ppt ch05
9781111530532 ppt ch059781111530532 ppt ch05
9781111530532 ppt ch05
 
Java 8
Java 8Java 8
Java 8
 
Ap Power Point Chpt3
Ap Power Point Chpt3Ap Power Point Chpt3
Ap Power Point Chpt3
 
slides03.ppt
slides03.pptslides03.ppt
slides03.ppt
 
Chapter3
Chapter3Chapter3
Chapter3
 
Hello java
Hello java  Hello java
Hello java
 
Hello java
Hello java   Hello java
Hello java
 
Hello Java-First Level
Hello Java-First LevelHello Java-First Level
Hello Java-First Level
 
TDD Training
TDD TrainingTDD Training
TDD Training
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Cancer genomics big_datascience_meetup_july_14_2014
Cancer genomics big_datascience_meetup_july_14_2014Cancer genomics big_datascience_meetup_july_14_2014
Cancer genomics big_datascience_meetup_july_14_2014
 
Javascript
JavascriptJavascript
Javascript
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 
Core java
Core javaCore java
Core java
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 

More from Richard Styner

More from Richard Styner (14)

OneNote for Students.pptx
OneNote for Students.pptxOneNote for Students.pptx
OneNote for Students.pptx
 
Hopscotch.docx
Hopscotch.docxHopscotch.docx
Hopscotch.docx
 
Lit Review + Case Study (1).docx
Lit Review + Case Study (1).docxLit Review + Case Study (1).docx
Lit Review + Case Study (1).docx
 
udlspace.docx
udlspace.docxudlspace.docx
udlspace.docx
 
Documentary Video UDL Lesson.docx
Documentary Video UDL Lesson.docxDocumentary Video UDL Lesson.docx
Documentary Video UDL Lesson.docx
 
rubric.docx
rubric.docxrubric.docx
rubric.docx
 
Ppt chapter03
Ppt chapter03Ppt chapter03
Ppt chapter03
 
Ppt chapter01
Ppt chapter01Ppt chapter01
Ppt chapter01
 
Richard Styner Issues and trends
Richard Styner Issues and trendsRichard Styner Issues and trends
Richard Styner Issues and trends
 
Ppt chapter 01
Ppt chapter 01Ppt chapter 01
Ppt chapter 01
 
Tech mentoring project presentation
Tech mentoring project presentationTech mentoring project presentation
Tech mentoring project presentation
 
The Photoshop Effect
The Photoshop EffectThe Photoshop Effect
The Photoshop Effect
 
Stanford Solar Center Joint Curriculum
Stanford Solar Center Joint CurriculumStanford Solar Center Joint Curriculum
Stanford Solar Center Joint Curriculum
 
The Stanford Solar Lab
The Stanford Solar Lab The Stanford Solar Lab
The Stanford Solar Lab
 

Recently uploaded

Recently uploaded (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 

Ppt chapter06

  • 1. Chapter 6 Control Statements Continued Fundamentals of Java
  • 2. Fundamentals of Java 2 Objectives  Construct complex Boolean expressions using the logical operators && (AND), || (OR), and ! (NOT).  Construct truth tables for Boolean expressions.  Understand the logic of nested if statements and extended if statements.
  • 3. Fundamentals of Java 3 Objectives (cont.)  Test if statements in a comprehensive manner.  Construct nested loops.  Create appropriate test cases for if statements and loops.  Understand the purpose of assertions, invariants, and loop verification.
  • 4. Fundamentals of Java 4 Vocabulary  Arithmetic overflow  Boundary condition  Combinatorial explosion  Complete code coverage  Equivalence class  Extended if statement
  • 5. Fundamentals of Java 5 Vocabulary (cont.)  Extreme condition  Input assertion  Logical operator  Loop invariant  Loop variant  Nested if statement
  • 6. Fundamentals of Java 6 Vocabulary (cont.)  Nested loop  Output assertion  Quality assurance  Robust  Truth table
  • 7. Fundamentals of Java 7 Logical Operators  Used in Boolean expressions that control the behavior of if, while, and for statements  Three logical operators: – AND – OR – NOT  Can combine smaller logical expressions into larger ones
  • 8. Fundamentals of Java 8 Logical Operators (cont.)  Truth tables: For complex logical expressions, shows how value of overall condition depends on values of operands – All combinations of values considered – 2n combinations of true and false for n operands
  • 9. Fundamentals of Java 9 Logical Operators (cont.) Table 6-1: Truth tables for three example sentences
  • 10. Fundamentals of Java 10 Logical Operators (cont.) Table 6-2: General rules for AND, OR, and NOT
  • 11. Fundamentals of Java 11 Logical Operators (cont.)  Can use parentheses with complex expressions – If (the sun is shining AND it is 8 a.m.) OR (NOT your brother is visiting) then let’s go for a walk else let’s stay at home. – If the sun is shining AND (it is 8 a.m. OR (NOT your brother is visiting)) then let’s go for a walk else let’s stay at home.  Truth tables would clarify these statements.
  • 12. Fundamentals of Java 12 Logical Operators (cont.)  Java’s logical operators: – AND: && – OR: || – NOT: !  Precedence rules: – ! has same precedence as other unary operators. – && and || only have higher precedence than the assignment operators.  && has higher precedence than ||.
  • 13. Fundamentals of Java 13 Logical Operators (cont.)  Example:
  • 14. Fundamentals of Java 14 Logical Operators (cont.)  Boolean variables: Can have value of true or false – Primitive data type – Example:  boolean b1 = true; if ( b1 ) { <do something> }
  • 15. Fundamentals of Java 15 Logical Operators (cont.)  Can break down complex Boolean expressions into a series of simpler ones  Useful equivalences: – !(p || q)  !p && !q – !(p && q) !p || !q – p || (q && r) (p || q) && (p || r) – p && (q || r)  (p && q) || (p && r)
  • 16. Fundamentals of Java 16 Logical Operators (cont.)  Short-circuit evaluation: JVM may know result of a Boolean expression before evaluating all of its parts. – Stops evaluation as soon as result is known – Example:  if( true || false )  Entire condition is true because first operand of the Boolean expression is true. – Second operand not examined at all
  • 17. Fundamentals of Java 17 Testing if Statements  Quality assurance: Ongoing process of making sure that a software product is developed to the highest standards possible – Subject to the constraints of time and money  Test data should try to achieve complete code coverage. – Every line in a program executed at least once
  • 18. Fundamentals of Java 18 Testing if Statements (cont.)  All sets of test data that exercise a program in the same manner belong to same equivalence class. – Test same paths through the program  Test data should include cases that assess program’s behavior under boundary conditions. – On or near boundaries between equivalence classes
  • 19. Fundamentals of Java 19 Testing if Statements (cont.)  Test under extreme conditions – With data at the limits of validity  Test data validation rules – Enter values that are valid and invalid. – Test boundary values between the two.
  • 20. Fundamentals of Java 20 Nested if Statements  Placing if statements within other if statements  Alternative to using logical operators
  • 21. Fundamentals of Java 21 Nested if Statements (cont.) Table 6-6: Truth table for reading a book, watching TV, or going for a walk  A nested if statement can be translated to an equivalent if statement that uses logical operators. – The reverse is also true.
  • 22. Fundamentals of Java 22 Nested if Statements (cont.) Figure 6-4: Flowchart for reading a book, watching TV, or going for a walk
  • 23. Fundamentals of Java 23 Nested if Statements (cont.)  Example:
  • 24. Fundamentals of Java 24 Nested if Statements (cont.)  Extended if statement:
  • 25. Fundamentals of Java 25 Logical Errors in Nested if Statements  Misplaced braces example:
  • 26. Fundamentals of Java 26 Logical Errors in Nested if Statements (Cont.) Table 6-7: Truth table for version 1 and version 2
  • 27. Fundamentals of Java 27 Logical Errors in Nested if Statements (cont.)  If braces removed, Java pairs the else with closest preceding if. – Can create logic or syntax errors if not careful – Can you spot the error in the following code?
  • 28. Fundamentals of Java 28 Logical Errors in Nested if Statements (cont.)  Better to over-use braces than under-use  Order of conditions often important in extended if-else constructs – Can you spot the logic error?
  • 29. Fundamentals of Java 29 Logical Errors in Nested if Statements (cont.)  Avoiding nested if statements can improve clarity, as in: if (90 <= average ) grade is A; if (80 <= average && average < 90) grade is B; if (70 <= average && average < 80) grade is C; if (60 <= average && average < 70) grade is D; if ( average < 60) grade is F;
  • 30. Fundamentals of Java 30 Nested Loops  A loop within another loop  Example:
  • 31. Fundamentals of Java 31 Testing Loops  Loops increase difficulty of testing. – Often do not iterate some fixed number of times – Design test data to cover situation where loop iterates:  Zero times  One time  Multiple times
  • 32. Fundamentals of Java 32 Testing Loops (cont.) Table 6-10: Test data for the count divisors program
  • 33. Fundamentals of Java 33 Testing Loops (cont.)  Combinatorial Explosion: Creating test data to verify multiple dependant components can result in huge amount of test data. – Example:  3 dependent components, each of which requires 5 tests to verify functionality  Total number of tests to verify entire program is 5*5*5=125.
  • 34. Fundamentals of Java 34 Testing Loops (cont.)  Robust program: Tolerates errors in user inputs and recovers gracefully  Best and easiest way to write robust programs is to check user inputs immediately on entry. – Reject invalid user inputs.
  • 35. Fundamentals of Java 35 Loop Verification  Process of guaranteeing that a loop performs its intended task – Independently of testing  assert statement: Allows programmer to evaluate a Boolean expression and halt the program with an error message if the expression’s value is false – General form:  assert <Boolean expression>
  • 36. Fundamentals of Java 36 Loop Verification (cont.)  To enable when running the program: – java -enableassertions AJavaProgram Example 6.1: Assert that x != 0
  • 37. Fundamentals of Java 37 Loop Verification (cont.) Figure 6-6: Failure of an assert statement
  • 38. Fundamentals of Java 38 Loop Verification: Assertions with Loops  Input assertions: State what can be expected to be true before a loop is entered  Output assertions: State what can be expected to be true when the loop is exited Table 6-12: Sums of the proper divisors of some integers
  • 39. Fundamentals of Java 39 Loop Verification: Assertions with Loops (cont.)  Sum proper divisors of positive integer:  Input assertions: – num is a positive integer – divisorSum == 0  Output assertion: – divisorSum is sum of all proper divisors of num
  • 40. Fundamentals of Java 40 Loop Verification: Invariant and Variant Assertions  Loop invariant: Assertion that expresses a relationship between variables that remains constant throughout all loop iterations  Loop variant: Assertion whose truth changes between the first and final iteration – Stated so that it guarantees the loop is exited  Usually occur in pairs
  • 41. Fundamentals of Java 41 Loop Verification: Invariant and Variant Assertions (cont.)
  • 42. Fundamentals of Java 42 Graphics and GUIs: Timers and Animations  In animation, slightly different frames are displayed in order at a rapid rate. – Produces illusion of continuous movement  Moving objects have: – Velocity  Distance (in pixels) traveled in a given unit of time – Direction
  • 43. Fundamentals of Java 43 Graphics and GUIs: Timers and Animations (cont.) Figure 6-7: Representing directions in two dimensions
  • 44. Fundamentals of Java 44 Graphics and GUIs: Timers and Animations (cont.)  Algorithm for animating a graphical object:  Java provides a timer object to schedule events at regular intervals.
  • 45. Fundamentals of Java 45 Graphics and GUIs: Timers and Animations (cont.)  Timer for animations is an instance of the class Timer.
  • 46. Fundamentals of Java 46 Graphics and GUIs: Timers and Animations (cont.) Table 6-15: Some commonly used Timer methods
  • 47. Fundamentals of Java 47 Design, Testing, and Debugging Hints  Most errors involving selection statements and loops are not syntax errors caught at compile time.  The presence or absence of braces can seriously affect the logic of a selection statement or loop.
  • 48. Fundamentals of Java 48 Design, Testing, and Debugging Hints (cont.)  When testing programs with if or if-else statements, use data that force the program to exercise all logical branches.  When testing programs with if statements, formulate equivalence classes, boundary conditions, and extreme conditions.  Use an if-else statement rather than two if statements when the alternative courses of action are mutually exclusive.
  • 49. Fundamentals of Java 49 Design, Testing, and Debugging Hints (cont.)  When testing a loop, use limit values as well as typical values.  Check entry and exit conditions for each loop.  For a loop with errors, use debugging output statements to verify the control variable’s value on each pass through the loop. – Check value before the loop is initially entered, after each update, and after the loop is exited.
  • 50. Fundamentals of Java 50 Summary  A complex Boolean expression contains one or more Boolean expressions and the logical operators && (AND), || (OR), and ! (NOT).  A truth table can determine the value of any complex Boolean expression.  Java uses short-circuit evaluation of complex Boolean expressions.
  • 51. Fundamentals of Java 51 Summary (cont.)  Nested if statements are another way of expressing complex conditions.  A nested if statement can be translated to an equivalent if statement that uses logical operators.  An extended or multiway if statement expresses a choice among several mutually exclusive alternatives.
  • 52. Fundamentals of Java 52 Summary (cont.)  Loops can be nested in other loops.  Equivalence classes, boundary conditions, and extreme conditions are important features used in tests of control structures involving complex conditions.  Loops can be verified to be correct by using assertions, loop variants, and loop invariants.