1 Decisions, decisions, decisions Chapter 5 Fall 2006 CS 101 Aaron Bloomfield.

Slides:



Advertisements
Similar presentations
What is the Result and Type of the Following Expressions? int x=2, y=15;double u=2.0,v=15.0; -xx+yx-y x*vy / xx/yy%xx%y u*vu/vv/uu%v x * u(x+y)*uu /(x-x)
Advertisements

Topic 03 Control Statements Programming II/A CMC2522 / CIM2561 Bavy Li.
If Statements & Relational Operators Programming.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Control Constructs Mechanisms for deciding when and how often an action should be taken.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Logical Operators and Conditional statements
Chapter 4 Making Decisions
C++ for Engineers and Scientists Third Edition
COMP 110 Introduction to Programming Mr. Joshua Stough September 19, 2007.
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Fundamental Programming: Fundamental Programming Introduction to C++
1 Decisions, decisions, decisions Chapter 4 Trey Kirk.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
1 Compound Assignment C++ has a large set of operators for applying an operation to an object and then storing the result back into the object Examples.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Decisions, decisions, decisions. Background  Our problem-solving solutions so far have the straight-line property They execute the same statements for.
Representing Relations
1 Chapter 4, Part 1 If Control Construct A mechanism for deciding whether an action should be taken JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Java Programming: From Problem Analysis to Program Design, 3e Chapter 4 Control Structures I: Selection.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
ICT Introduction to Programming Chapter 4 – Control Structures I.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
Boolean values Gateway to decision making. Background Our problem-solving solutions so far have the straight-line property –They execute the same statements.
If Statements Programming. COMP104 Lecture 7 / Slide 2 Review: Rules for Division l C++ treats integers different than doubles. 100 is an int. l 100.0,
Control statements Mostafa Abdallah
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC INTRO TO COMPUTING - PROGRAMMING If Statement.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
Decision Statements, Short- Circuit Evaluation, Errors.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
1 Review for Midterm 2 Aaron Bloomfield CS 101-E.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Decisions. Background Our problem-solving solutions so far have the straight-line property –They execute the same statements for every run of the program.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
What is the Result and Type of the Following Expressions? int x=2, y=15;double u=2.0,v=15.0; -xx+yx-y x*vy / xx/yy%xx%y u*vu/vv/uu%v x * u(x+y)*uu /(x-x)
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 15, 2004 Lecture Number: 11.
Decisions Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Decision Structures Michele Co CS 101-E. 2 UVa CS101E Spring 2007 Today if statements Logical expressions –Truth tables –Boolean algebra –DeMorgan’s laws.
Decisions, decisions, decisions
Selection (also known as Branching) Jumail Bin Taliba by
A mechanism for deciding whether an action should be taken
Decisions.
Expression Review what is the result and type of these expressions?
The System.exit() Method
Control Structure Chapter 3.
Chapter 2 Programming Basics.
Boolean Expressions to Make Comparisons
COMS 261 Computer Science I
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Control Structure.
Presentation transcript:

1 Decisions, decisions, decisions Chapter 5 Fall 2006 CS 101 Aaron Bloomfield

2 Background  Our problem-solving solutions so far have the straight-line property They execute the same statements for every run of the program public class DisplayForecast // main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world"); System.out.print(" market for maybe five "); System.out.println("computers. “); System.out.print(" Thomas Watson, IBM, “); System.out.println("1943.“); } }

3 Background  For general problem solving we need more capabilities The ability to control which statements are executed The ability to control how often a statement is executed  We will concentrate first on controlling which statements are executed  Java provides the if and switch conditional constructs to control whether a statement list is executed The if constructs use logical expressions to determine their course of action  We will start with logical expressions

4 Logical expressions

5  The branch of mathematics dealing with logical expressions is Boolean algebra Developed by the British mathematician George Boole

6 Logical expressions  A logical expression has either the value logical true or logical false Some expressions whose values are logical true  The year 2004 is a leap year  A meter equals 100 centimeters Some expressions whose values are logical false  A triangle has four sides  The area of square is always equal to twice its perimeter

7 Logical expressions  There are three primary logical operators for manipulating logical values Logical and Logical or Logical not  The operators work as most of us would expect

