Logical Operators and Conditional statements Logical Operators Ifelse

  • Slides: 30
Download presentation
Logical Operators and Conditional statements • • Logical Operators If-else statement Block statements Nested

Logical Operators and Conditional statements • • Logical Operators If-else statement Block statements Nested if statement Data Comparisons Switch Reading for this class: L&L 5. 2 - 5. 4

Logical Operators • The following logical operators can also be used in boolean expressions:

Logical Operators • The following logical operators can also be used in boolean expressions: ! && || Logical NOT Logical AND Logical OR • They operate on boolean operands and produce boolean results – Logical NOT is a unary operator (it operates on one operand) – Logical AND and logical OR are binary operators (each operates on two operands) 2

Logical NOT • The logical NOT operation is also called logical negation or logical

Logical NOT • The logical NOT operation is also called logical negation or logical complement • If some boolean condition a is true, then !a is false; • If a is false, then !a is true • Logical operations can be shown with a truth table a !a true false true 3

Logical AND and Logical OR • The logical AND expression a && b is

Logical AND and Logical OR • 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 both are true, and false otherwise 4

Logical Operators • A truth table shows all possible true-false combinations of the terms

Logical Operators • A truth table shows all possible true-false combinations of the terms • Since && and || each have two operands, there are four possible combinations of conditions a and b a b true false a && b a || b true false true false

Short-Circuited Operators • The processing of logical AND and logical OR is “short-circuited” •

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 if (count != 0 && total/count > MAX) System. out. println ("Testing…"); • This coding technique must be used carefully

The if-else Statement • An else clause can be added to an if statement

The if-else Statement • An else clause can be added to an if statement to make an if-else statement if ( condition ) statement 1; else statement 2; • If the condition is true, statement 1 is executed; if the condition is false, statement 2 is executed • One or the other will be executed, but not both • See Wages. java (page 211) 7

Indentation Revisited • Remember that indentation is for the human reader and is ignored

Indentation Revisited • Remember that indentation is for the human reader and is ignored by the Java compiler if (total > MAX) System. out. println ("Error!!"); error. Count++; Despite what is implied by the indentation, the increment will occur whether the if condition is true or not, as follows: if (total > MAX) System. out. println ("Error!!"); error. Count++;

Block Statements • Several statements can be grouped into a block statement delimited by

Block Statements • Several statements can be grouped into a block statement delimited by braces if (total > MAX) { System. out. println ("Error!!"); error. Count++; } Now the increment will only occur when the if condition is true • A block statement can be used wherever a statement is called for in the Java syntax 9

Block Statements • In an if-else statement, the if portion, or the else portion,

Block Statements • In an if-else statement, the if portion, or the else portion, or both, could be block statements if (total > MAX) { System. out. println ("Error!!"); error. Count++; } else { System. out. println ("Total: " + total); current = total*2; } 10

The Conditional Operator • Java has a conditional operator that uses a boolean condition

The Conditional Operator • Java has a conditional operator that uses a boolean condition to determine which of two expressions is evaluated • Its syntax is: condition ? expression 1 : expression 2 • If the condition is true, expression 1 is evaluated; if it is false, expression 2 is evaluated • The value of the entire conditional operator is the value of the selected expression 11

The Conditional Operator • The conditional operator is similar to an if-else statement, except

The Conditional Operator • The conditional operator is similar to an if-else statement, except that it is an expression that returns a single value • For example: larger = ((num 1 > num 2) ? num 1 : num 2); • If num 1 is greater than num 2, then num 1 is assigned to larger; otherwise, num 2 is assigned to larger • The conditional operator is ternary because it requires three operands: a condition and two alternative values 12

Nested if Statements • The statement executed as a result of an if statement

Nested if Statements • The statement executed as a result of an if statement or an else clause can be another if statement • These are called nested if statements • An else clause is matched to the last unmatched if (no matter what the indentation implies) • Braces can be used to specify the if statement to which an else clause belongs • See Min. Of. Three. java (page 219) 13

Comparing Data • When comparing data using boolean expressions, it's important to understand the

Comparing Data • When comparing data using boolean expressions, 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 strings (alphabetical order) Comparing object vs. comparing object references

Comparing Float Values • You should rarely use the equality operator (==) when comparing

Comparing Float Values • 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 • Computations often result in slight differences that may be irrelevant • In many situations, you might consider two floating point numbers to be "close enough" even if they aren't exactly equal

Comparing Float Values • To determine the equality of two floats, you may want

Comparing Float Values • To determine the equality of two floats, you may want to use the following technique: if (Math. abs(f 1 - f 2) < TOLERANCE) System. out. println ("Essentially equal"); • If the absolute value of the difference between the two floating point values is less than the tolerance, they are considered to be equal • The tolerance could be set to any appropriate level, such as 0. 000001

