1 CS257 Computer Science I Kevin Sahr, PhD Lecture 6: Comparing Data and Complex Boolean Expressions Comparing Data 2 When comparing data it's important to understand the nuances of certain data types Let's examine some key situations: Comparing floating point values for equality Comparing characters Comparing objects (vs. comparing object references) Comparing Strings Comparing Floating Point Values 3 You should rarely use the equality operator (==) when comparing two floating point values (float or double) Two floating point values are equal only if their underlying binary representations match exactly But floating point representations actually only store approximations to real numbers Floating point computations often introduce very small errors known as rounding errors Therefore, in many situations, we consider two floating point numbers to be equal if they differ by some very small amount, even if they aren't exactly equal Comparing Float Values 4 To determine the equality of two floats, the following technique is often used: if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal"); If the difference between the two floating point values is less than the tolerance, they are considered to be equal The tolerance should be set to an appropriate level for your problem, such as 0.0000001
Representing Money 5 In applications where rounding error is unacceptable values are often represented internally using appropriately scaled integers For example, monetary values might be represented as an integer number of 1/100th s of a cent EX: $123.45 could be stored internally as the integer value 1234500 converted to/from floating point values for output and input If values are represented this way, they can be compared using == (just like any other integers) Comparing Characters 6 Java character data uses the Unicode character set Unicode specifies a particular numeric value for each character, and therefore an ordering We can use relational operators on character data based on the Unicode ordering EX: the character '+' is less than the character 'J' because the numeric value of '+' comes before the numeric value of 'J' in the Unicode character set Comparing Characters 7 It is often useful to note that in Unicode the digit characters (0-9) are contiguous and in order Likewise, the uppercase letters (A-Z) and lowercase letters (a-z) are contiguous and in order Characters Unicode Values 0 9 48 through 57 A Z 65 through 90 a z 97 through 122 Comparing Objects 8 The == operator can be applied to objects but it returns true only if the two references are aliases of each other (i.e., they refer to the same object) more often we want to compare objects based on their internal values The equals method is defined for all objects, but unless we redefine it when we write a class, it has the same semantics as the == operator When you write a class, you can redefine the equals method to return true or false under whatever conditions are appropriate for instances of your class
Comparing Strings 9 Remember that in Java a String is an object The equals method can be called with Strings to determine if they contain exactly the same characters in the same order The equals method returns a boolean result if (name1.equals(name2)) System.out.println ("Same name"); Comparing Strings Since Strings are objects, we cannot use the relational operators to compare strings 10 using the relational operators will compare the addresses of the Strings, which is probably not what we want! The String class contains a method called compareto to determine if one string comes before another Strings are compared based on lexicographic ordering The characters in the String are compared from firstto-last until a difference is found compareto Method for Strings 11 The method invocation name1.compareto(name2) returns zero if name1 and name2 are equal (contain the same characters) returns a negative value if name1 is less than name2 returns a positive value if name1 is greater than name2 EX: if (name1.compareto(name2) == 0) System.out.println ("Same name"); else if (name1.compareto(name2) < 0) System.out.println (name1 + "comes first"); else System.out.println (name2 + "comes first"); Lexicographic Ordering 12 Lexicographic ordering is not strictly alphabetical when uppercase and lowercase characters are mixed For example, the string "Great" comes before the string "fantastic" because all of the uppercase letters come before all of the lowercase letters in Unicode Also, short strings lexicographically come before longer strings with the same prefix Therefore "book" comes before "bookcase"
Complex Boolean Expressions 13 So far we have only worked with simple boolean simple boolean do not contain logical operators EX: num1 <= num2 name1.equals(name2) atree.getisalive() somebooleanvariable Simple boolean can be combined using logical operators to create complex boolean Logical Operators 14 The Java logical operators are:! Logical NOT && Logical AND Logical OR logical operators take boolean operands Logical NOT is a unary operator (it operates on one operand) Logical AND and logical OR are binary operators (each operates on two operands) involving logical operators are boolean they evaluate to either true or false Logical NOT 15 The logical NOT operation is also called logical negation or logical complement If some boolean expression a is true, then!a is false; if a is false, then!a is true Truth Tables 16 logical can be completely defined using a truth table a truth table specifies all possible values for the operands and the resulting value of the logical expression here is the truth table for logical NOT: a!a true false false true
Logical AND and Logical OR 17 The logical AND expression a && b is true if both a and b are true, and false otherwise The logical OR expression a b is true if a or b or both are true, and false otherwise Logical Operators 18 A truth table shows all possible true/false combinations of the operands Since && and each have two operands, there are four possible combinations of conditions a and b here are the combined truth tables for AND and OR: a b a && b a b true true true true true false false true false true false true false false false false Logical Operator Precedence 19 Expressions that use logical operators can form complex conditions. EX: if (total < MAX+5 &&!found) System.out.println ("Processing "); All logical operators have lower precedence than the relational operators Logical NOT has higher precedence than logical AND and logical OR Logical AND has higher precedence than logical OR Parenthesis can always be used to override precedence (or to minimize confusion) Truth Tables 20 Specific complex boolean can be evaluated using truth tables EX: total < MAX found!found total < MAX &&!found false false true false false true false false true false true true true true false false
Steps: First Create the Columns 1. Create a column for the expression to be evaluated 2. Find the logical operator in the expression with the lowest precedence 3. Create a column to the left of the expression for each of the operands of that logical operator 4. For each of the newly created columns that are themselves complex boolean, repeat steps 2 and 3 for that expression 5. Continue until all operands are simple boolean 6. Rearrange the columns (if needed) so that the columns containing simple boolean are the left-most columns 21 Checking the Columns 22 You now have all the columns The rightmost column should contain the expression being evaluated The left-most columns should consist of all the simple boolean contained in the expression being evaluated each column in between should provide the truth values for a single logical operator involving operands to the left of it Steps: Then Create the Rows 23 1. The number of rows will be the number of unique combinations of the simple boolean 1. N boolean requires 2 N rows 2. Fill-in the columns beneath the simple boolean with all possible unique true/false combinations of those 3. Fill-in the remainder of each row from left-to-right by evaluating each column s expression using the operand truth values given to the left on the same row Creating a Truth Table 24 Example: total < MAX found!found total < MAX &&!found false false true false false true false false true false true true true true false false
Short-Circuited Operators The processing of logical AND and logical OR is short-circuited If the left operand is sufficient to determine the result, the right operand is not evaluated EX: if (count!= 0 && total/count > MAX) System.out.println ("Testing "); In this example if count is 0, then the first operand of && is false, and therefore the entire complex boolean expression is false 25 doesn t matter whether or not total/count > MAX This type of processing must be used consciously and carefully! Lecture 6 Vocabulary 26 rounding error lexicographic ordering simple boolean logical operators complex boolean unary operator binary operator truth table short-circuited operators