SlideShare a Scribd company logo
1 of 33
Copyright © 2014 by John Wiley & Sons. All rights reserved. 1
Chapter 5 - Decisions
Copyright © 2014 by John Wiley & Sons. All rights reserved. 2
Chapter Goals
 To implement decisions using if statements
 To compare integers, floating-point numbers, and strings
 To write statements using the boolean data type
 To develop strategies for testing your programs
 To validate user input
Copyright © 2014 by John Wiley & Sons. All rights reserved. 7
Syntax 5.1 The if Statement
Copyright © 2014 by John Wiley & Sons. All rights reserved. 15
Avoid Duplication in Branches
 If you have duplicate code in each branch, move it out of the if statement.
 Don't do this
if (floor > 13)
{
actualFloor = floor – 1;
System.out.println("Actual floor: " + actualFloor);
}
else
{
actualFloor = floor;
System.out.println("Actual floor: " + actualFloor);
}
 Instead do this:
if (floor > 13)
{
actualFloor = floor – 1;
}
else
{
actualFloor = floor;
}
System.out.println("Actual floor: " + actualFloor);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 18
What can be a Boolean Expression
 Boolean literals: true ,false
 Expressions with relational (comparison) operators
 Variables of boolean type
 Logical operators: && (and) , || (or), ! (not)
 Calls to boolean methods
Copyright © 2014 by John Wiley & Sons. All rights reserved. 19
Comparing Values: Relational Operators
 Relational operators compare values:
 The == denotes equality testing:
floor = 13; // Assign 13 to floor
if (floor == 13) // Test whether floor equals 13
 Relational operators have lower precedence than arithmetic
operators:
floor - 1 < 13
Copyright © 2014 by John Wiley & Sons. All rights reserved. 20
Syntax 5.2 Comparisons
Copyright © 2014 by John Wiley & Sons. All rights reserved. 21
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
 This is due to round-off errors
 When comparing floating-point numbers, don’t test for
equality.
• Check whether they are close enough.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 22
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 commonly set to 10-14
Copyright © 2014 by John Wiley & Sons. All rights reserved. 23
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 if two strings are stored in the same memory location
 equals method tests equal contents
Copyright © 2014 by John Wiley & Sons. All rights reserved. 24
Comparing Strings – compareTo Method
 compareTo method compares strings in lexicographic order -
dictionary order.
 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
Copyright © 2014 by John Wiley & Sons. All rights reserved. 25
 Lexicographic Ordering
Lexicographic Ordering
Copyright © 2014 by John Wiley & Sons. All rights reserved. 26
 Differences in dictionary ordering and ordering in Java
• All uppercase letters come before the lowercase letters. "Z" comes
before "a"
• The space character comes before all printable characters
• Numbers come before letters
• Ordering of punctuation marks varies
 To see which of two terms comes first in the dictionary,
consider the first letter in which they differ
Lexicographic Ordering
Copyright © 2014 by John Wiley & Sons. All rights reserved. 27
Comparing Objects
 The == operator tests whether two object references are
identical,
• whether they refer to the same object.
 Look at this code
Rectangle box1 = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box1;
Rectangle box3 = new Rectangle(5, 10, 20, 30);
• box1 == box2 is true
• box1 == box3 is false
 Use the equals method to test if two rectangles have the same
content
box1.equals(box3)
• They have the same upper-left corner and the same width and height
 Caveat: equals must be defined for the class
Copyright © 2014 by John Wiley & Sons. All rights reserved. 28
Object Comparison
Copyright © 2014 by John Wiley & Sons. All rights reserved. 29
Testing for null
 null reference refers to no object:
