Presentation is loading. Please wait.

Presentation is loading. Please wait.

Boolean Expressions and if-else Statements

Similar presentations


Presentation on theme: "Boolean Expressions and if-else Statements"— Presentation transcript:

1 Boolean Expressions and if-else Statements
Java Methods TM Maria Litvin Gary Litvin An Introduction to Object-Oriented Programming if (chapter == 7) Boolean Expressions and if-else Statements C (and early C++) didn’t have boolean data type: boolean values were represented as integers: 1 for true, 0 for false. This could lead to obscure code, such as if (a - b)... meaning if (a - b != 0)... Later the bool type was added to C++. It is better to keep booleans and integers separate. In Java the reserved word is boolean. Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.

2 Objectives: Learn about the boolean data type
Learn the syntax for if-else statements Learn about relational and logical operators, De Morgan’s laws, short-circuit evaluation Learn when to use nested if-else statements, if-else-if sequences, the switch statement Another objective is to discuss team development and illustrate software reusability in the context of a simple but realistic case study, the Craps applet.

3 if-else Statement if ( <condition> ) { < statements > }
< other statements > if ( <condition> ) { < statements > } When the if or else clause contains only one statement, the braces are optional, but it is safer to always keep them. With braces it is also easier to add a statement to an if or else clause. else clause is optional

4 boolean Data Type George Boole (1815 - 1864)
Reserved words George Boole ( ) boolean variables may have only two values, true or false. You define boolean fields or boolean local variables the same way as other variables: private boolean hasMiddleName; boolean isRolling = false; boolean true false There is no point, really, in using boolean symbolic constants because you can just use true and false in the code. George Boole is a British mathematician who studied properties of formal logic.

5 Boolean Expressions In if (<condition> ) <condition> is a Boolean expression. A Boolean expression evaluates to either true or false. Boolean expressions are written using boolean variables and relational and logical operators. You can assign the result of an arithmetic expression to an int or double variable. Similarly, you can assign the result of a Boolean expression to a boolean variable. For example, rather than writing boolean exceedsLimit; if (x > limit) exceedsLimit = true; else exceedsLimit = false; you can write simply: boolean exceedsLimit = x > limit;

6 Relational Operators <, >, <=, >=, ==, != is equal to
<, >, <=, >=, ==, != is equal to is NOT equal to = is for assignment, == is for comparison.

7 Relational Operators (cont’d)
Apply to numbers or chars: if ( x <= y ) ... if ( a != 0 ) ... if ( letter == ‘Y’ ) ... Do not use == or != with doubles because they may have rounding errors double x = 7.0; double y = 3.5; if (x / y == 2.0) ... <= and >= are OK with doubles, because in this type of comparison the program usually doesn’t care about the situation when the numbers are exactly equal. May be false!

8 Relational Operators (cont’d)
Be careful using == and != with objects (e.g., Strings): they compare references (addresses) rather than values (the contents) String cmd = console.readLine(); if ( cmd == "Help" ) ... In Java you have to always be aware when two variables refer to the same object and when to two different objects, perhaps with equal values. Wrong! (always false)

9 Relational Operators (cont’d)
Use the equals method to compare Strings: or String cmd = console.readLine(); if ( cmd.equals ("Help") ) ... The “value” may be defined differently for different types of objects. For strings, the value is the characters in the string; for “employees,” equals may mean the same social security number. A programmer defines the meaning of “equals” for the objects of his or her class. if ( "Help".equals (cmd) ) ...

10 Relational Operators (cont’d)
Use the == or != operator with strings and other objects when you want to know whether or not this is exactly the same object. Also use == or != to compare to null: Comparison to null works for all types of objects. String text = file.readLine(); if ( text != null ) ...

11 Logical Operators &&, ||, ! and or not
&&, ||, ! and or Logical operators parallel those in formal logic. not

12 Logical Operators (cont’d)
( condition1 && condition2 ) is true if and only if both condition1 and condition2 are true ( condition1 || condition2 ) is true if and only if condition1 or condition2 (or both) are true !condition1 is true if and only if condition1 is false Note that || is inclusive or: either one or the other or both.

13 Logical Operators (cont’d)
&&, ||, and ! obey the laws of formal logic called De Morgan's laws: Example: if ( ! ( x => -10 && x <= 10 ) ) ... if ( x < -10 || x > 10 ) ... ! (p && q) == ( !p || !q ) ! (p || q) == ( !p && !q ) In formal logic there is a duality principle: if you take an equality made with &&, ||, and ! and replace all && with || and vice versa, you’ll get another equality. De Morgan’s laws are dual. Easier to read

14 Ranks of Operators ! -(unary) ++ -- (cast) * / % + -
* / % < <= > >= == != && || Thus you can string several && with no parentheses: a && b && c. The rank of || is lower than &&, so a && b || c && d is the same as (a && b) || (c && d), but the expression is more readable with parentheses. Easier to read if ( ( ( year % 4 ) == 0 ) && ( month == 2 ) ) ... if ( year % 4 == 0 && month == 2 ) ...

