Boolean Expressions and if-else Statements

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
C++ for Engineers and Scientists Third Edition
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
1 Relational Expressions Relational expressions: –Expressions that compare operands –Sometimes called conditions –Evaluated to yield a result –Typically.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Java Syntax and Style JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin,
Flow of Control Part 1: Selection
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Data Types, Variables, and Arithmetic JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
Boolean Expressions and if-else Statements Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006.
1 CS1001 Lecture Overview Java Programming Java Programming Arrays Arrays.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
7-1 boolean Data Type George Boole ( ) boolean variables may have only two values, true or false You define boolean fields or boolean local variables.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
The Essentials of a Java Program JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
Copyright © Curt Hill The C++ IF Statement More important details More fun Part 3.
Control Structures I Chapter 3
Java Programming Fifth Edition
Chapter 4 – C Program Control
Week 3 - Friday CS222.
Selection (also known as Branching) Jumail Bin Taliba by
Selections Java.
More important details More fun Part 3
Java Primer 1: Types, Classes and Operators
Chapter 4: Making Decisions.
CHAPTER 4 Selection CSEG1003 Introduction to Computing
Lecture 3- Decision Structures
EGR 2261 Unit 4 Control Structures I: Selection
The Selection Structure
Switch Statement.
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Topics The if Statement The if-else Statement Comparing Strings
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Chapter 4: Making Decisions.
Control Structures – Selection
Boolean Expressions And if…else Statements.
Selection Statements Chapter 5
Topics The if Statement The if-else Statement Comparing Strings
Chapter 3: Program Statements
Writing a program with conditionals
Introduction to C++ Programming
Chapter 8 JavaScript: Control Statements, Part 2
Chapter 7 Additional Control Structures
Objectives After studying this chapter, you should be able to:
Introduction to Primitive Data types
Control Structure Chapter 3.
SE1H421 Procedural Programming LECTURE 4 Operators & Conditionals (1)
The Java switch Statement
Boolean Expressions to Make Comparisons
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Unit 7 - Short-Circuit Evaluation - De Morgan’s Laws - The switch statement - Type-casting in Java - Using Math.random()
CprE 185: Intro to Problem Solving (using C)
Controlling Program Flow
Introduction to Primitive Data types
Presentation transcript:

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.

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.

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

boolean Data Type George Boole (1815 - 1864) Reserved words George Boole (1815 - 1864) 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.

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;

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

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!

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)

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) ) ...

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 ) ...

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

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.

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

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 ) ...

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

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.

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.

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

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!

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.

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.

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.

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.

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.

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.

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.