String middleInitial = null; // Not set
if ( . . . )
{
middleInitial = middleName.substring(0, 1);
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 30
Testing for null
 Can be used in tests:
if (middleInitial == null)
{
System.out.println(firstName + " " + lastName);
}
else
{
System.out.println(firstName + " " +
middleInitial + ". " + lastName);
}
 Use ==, not equals, to test for null
 null is not the same as the empty string ""
 Attempt to access object through null throws exception
Copyright © 2014 by John Wiley & Sons. All rights reserved. 40
Multiple Alternatives: Sequences of
Comparisons
 Example: damage done by earthquake of a given magnitude on
the Richter scale:
if (richter >= 8.0)
{
description = "Most structures fall”;
}
else if (richter >= 7.0)
{
description = "Many buildings destroyed”;
}
else if (richter >= 6.0)
{
description = "Many buildings considerably damaged, some collapse”;
}
else if (richter >= 4.5)
{
description = "Damage to poorly constructed buildings”;
}
else
{
description = "No destruction of buildings”;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved. 43
Multiple Alternatives - Flowchart
Copyright © 2014 by John Wiley & Sons. All rights reserved. 44
Multiple Alternatives: Cascaded If’s
 The order of the if and else if matters
 Error
if (richter >= 4.5) // Tests in wrong order
{
description = "Damage to poorly constructed buildings”;
}
else if (richter >= 6.0)
{
description = "Many buildings considerably damaged, some collapse”;
}
else if (richter >= 7.0)
{
description = "Many buildings destroyed”;
}
else if (richter >= 8.0)
{
description = "Most structures fall”;
}
 When using multiple if statements, test general conditions after
more specific conditions.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 45
Multiple Alternatives
 In this example, must use if/else if/else sequence, not just
multiple independent if statements
 Error
if (richter >= 8.0) // Didn't use else
{
description = "Most structures fall”;
}
if (richter >= 7.0)
{
description = "Many buildings destroyed”;
}
if (richter >= 6.0)
{
description = "Many buildings considerably damaged, some collapse”;
}
if (richter >= 4.5)
{
"Damage to poorly constructed buildings”;
}
 The alternatives are no longer exclusive.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 52
Nested Branches
 Nested set of statements:
• An if statement inside another
 Example: Federal Income Tax
• Tax depends on marital status and income
Copyright © 2014 by John Wiley & Sons. All rights reserved. 54
Nested Branches - Flowchart
Copyright © 2014 by John Wiley & Sons. All rights reserved. 55
section_4/TaxReturn.java
1 /**
2 A tax return of a taxpayer in 2008.
3 */
4 public class TaxReturn
5 {
6 public static final int SINGLE = 1;
7 public static final int MARRIED = 2;
8
9 private static final double RATE1 = 0.10;
10 private static final double RATE2 = 0.25;
11 private static final double RATE1_SINGLE_LIMIT = 32000;
12 private static final double RATE1_MARRIED_LIMIT = 64000;
13
14 private double income;
15 private int status;
16
17 /**
18 Constructs a TaxReturn object for a given income and
19 marital status.
20 @param anIncome the taxpayer income
21 @param aStatus either SINGLE or MARRIED
22 */
23 public TaxReturn(double anIncome, int aStatus)
24 {
25 income = anIncome;
26 status = aStatus;
27 }
28
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 56
section_4/TaxReturn.java
29 public double getTax()
30 {
31 double tax1 = 0;
32 double tax2 = 0;
33
34 if (status == SINGLE)
35 {
36 if (income <= RATE1_SINGLE_LIMIT)
37 {
38 tax1 = RATE1 * income;
39 }
40 else
41 {
42 tax1 = RATE1 * RATE1_SINGLE_LIMIT;
43 tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT);
44 }
45 }
46 else
47 {
48 if (income <= RATE1_MARRIED_LIMIT)
49 {
50 tax1 = RATE1 * income;
51 }
52 else
53 {
54 tax1 = RATE1 * RATE1_MARRIED_LIMIT;
55 tax2 = RATE2 * (income - RATE1_MARRIED_LIMIT);
56 }
57 }
58
59 return tax1 + tax2;
60 }
61 }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 80
Boolean Variables and Operators
 To store the evaluation of a logical condition that can be true or false,
you use a Boolean variable.
 The boolean data type has exactly two values, denoted false and
true.
boolean failed = true;
Boolean negative = x < 0;
 Later in your program, use the value to make a decision
if (failed==true) // Only executed if failed has been set to true
{ . . . }
 A Boolean variable is also called a flag because it can be either up
(true) or down (false).
Copyright © 2014 by John Wiley & Sons. All rights reserved. 81
Boolean Variables and Operators
 You often need to combine Boolean values when making
complex decisions
 An operator that combines Boolean conditions is called a
Boolean operator.
 The && operator is called and
• Yields true only when both conditions are true.
 The || operator is called or
• Yields the result true if at least one of the conditions is true.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 82
Boolean Variables and Operators
 To test if water is liquid at a given temperature
if (temp > 0 && temp < 100)
{
System.out.println("Liquid");
}
 Flowchart
Copyright © 2014 by John Wiley & Sons. All rights reserved. 83
Boolean Variables and Operators
 To test if water is not liquid at a given temperature
if (temp <= 0 || temp >= 100)
{
System.out.println(“Not liquid");
}
 Flowchart
Copyright © 2014 by John Wiley & Sons. All rights reserved. 84
Boolean Variables and Operators
Copyright © 2014 by John Wiley & Sons. All rights reserved. 85
Boolean Variables and Operators
 To invert a condition use the not Boolean operator
 The ! operator takes a single condition
• Evaluates to true if that condition is false and
• Evaluates to false if the condition is true
 To test if the Boolean variable frozen is false:
if (!frozen) { System.out.println("Not frozen"); }
Copyright © 2014 by John Wiley & Sons. All rights reserved. 86
Logical Identities
 true && A yields A
 false && A yields false
 True || A yields true
 False || A yields A
 B == true yields B
 !(A && B) == (!A || !B)
 !(A || B) == (!A && !B)
Let A, B be an arbitrary boolean expressions:
Short Circuit Evaluation: Only evaluate what is required to determine truth value
Copyright © 2014 by John Wiley & Sons. All rights reserved. 87
De Morgan’s Law in Action
if ((obj != null) && (obj.getSomething() > 0)) {
// CODE
else
// Is obj == null here??

More Related Content

What's hot

Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016BienvenidoVelezUPR
 
Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016BienvenidoVelezUPR
 
Chapter 4 Powerpoint
Chapter 4 PowerpointChapter 4 Powerpoint
Chapter 4 PowerpointGus Sandoval
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaEduardo Bergavera
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsSvetlin Nakov
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5Mahmoud Ouf
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONSVISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONSSuraj Kumar
 

What's hot (20)

Icom4015 lecture3-f16
Icom4015 lecture3-f16Icom4015 lecture3-f16
Icom4015 lecture3-f16
 
CIIC 4010 Chapter 1 f17
CIIC 4010 Chapter 1 f17CIIC 4010 Chapter 1 f17
CIIC 4010 Chapter 1 f17
 
CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17CiIC4010-chapter-2-f17
CiIC4010-chapter-2-f17
 
Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016Advanced Programming Lecture 5 Fall 2016
Advanced Programming Lecture 5 Fall 2016
 
Icom4015 lecture8-f16
Icom4015 lecture8-f16Icom4015 lecture8-f16
Icom4015 lecture8-f16
 
Icom4015 lecture7-f16
Icom4015 lecture7-f16Icom4015 lecture7-f16
Icom4015 lecture7-f16
 
Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016Advanced Programming Lecture 6 Fall 2016
Advanced Programming Lecture 6 Fall 2016
 
Icom4015 lecture14-f16
Icom4015 lecture14-f16Icom4015 lecture14-f16
Icom4015 lecture14-f16
 
Icom4015 lecture10-f16
Icom4015 lecture10-f16Icom4015 lecture10-f16
Icom4015 lecture10-f16
 
Icom4015 lecture11-s16
Icom4015 lecture11-s16Icom4015 lecture11-s16
Icom4015 lecture11-s16
 
Chapter 4 Powerpoint
Chapter 4 PowerpointChapter 4 Powerpoint
Chapter 4 Powerpoint
 
06slide
06slide06slide
06slide
 
07slide
07slide07slide
07slide
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
C sharp chap4
C sharp chap4C sharp chap4
C sharp chap4
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONSVISUAL BASIC 6 - CONTROLS AND DECLARATIONS
VISUAL BASIC 6 - CONTROLS AND DECLARATIONS
 

Similar to Implement Decisions Using if Statements

chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)It Academy
 
Chapter 3:Programming with Java Operators and Strings
Chapter 3:Programming with Java Operators and  StringsChapter 3:Programming with Java Operators and  Strings
Chapter 3:Programming with Java Operators and StringsIt Academy
 
Chapter 3 : Programming with Java Operators and Strings
Chapter 3 : Programming with Java Operators and  StringsChapter 3 : Programming with Java Operators and  Strings
Chapter 3 : Programming with Java Operators and StringsIt Academy
 
Chapter 3
Chapter 3Chapter 3
Chapter 3It Academy
 
Programming in Java: Control Flow
Programming in Java: Control FlowProgramming in Java: Control Flow
Programming in Java: Control FlowMartin Chapman
 
05 Conditional statements
05 Conditional statements05 Conditional statements
05 Conditional statementsmaznabili
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysDevaKumari Vijay
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My HeartBui Kiet
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupDror Helper
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenGraham Royce
 
Javatut1
Javatut1 Javatut1
Javatut1 desaigeeta
 

Similar to Implement Decisions Using if Statements (20)

chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)
 
Chapter 3:Programming with Java Operators and Strings
Chapter 3:Programming with Java Operators and  StringsChapter 3:Programming with Java Operators and  Strings
Chapter 3:Programming with Java Operators and Strings
 
Chapter 3 : Programming with Java Operators and Strings
Chapter 3 : Programming with Java Operators and  StringsChapter 3 : Programming with Java Operators and  Strings
Chapter 3 : Programming with Java Operators and Strings
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Programming in Java: Control Flow
Programming in Java: Control FlowProgramming in Java: Control Flow
Programming in Java: Control Flow
 
05 Conditional statements
05 Conditional statements05 Conditional statements
05 Conditional statements
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Chapter3
Chapter3Chapter3
Chapter3
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
Ch3
Ch3Ch3
Ch3
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Java unit 3
Java unit 3Java unit 3
Java unit 3
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet Soup
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
 
Javatut1
Javatut1 Javatut1
Javatut1
 
Java tut1
Java tut1Java tut1
Java tut1
 
Lecture1.pdf
Lecture1.pdfLecture1.pdf
Lecture1.pdf
 

Recently uploaded

Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsSachinPawar510423
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptMadan Karki
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction managementMariconPadriquez1
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 

Recently uploaded (20)

Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documents
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.ppt
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction management
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 

Implement Decisions Using if Statements

  • 1. Copyright © 2014 by John Wiley & Sons. All rights reserved. 1 Chapter 5 - Decisions
  • 2. Copyright © 2014 by John Wiley & Sons. All rights reserved. 2 Chapter Goals  To implement decisions using if statements  To compare integers, floating-point numbers, and strings  To write statements using the boolean data type  To develop strategies for testing your programs  To validate user input
  • 3. Copyright © 2014 by John Wiley & Sons. All rights reserved. 7 Syntax 5.1 The if Statement
  • 4. Copyright © 2014 by John Wiley & Sons. All rights reserved. 15 Avoid Duplication in Branches  If you have duplicate code in each branch, move it out of the if statement.  Don't do this if (floor > 13) { actualFloor = floor – 1; System.out.println("Actual floor: " + actualFloor); } else { actualFloor = floor; System.out.println("Actual floor: " + actualFloor); }  Instead do this: if (floor > 13) { actualFloor = floor – 1; } else { actualFloor = floor; } System.out.println("Actual floor: " + actualFloor);
  • 5. Copyright © 2014 by John Wiley & Sons. All rights reserved. 18 What can be a Boolean Expression  Boolean literals: true ,false  Expressions with relational (comparison) operators  Variables of boolean type  Logical operators: && (and) , || (or), ! (not)  Calls to boolean methods
  • 6. Copyright © 2014 by John Wiley & Sons. All rights reserved. 19 Comparing Values: Relational Operators  Relational operators compare values:  The == denotes equality testing: floor = 13; // Assign 13 to floor if (floor == 13) // Test whether floor equals 13  Relational operators have lower precedence than arithmetic operators: floor - 1 < 13
  • 7. Copyright © 2014 by John Wiley & Sons. All rights reserved. 20 Syntax 5.2 Comparisons
  • 8. Copyright © 2014 by John Wiley & Sons. All rights reserved. 21 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  This is due to round-off errors  When comparing floating-point numbers, don’t test for equality. • Check whether they are close enough.
  • 9. Copyright © 2014 by John Wiley & Sons. All rights reserved. 22 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 commonly set to 10-14
  • 10. Copyright © 2014 by John Wiley & Sons. All rights reserved. 23 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 if two strings are stored in the same memory location  equals method tests equal contents
  • 11. Copyright © 2014 by John Wiley & Sons. All rights reserved. 24 Comparing Strings – compareTo Method  compareTo method compares strings in lexicographic order - dictionary order.  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
  • 12. Copyright © 2014 by John Wiley & Sons. All rights reserved. 25  Lexicographic Ordering Lexicographic Ordering
  • 13. Copyright © 2014 by John Wiley & Sons. All rights reserved. 26  Differences in dictionary ordering and ordering in Java • All uppercase letters come before the lowercase letters. "Z" comes before "a" • The space character comes before all printable characters • Numbers come before letters • Ordering of punctuation marks varies  To see which of two terms comes first in the dictionary, consider the first letter in which they differ Lexicographic Ordering
  • 14. Copyright © 2014 by John Wiley & Sons. All rights reserved. 27 Comparing Objects  The == operator tests whether two object references are identical, • whether they refer to the same object.  Look at this code Rectangle box1 = new Rectangle(5, 10, 20, 30); Rectangle box2 = box1; Rectangle box3 = new Rectangle(5, 10, 20, 30); • box1 == box2 is true • box1 == box3 is false  Use the equals method to test if two rectangles have the same content box1.equals(box3) • They have the same upper-left corner and the same width and height  Caveat: equals must be defined for the class
  • 15. Copyright © 2014 by John Wiley & Sons. All rights reserved. 28 Object Comparison
  • 16. Copyright © 2014 by John Wiley & Sons. All rights reserved. 29 Testing for null  null reference refers to no object: String middleInitial = null; // Not set if ( . . . ) { middleInitial = middleName.substring(0, 1); }
  • 17. Copyright © 2014 by John Wiley & Sons. All rights reserved. 30 Testing for null  Can be used in tests: if (middleInitial == null) { System.out.println(firstName + " " + lastName); } else { System.out.println(firstName + " " + middleInitial + ". " + lastName); }  Use ==, not equals, to test for null  null is not the same as the empty string ""  Attempt to access object through null throws exception
  • 18. Copyright © 2014 by John Wiley & Sons. All rights reserved. 40 Multiple Alternatives: Sequences of Comparisons  Example: damage done by earthquake of a given magnitude on the Richter scale: if (richter >= 8.0) { description = "Most structures fall”; } else if (richter >= 7.0) { description = "Many buildings destroyed”; } else if (richter >= 6.0) { description = "Many buildings considerably damaged, some collapse”; } else if (richter >= 4.5) { description = "Damage to poorly constructed buildings”; } else { description = "No destruction of buildings”; }
  • 19. Copyright © 2014 by John Wiley & Sons. All rights reserved. 43 Multiple Alternatives - Flowchart
  • 20. Copyright © 2014 by John Wiley & Sons. All rights reserved. 44 Multiple Alternatives: Cascaded If’s  The order of the if and else if matters  Error if (richter >= 4.5) // Tests in wrong order { description = "Damage to poorly constructed buildings”; } else if (richter >= 6.0) { description = "Many buildings considerably damaged, some collapse”; } else if (richter >= 7.0) { description = "Many buildings destroyed”; } else if (richter >= 8.0) { description = "Most structures fall”; }  When using multiple if statements, test general conditions after more specific conditions.
  • 21. Copyright © 2014 by John Wiley & Sons. All rights reserved. 45 Multiple Alternatives  In this example, must use if/else if/else sequence, not just multiple independent if statements  Error if (richter >= 8.0) // Didn't use else { description = "Most structures fall”; } if (richter >= 7.0) { description = "Many buildings destroyed”; } if (richter >= 6.0) { description = "Many buildings considerably damaged, some collapse”; } if (richter >= 4.5) { "Damage to poorly constructed buildings”; }  The alternatives are no longer exclusive.
  • 22. Copyright © 2014 by John Wiley & Sons. All rights reserved. 52 Nested Branches  Nested set of statements: • An if statement inside another  Example: Federal Income Tax • Tax depends on marital status and income
  • 23. Copyright © 2014 by John Wiley & Sons. All rights reserved. 54 Nested Branches - Flowchart
  • 24. Copyright © 2014 by John Wiley & Sons. All rights reserved. 55 section_4/TaxReturn.java 1 /** 2 A tax return of a taxpayer in 2008. 3 */ 4 public class TaxReturn 5 { 6 public static final int SINGLE = 1; 7 public static final int MARRIED = 2; 8 9 private static final double RATE1 = 0.10; 10 private static final double RATE2 = 0.25; 11 private static final double RATE1_SINGLE_LIMIT = 32000; 12 private static final double RATE1_MARRIED_LIMIT = 64000; 13 14 private double income; 15 private int status; 16 17 /** 18 Constructs a TaxReturn object for a given income and 19 marital status. 20 @param anIncome the taxpayer income 21 @param aStatus either SINGLE or MARRIED 22 */ 23 public TaxReturn(double anIncome, int aStatus) 24 { 25 income = anIncome; 26 status = aStatus; 27 } 28 Continued
  • 25. Copyright © 2014 by John Wiley & Sons. All rights reserved. 56 section_4/TaxReturn.java 29 public double getTax() 30 { 31 double tax1 = 0; 32 double tax2 = 0; 33 34 if (status == SINGLE) 35 { 36 if (income <= RATE1_SINGLE_LIMIT) 37 { 38 tax1 = RATE1 * income; 39 } 40 else 41 { 42 tax1 = RATE1 * RATE1_SINGLE_LIMIT; 43 tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT); 44 } 45 } 46 else 47 { 48 if (income <= RATE1_MARRIED_LIMIT) 49 { 50 tax1 = RATE1 * income; 51 } 52 else 53 { 54 tax1 = RATE1 * RATE1_MARRIED_LIMIT; 55 tax2 = RATE2 * (income - RATE1_MARRIED_LIMIT); 56 } 57 } 58 59 return tax1 + tax2; 60 } 61 }
  • 26. Copyright © 2014 by John Wiley & Sons. All rights reserved. 80 Boolean Variables and Operators  To store the evaluation of a logical condition that can be true or false, you use a Boolean variable.  The boolean data type has exactly two values, denoted false and true. boolean failed = true; Boolean negative = x < 0;  Later in your program, use the value to make a decision if (failed==true) // Only executed if failed has been set to true { . . . }  A Boolean variable is also called a flag because it can be either up (true) or down (false).
  • 27. Copyright © 2014 by John Wiley & Sons. All rights reserved. 81 Boolean Variables and Operators  You often need to combine Boolean values when making complex decisions  An operator that combines Boolean conditions is called a Boolean operator.  The && operator is called and • Yields true only when both conditions are true.  The || operator is called or • Yields the result true if at least one of the conditions is true.
  • 28. Copyright © 2014 by John Wiley & Sons. All rights reserved. 82 Boolean Variables and Operators  To test if water is liquid at a given temperature if (temp > 0 && temp < 100) { System.out.println("Liquid"); }  Flowchart
  • 29. Copyright © 2014 by John Wiley & Sons. All rights reserved. 83 Boolean Variables and Operators  To test if water is not liquid at a given temperature if (temp <= 0 || temp >= 100) { System.out.println(“Not liquid"); }  Flowchart
  • 30. Copyright © 2014 by John Wiley & Sons. All rights reserved. 84 Boolean Variables and Operators
  • 31. Copyright © 2014 by John Wiley & Sons. All rights reserved. 85 Boolean Variables and Operators  To invert a condition use the not Boolean operator  The ! operator takes a single condition • Evaluates to true if that condition is false and • Evaluates to false if the condition is true  To test if the Boolean variable frozen is false: if (!frozen) { System.out.println("Not frozen"); }
  • 32. Copyright © 2014 by John Wiley & Sons. All rights reserved. 86 Logical Identities  true && A yields A  false && A yields false  True || A yields true  False || A yields A  B == true yields B  !(A && B) == (!A || !B)  !(A || B) == (!A && !B) Let A, B be an arbitrary boolean expressions: Short Circuit Evaluation: Only evaluate what is required to determine truth value
  • 33. Copyright © 2014 by John Wiley & Sons. All rights reserved. 87 De Morgan’s Law in Action if ((obj != null) && (obj.getSomething() > 0)) { // CODE else // Is obj == null here??