15 Short-Circuit Evaluation
if (condition1 && condition2) ... If condition1 is false, condition2 is not evaluated (the result is false anyway) if (condition1 || condition2) ... If condition1 is true, condition2 is not evaluated (the result is true anyway) Java has another set of operators, & (and), | (or), ~ (not), and ^ (xor). These are bitwise logical operators that work on bit patterns. Unfortunately, these can be also used with boolean variables. When applied to booleans, & and | do NOT follow the short-circuit evaluation rule. So be very careful to make sure you have && and ||. if ( x >= 0 && Math.sqrt (x) < 15.0) ... Always OK: won’t get to sqrt if x < 0

16 Nested if-else if ("forward".equals(cmd)) { if (slide >= numSlides)
beep.play(); else slide++; } if (slide <= 1) slide--; If you nest if-else to more than two levels, it may be hard to read. Reconsider your design: perhaps you need helper methods that handle different cases.

17 if-else-if if (drinkSize.equals(”Large")) { price += 1.39; }
else if (drinkSize.equals("Medium")) price += 1.19; else // if "Small" drink size price += 0.99; In the if-else-if sequence, the second if-else is actually nested within the preceding else clause, but this layout is conventional and more readable. The sequence remains readable even if it is quite long.

18 Common if-else Errors if (...) ; { statements; ... } Extra semicolon
It is safer to always use braces in if-else if (...) statement1; statement2; ... if (...) statement1; else statement2; ... With the extra semicolon, the code will executed as follows: if (...) do nothing perform statements in braces (unconditionally) The second example of missing braces is known as a “dangling” else: the else clause actually pairs with the inner if, not the outer if as the programmer intended and as the indentation implied. Missing braces

19 The switch Statement switch case default break switch (expression) {
case value1: ... break; case value2: default: } Reserved words switch case default break There is a legend in software folklore that a missing break in a program caused the whole telephone grid of New York to go down, costing millions of dollars. You have to be careful about breaks; they are among the many opportunities to make a stupid mistake not caught by the compiler. Attention to detail is key. Don’t forget breaks!

20 The Craps Applet The purpose of this case study is both to practice with if-else and boolean expressions and to discuss OO design, team development, and software reusability.

21 The Craps Applet (cont’d)
Your job Your assignment is placed into the context of a larger team effort. All you need to know is the public interface for your class CrapsGame, i.e., its two public methods.

22 The Craps Applet (cont’d)
Step 1: Test your CrapsGame class separately using the simple applet CrapsOne provided to you. It would take a long time to test your class in the real applet, with random numbers of points coming up on the dice. You want a more controlled test, in which you can specify the outcome of a “dice roll,” and you need to run through all relevant sequences of “roll” outcomes.

23 The Craps Applet (cont’d)
Step 2: Use your CrapsGame in the CrapsStats application. Note how the CrapsGame class is used first in the Craps applet, then in the CrapsStats application. This is a simple example of reusability.

24 The Craps Applet (cont’d)
Step 3: Finish the RollingDie class (the drawDots method). Step 4: Integrate CrapsGame and RollingDie into the Craps applet. Step 3 is here to let you use a switch.

25 Review: What are the possible values of a boolean variable?
What operators are used to compare values of numbers and chars? How can you test whether two Strings have the same values? Which binary operators have higher rank (are executed first), relational or logical? What are the possible values of a boolean variable? true, false What operators are used to compare values of numbers and chars? Relational operators <, <=, >, >=, ==, and !=. How can you test whether two Strings have the same values? if (str1.equals(str2)) ... Which binary operators have the higher rank (are executed first), relational or logical? Relational. First arithmetic (*, /, and %, then + and -), then relational, and logical last.

26 Review (cont’d): Can you have an if statement without an else?
What are De Morgan’s laws? Explain short-circuit evaluation. How long can an if-else-if sequence be? What are breaks used for in switch? What happens if you forget one? Can the same case in a switch have two breaks? Can you have an if statement without an else? Yes, else is optional. What are De Morgan’s laws? ! (a && b) is the same as (!a || !b); ! (a || b) is the same as (!a && !b); Explain short-circuit evaluation. In a sequence of && operators, once you encounter one condition that is false, the rest are not evaluated and the result is set to false. Likewise, in a sequence of || operators, once you encounter a condition that is true, the rest are not evaluated and the result is set to true. How long can an if-else-if sequence be? As long as you need, usually quite readable. But if it is very long, you might consider a switch. What are breaks used for in a switch? What happens if you forget one? A break instructs the code to break out of the switch and go to the statement after the switch. If a break is missing, the code “falls through” and continues with the statements in the next case. Can the same case in a switch have two breaks? A case may have several breaks, but all except the last one must be inside an if or else.


Download ppt "Boolean Expressions and if-else Statements"

Similar presentations


Ads by Google