8 Truth tables  We use truth tables to give formal specifications of the operators “It works as most of us would expect” allows for ambiguity of interpretation  Jim is smiling or Patty is smiling Can both Jim and Patty both be smiling?  Truth tables Lists all combinations of operand values and the result of the operation for each combination pq p and q False FalseFalse False TrueFalse True FalseFalse True TrueTrue

9 Or and not truth tables pq p or q False FalseFalse False TrueTrue True FalseTrue True TrueTrue pnot p False True True False

10 Boolean algebra  Can create complex logical expressions by combining simple logical expressions not (p and q) pq p and q not (p and q) False FalseFalseTrue False TrueFalseTrue True FalseFalseTrue True TrueTrueFalse

11 DeMorgan’s laws  not (p and q) equals (not p) or (not q) (not p) or pq p and q not (p and q) ( not p) (not q) (not q) False False False True True True True False True False True True False True True False False True False True True True True True False False False False

12 DeMorgan’s laws  not (p or q) equals (not p) and (not q) (not p) and pq p or q not (p or q) ( not p) (not q) (not q) False False False True True True True False True True False True False False True False True False False True False True True True False False False False

13 DeMorgan’s laws  If you remember nothing else about the Boolean operators, remember that: not (a and b) == (not a) or (not b) not (a or b) == (not a) and (not b)

14 Sidewalk chalk guy Source: Source:

15 Boolean expressions

16 A boolean type  Java has the logical type boolean  Type boolean has two literal constants true false  Operators The and operator is &&  Don’t use & The or operator is ||  Don’t use | The not operator is !

17 Defining boolean variables  Local boolean variables are uninitialized by default boolean isWhitespace; boolean receivedAcknowledgement; boolean haveFoundMissingLink;

18 Defining boolean variables  Local boolean variables with initialization boolean canProceed = true; boolean preferCyan = false; boolean completedSecretMission = true;

19 Assignment vs. comparison  = is the assignment operator It copies the value on the right to the location on the left Consider: int x; x = 5; The value 5 is copied to the spot x in memory  == is the comparison operator Returns a boolean (true or false) if the two sides are equal Consider: int x = 5; System.out.println (x == 5); System.out.println (x == 6); Prints out true, false

20 Other operators  Equality operators == and != Operator ==  Returns true if the operands have the same value; otherwise, returns false  This is not the assignment operator! Operator !=  Returns true if the operands have different values; otherwise, returns false The operators work with all types of values

21 Evaluating boolean expressions  Suppose boolean p = true; boolean q = false; boolean r = true; boolean s = false;  What is the value of p p && s !s p == q q q != r p && r r == s q || s q != s

22 Evaluating boolean expressions  Suppose int i = 1; int j = 2; int k = 2; char c = '#'; char d = '%'; char e = '#';  What is the value of j == k i != k i == j j != k c == e d != e c == d c != e

23 A bit of humor…

24 Translating English to logical expressions

25 Translating English to logical expressions  English doesn’t always translate cleanly into logical expressions  To see this, we need to examine the NOR operator It doesn’t exist in Java, but we can fake it p NOR q == NOT (p OR q) NOR is represented by a downward arrow:   In Java, given variables p and q NOR is done by: !(p||q) pq p or q not (p or q) p nor q False False False TrueTrue False True True FalseFalse True False True FalseFalse True True True FalseFalse

26 Translation Example  “I have neither given nor received help on this exam” Rephrased: “I have not given nor received …” Let p = “I have given help on this exam” Let q = “I have received help on this exam”  Translation is: pq Remember the precedence: NOT is done first! pq pppqpq TTFF TFFT FTTF FFTF

27 Translation example, take 2  “I have neither given nor received help on this exam” Rephrased: “I have not (given nor received …)” Let p = “I have given help on this exam” Let q = “I have received help on this exam”  Another translation is: (pq) = p || q pqp || q TTT TFT FTT FFF

28 Translation example, rephrased  What is meant is “I have not given and I have not received help on this exam” Or “I have not (given or received) help on this exam” This is a DeMorgaization of the one above it  The problem:  has a higher precedence than  in Boolean logic, but not always in English  Also, “neither” is vague pq pq(p||q) TTFF TFFF FTFF FFTT