Comparing Characters • As we've discussed, Java character data is based on the Unicode

Comparing Characters • As we've discussed, Java character data is based on the Unicode character set • Unicode assigns a particular numeric value to each character and this creates an ordering of characters • We can use relational operators on character data based on this ordering • For example, the character ‘A' is less than the character 'J' because it comes before it in the Unicode character set • L&L Appendix C provides an overview of Unicode

Comparing Characters • In Unicode, the digit characters (0 -9) are contiguous and in

Comparing Characters • In Unicode, the digit characters (0 -9) are contiguous and in order of their numerical value • Likewise, the uppercase letters (A-Z) and lowercase letters (a-z) are contiguous and in alphabetical order Characters 0– 9 A–Z a–z Unicode Values 48 through 57 65 through 90 97 through 122

Comparing Characters • Therefore, if we want to base a decision in our program

Comparing Characters • Therefore, if we want to base a decision in our program on whether a character is a digit or not, we can use the following code: if (character >= ‘ 0’ && character <= ‘ 9’) System. out. println (“Yes, it’s a digit!”); • We can also check for a valid upper case alphabetic character as follows: if (character >= ‘A’ && character <= ‘Z’) System. out. println (“It’s a capital letter!”);

Comparing Strings • Remember that in Java a string is an object • We

Comparing Strings • Remember that in Java a string is an object • We cannot use the == operator to determine if the values of two strings are identical (character by character) • The equals method can be called with strings to determine if two strings contain exactly the same characters in the same order • The equals method returns a boolean result if (name 1. equals(name 2)) System. out. println ("Same name");

Comparing Strings • We cannot use the relational operators to compare strings • The

Comparing Strings • We cannot use the relational operators to compare strings • The String class contains a method called compare. To to determine if one string comes before another • A call to name 1. compare. To(name 2) – returns zero if name 1 and name 2 are equal (contain the same characters) – returns a negative value if name 1 is less than name 2 – returns a positive value if name 1 is greater than name 2

Comparing Strings if (name 1. compare. To(name 2) < 0) System. out. println (name

Comparing Strings if (name 1. compare. To(name 2) < 0) System. out. println (name 1 + "comes first"); else if (name 1. compare. To(name 2) == 0) System. out. println ("Same name"); else System. out. println (name 2 + "comes first"); • Because comparing characters and strings is based on a character set, it is called a lexicographic ordering

Lexicographic Ordering • Lexicographic ordering is not strictly alphabetical with mixed uppercase and lowercase

Lexicographic Ordering • Lexicographic ordering is not strictly alphabetical with mixed uppercase and lowercase characters • For example, the string "Great" comes before the string "fantastic" because in Unicode the uppercase letters have lower values than the lowercase letters. Therefore, ‘G’ is less than ‘f’ • Also, short strings come before longer strings with the same prefix (lexicographically) • Therefore "book" comes before "bookcase"

Comparing Objects • The == operator can be applied to objects – it returns

Comparing Objects • The == operator can be applied to objects – it returns true if the two references are aliases of each other • The equals method is defined for all objects, but unless you redefine it when you 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 under whatever conditions are appropriate • It has been redefined in the String class to compare the characters in the two strings

The switch Statement • The switch statement provides another way to decide which statement

The switch Statement • The switch statement provides another way to decide which statement to execute next • The switch statement evaluates an integral expression (int or char only), then attempts to match the result to one of several possible cases • Each case contains a value and a statement list • The flow of control transfers to the statement list associated with the first case value that matches 25

The switch Statement • The general syntax of a switch statement is: switch and

The switch Statement • The general syntax of a switch statement is: switch and case are reserved words switch ( expression ) { case value 1 : statement-list 1 case value 2 : statement-list 2 case value 3 : statement-list 3 case. . . } If expression matches value 2, control jumps to here

The switch Statement • Often a break statement is used as the last statement

The switch Statement • Often a break statement is used as the last statement in each case's statement list • A break statement causes control to transfer to the end of the switch statement • If a break statement is not used, the flow of control will continue into the next case • Sometimes this may be appropriate, but often we only want to execute the statements associated with one case

The switch Statement • An example of a switch statement: switch (option) { case

The switch Statement • An example of a switch statement: switch (option) { case 'A': a. Count++; break; case 'B': b. Count++; break; case 'C': c. Count++; break; }

The switch Statement • A switch statement can have an optional default case •

The switch Statement • A switch statement can have an optional default case • The default case has no associated value and simply uses the reserved word default • If there is a default case and no other value matches, control will transfer to the default statement list • If there is no default case and no other value matches, control falls through to the statement after the switch without executing any statements

The switch Statement • An example of a switch statement using default: switch (option)

The switch Statement • An example of a switch statement using default: switch (option) { case 'A': a. Count++; break; case 'B': b. Count++; break; default: error. Count++; break; }