29 Disclaimer  The preceding example was showing that when English can be clear, it does not always translate clearly into Boolean logic The English meaning is exact The Boolean translation is not  This does not mean that you can cheat, and say that I said it was allowed by the honor code

30 End of lecture on 18 September 2006

31 Floating point comparison

32 Floating point precission  What gets printed? class FloatTest { public static void main (String args[]) { double y = ; System.out.println (y); } There are ’s

33 Program demo FloatTest.java FloatTest.java

34 Take care with floating-point values  Consider double a = 1; double b = double c = ;  Two true expressions! c == bb != a  Two false expressions! a == bb != c  Problem lies with the finite precision of the floating-point types  Instead with the ordering operators for closeness

35 How to solve this  Don’t compare floating-point values if you can help it! Both doubles and floats  Need to test if the two doubles are “close” in value final double EPSILON = ; boolean foo = Math.abs (a-b) < EPSILON;

36 More on evaluating expressions

37 Ordering operators  Java provides ordering operators for the primitive types Four ordering operators,, = They correspond to mathematical operators of, ≤, and ≥  Together the equality and ordering operators are known as the relational operators  False is less than true

38 Evaluation boolean expressions  Suppose int i = 1; int j = 2; int k = 2;  What is the value of i < j j < k i <= k j >= k i >= k

39 Unicode values  Character comparisons are based on their Unicode values  Characters ‘0’, ‘1’, … ‘9’ have expected order Character ‘0’ has the encoding 48 Character ‘1’ has the encoding 49, and so on.  Upper case Latin letters ‘A’, ‘B’, … ‘Z’ have expected order Character ‘A’ has the encoding 65, character ‘B’ has the encoding 66, and so on.  Lower case Latin letters ‘a’, ‘b’, … ‘z’ have expected order  Character ‘a’ has the encoding 97  Character ‘b’ has the encoding 98, and so on.

40 Evaluation boolean expressions  Suppose char c = '2'; char d = '3'; char e = '2';  What is the value of c < d c < e c <= e d >= e c >= e

41 Operator precedence revisited  Highest to lowest Parentheses Unary operators Multiplicative operators Additive operators Relational ordering Relational equality Logical and Logical or Assignment

42 Expressions vs. statements  A statement is a single command for Java to do, and always ends in a semi-colon (for now, at least) System.out.println (“hello world”); int x = 4; ++x;  An expression returns a value, and does not have a semi- colon 5 circle.getRadius() x  Note the difference between the following: ++iis an expression ++i;is a statement

43 Sand Castles

44 if statement

45 Conditional constructs  Provide Ability to control whether a statement list is executed  Two constructs If statement  if  if-else  if-else-if Switch statement

46 Basic if statement  Syntax if (Expression) Action  If the Expression is true then execute Action  Action is either a single statement or a group of statements within braces  For us, it will always be a group of statements within braces Expression Action truefalse

47 Example if (value < 0) { value = -value; } Is our number negative? If Value is not less than zero then our number is fine as is If Value is less than zero then we need to update its value to that of its additive inverse false Value < 0 Value = -Value true Our number is now definitely nonnegative

48 Sorting two values System.out.print("Enter an integer number: "); int value1 = stdin.nextInt(); System.out.print("Enter another integer number: "); int value2 = stdin.nextInt(); // rearrange numbers if necessary if (value2 < value1) { // values are not in sorted order int rememberValue1 = value1; value1 = value2; value2 = rememberValue1; } // display values System.out.println("The numbers in sorted order are " + value1 + " and then " + value2); What happens if the user enters 11 and 28? What happens if the user enters 11 and 4?

If semantics Are the numbers out of order Rearrange value1 and value2 to put their values in the proper order value2 < value1 intrememberValue1 = value1 value1 = value2 value2 = rememberValue1 true false The numberswereinitially in order The numbers were rearranged into the proper order The numbers are in order

50 What an if statement executes  An if statement executes the next block of code  A block is either: A single statement without curly brackets: if (a == b) System.out.println (“a==b!!!”); A number of statements enclosed by curly brackets: if (a == b) { System.out.print (“a”); System.out.print (“==”); System.out.print (“b”); System.out.println (“!!!”); }

51 Why we always use braces  What is the output? int m = 5; int n = 10; if (m < n) ++m; ++n; System.out.println(" m = " + m + " n = “ + n);

52 Warn your grandparents! Historically, this class has been lethal to grandparents of students in the class Historically, this class has been lethal to grandparents of students in the class –More often grandmothers This happens most around test time This happens most around test time –Although occasionally around the times a big assignment is due See See

53 if-else statement

54 The if-else statement  Syntax if (Expression) Action 1 else Action 2  If Expression is true then execute Action 1 otherwise execute Action 2  The actions are either a single statement or a list of statements within braces Expression Action 1 Action 2 true false

55 Finding the maximum of two values System.out.print("Enter an integer number: "); int value1 = stdin.nextInt(); System.out.print("Enter another integer number: "); int value2 = stdin.nextInt(); int maximum; if (value1 < value2) { // is value2 larger? maximum = value2; // yes: value2 is larger } else { // (value1 >= value2) maximum = value1; // no: value2 is not larger } System.out.println("The maximum of " + value1 + " and " + value2 + " is " + maximum); But is it initialized?

56 Finding the maximum of two values System.out.print("Enter an integer number: "); int value1 = stdin.nextInt(); System.out.print("Enter another integer number: "); int value2 = stdin.nextInt(); int maximum; if (value1 < value2) { // is value2 larger? maximum = value2; // yes: value2 is larger } System.out.println("The maximum of " + value1 + " and " + value2 + " is " + maximum); But is it initialized?

57 Finding the maximum of two values value1 < value2 maximum = value2 maximum = value1 true false Is value2 larger than value1 Yes, it is. So value2 is larger than value1. In this case, maximum is set to value2 No, its not. So value1 is at least as large as value2. In this case, maximum is set to value1 Either case, maximum is set correctly

58 Why we use whitespace  What does the following do? System.out.print("Enter an integer number: "); int value1 = stdin.nextInt(); System.out.print("Enter another integer number: "); int value2 = stdin.nextInt(); if (value2 < value1) { int rememberValue1 = value1; value1 = value2; value2 = rememberValue1; } System.out.println("The numbers in sorted order are " + value1 + " and then " + value2);

59 How do you like your braces? if (a == b) { //... } else { //... } if (a == b) { //... } else { //... } if (a == b) { //... } else { //... } if (a == b) { //... } else { //... } if (a == b) { //... } else { //... }

60 If-then-else precedence if (number != 0) if (number > 0) System.out.println("positive"); else System.out.println("negative"); Which if does this else refer to?

61 If-then-else precedence without whitespace if (number != 0) if (number > 0) System.out.println("positive"); else System.out.println("negative"); else System.out.println("zero");

62 Program demo ElsePrecedence.java ElsePrecedence.java

63 End of lecture on 20 September 2006

64 if-else-if statement

65 if (number == 0) { System.out.println("zero"); } else If-else-if  Consider System.out.println("positive"); } else { System.out.println("negative"); } } { These braces aren’t needed if (number > 0) { Same results as previous segment – but this segment better expresses the meaning of what is going on We can change the whitespace of the code

66 Sorting three values  For sorting values n1, n2, and n3 there are six possible orderings n1  n2  n3 n1  n3  n2 n2  n1  n3 n2  n3  n1 n3  n1  n2 n3  n2  n1  Suppose s1, s2, s3 are to be a sorted version of n1, n2, and n3

67 Sorting three values if ((n1 <= n2) && (n2 <= n3)) { // n1 <= n2 <= n3 s1 = n1; s2 = n2; s3 = n3; } else if ((n1 <= n3) && (n3 <= n2)) { // n1 <= n3 <= n2 s1 = n1; s2 = n3; s3 = n2; } else if ((n2 <= n1) && (n1 <= n3)) { // n2 <= n1 <= n3 s1 = n2; s2 = n1; s3 = n3; } else if ((n2 <= n3) && (n3 <= n1)) { // n2 <= n3 <= n1 s1 = n2; s2 = n3; s3 = n1; } else if ((n3 <= n1) && (n1 <= n2)) { // n3 <= n1 <= n2 s1 = n3; s2 = n1; s3 = n2; } else { // n3 <= n2 <= n1 s1 = n3; s2 = n2; s3 = n1; }

68 ?: notation

69 Finding the minimum value  Consider: // z is to hold the minimum of x and y if ( x < y ) z = x; else z = y ;  Another way to do this: z = (x<y) ? x : y; Notice no braces!

70 The ?: notation  Only works when both “cases” return a value! Meaning when both “cases” are expressions Example: z = (x<y) ? x : y; Thus, you can’t put a print statement in there!  Can be difficult to read System.out.println ((number != 0) ? ((number > 0) ? "positive“ : "negative") : "zero“); if (number != 0) if (number > 0) System.out.println("positive"); else System.out.println("negative"); else System.out.println("zero");

71 A bit of humor…

72 switch statement

73 Switch statement  Software engineers often confronted with programming tasks where required action depends on the values of integer expressions The if-else-if construct can be used  Separately compare the desired expression to a particular value If the expression and value are equal, then perform the appropriate action  Because such programming tasks occur frequently Java includes a switch statement  The task is often more readable with the switch then with the if-else-if

74 A switch statement example if (a == ‘0’) System.out.println (“zero”); else if (a == ‘1’) System.out.println (“one”); else if (a == ‘2’) System.out.println (“two”); else if (a == ‘3’) System.out.println (“three”); else if (a == ‘4’) System.out.println (“four”); else System.out.println (“five+”); switch (a) { case ‘0’: System.out.println (“zero”); break; case ‘1’: System.out.println (“one”); break; case ‘2’: System.out.println (“two”); break; case ‘3’: System.out.println (“three”); break; case ‘4’: System.out.println (“four”); break; default: System.out.println (“five+”); break; }

75 End of lecture on 25 September 2006  But will start again at the beginning of the switch statement  And did exam review as well

76 Switch statement switch(SwitchExpression) { caseCaseExpression 1 : Action 1 ; caseCaseExpression 2 : Action 2 ;... caseCaseExpression n : Action n ; default: Action n+1 ; } Constant integral expression Java statements Integral expression to be matched with a case expression

77 Testing for vowel-ness switch (ch) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': System.out.println("vowel“); break; default: System.out.println("not a vowel“); }

78 Testing for vowel-ness switch (ch) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': System.out.println("vowel“); break; default: System.out.println("not a vowel“); } The break causes an exiting of the switch Handles all of the other cases

79 A better way to format that switch statement switch (ch) { case 'a': // FALL THRU case 'A': // FALL THRU case 'e': // FALL THRU case 'E': // FALL THRU case 'i': // FALL THRU case 'I': // FALL THRU...

80 Processing a request System.out.print("Enter a number: "); int n1 = stdin.nextInt(); System.out.print("Enter another number: "); int n2 = stdin.nextInt(); System.out.print("Enter desired operator: "); char operator = stdin.nextLine().charAt(0); switch (operator) { case '+' : System.out.println((n1 + n2)); break; case '-' : System.out.println(n1 - n2); break; case '*' : System.out.println(n1 * n2); break; case '/' : System.out.println(n1 / n2); break; default: System.out.println(“Illegal request“); }

81 Survey How many people feel they understand the switch statement? How many people feel they understand the switch statement?

82 Biggest software errors Ariane 5 rocket explosion (1996) Ariane 5 rocket explosion (1996) –Due to loss of precision converting 64-bit double to 16-bit int Pentium division error (1994) Pentium division error (1994) –Due to incomplete look-up table (like an array) Patriot-Scud missile error (1991) Patriot-Scud missile error (1991) –Rounding error on the time –The missile did not intercept an incoming Scud missile, leaving 28 dead and 98 wounded Mars Climate Orbiter (1999) Mars Climate Orbiter (1999) –Onboard used metric units; ground computer used English units AT&T long distance (1990) AT&T long distance (1990) –Wrong break statement in C code Therac-25, X-ray ( ) Therac-25, X-ray ( ) –Badly designed software led to radiation overdose in chemotherapy patients NE US power blackout (2003) NE US power blackout (2003) –Flaw in GE software contributed to it References: References:

83 Object equality

84 Testing variables for equality  Consider System.out.print("Enter an integer number: "); int n1 = stdin.nextInt(); System.out.print("Enter another integer number: "); int n2 = stdin.nextInt(); if (n1 == n2) { System.out.println("Same"); } else { System.out.println(“Different"); } What is the output if the user enters 88 and 3? What is the output if the user enters 88 both times?

85 Program Demo IntEquality IntEquality

86 Testing objects for equality  Consider String s1 = “pastel”; String s2 = s1; if (s1 == s2) { System.out.println("Same"); } else { System.out.println("Different"); }

87 Testing objects for equality  Memory looks like  The comparison is between the references!  Thus, s1 and s2 are the same (they refer to the same object) "pastel"s1 s2

88 Testing objects for equality  Consider System.out.print("Enter a string: "); String s1 = stdin.nextLine(); System.out.print("Enter another string: "); String s2 = stdin.nextLine(); if (s1 == s2) { System.out.println("Same"); } else { System.out.println("Different"); } What is the output if the user enters "pastel" both times?

89 Program Demo StringEquality StringEquality

90 Testing objects for equality  When it is executed System.out.print("Enter a string: "); String s1 = stdin.nextLine(); System.out.print("Enter another string: "); String s2 = stdin.nextLine();  Memory looks like  As a result no matter what is entered s1 and s2 are not the same They refer to different objects "pastel"s1 " "s2

91 Comparing strings for equality  Consider: String s = "hello"; String t = "hello"; System.out.println (s == t);  What gets printed? true  Consider: String u = new String("hello"); String v = new String("hello"); System.out.println (u == v);  What gets printed? false Huh? These aren’t the exact same thing

92 Program Demo StringEquality2 StringEquality2

93 Testing operators for equality  Consider System.out.print("Enter a string: "); String s1 = stdin.nextLine(); System.out.print("Enter another string: "); String s2 = stdin.nextLine(); if (s1.equals(s2)) { System.out.println("Same"); } else { System.out.println("Different"); } Tests whether s1 and s2 represent the same object Most classes have a method equals(). It compares the objects themselves, not the references.

94 All your base are belong to us Flash animation Flash animation Flash animation Flash animation Reference: us Reference: us

95 Short-circuit evaluation

96 Short-circuit evaluation  The value of a logical expression can be known before all the operands have been considered If left operand of && is false, then the value must be false If left operand of || is true, then the value must be true  Java uses these properties to make logical operations efficient Evaluates left operand before it evaluates right operand If the operator value is determined from the left operand, then the right operand is not evaluated  The operation is short-circuited

97 Short-circuit evaluation  Short-circuit evaluation is useful when some property must be true for some other expression to be evaluated  Suppose you are interested in knowing whether scoreSum divided by nbrScores is greater than value The condition can be evaluated only if nbrScores is nonzero  The following expression correctly represents the condition (nbrScores != 0) && ((scoreSum / nbrScores) > value)

98 Short-circuit evaluation  Assume we have a returnsFalse() method from a ‘foo’ object It returns false And it prints “returnsFalse() called”  And a returnsTrue() method  Consider: if ( foo.returnsFalse() && foo.returnsTrue() ) { } if ( foo.returnsTrue() && foo.returnsFalse() ) { } if ( foo.returnsFalse() || foo.returnsTrue() ) { } if ( foo.returnsTrue() || foo.returnsFalse() ) { } returnsFalse() called returnsTrue() called returnsFalse() called returnsTrue() called Output

99 Quick survey How comfortable do you feel with if’s and switches? How comfortable do you feel with if’s and switches?

100 Biology Biology Physics Physics Interdisciplinary Interdisciplinary Chemistry Chemistry Mathematics Mathematics Literature Literature Peace Peace Hygiene Hygiene Economics Economics Medicine Medicine The 2002 Ig Nobel Prizes “Courtship behavior of ostriches towards humans under farming conditions in Britain” “Demonstration of the exponential decay law using beer froth” A comprehensive study of human belly button lint Creating a four-legged periodic table “Estimation of the surface area of African elephants” “The effects of pre-existing inappropriate highlighting on reading comprehension” For creating Bow-lingual, a computerized dog-to-human translation device For creating a washing machine for cats and dogs Enron et. al. for applying imaginary numbers to the business world “(male) asymmetry in man in ancient sculpture”