1 / 35

CSE 501N Fall ‘09 05: Predicates and Conditional Statements

CSE 501N Fall ‘09 05: Predicates and Conditional Statements. 10 September 2009 Nick Leidenfrost. Lecture Outline. Review Classes & Objects Access Modifiers Object Variables vs. Primitive Variables Logical Operands and Boolean Expressions Zooming Out: Packages & Libraries

Download Presentation

CSE 501N Fall ‘09 05: Predicates and Conditional Statements

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSE 501NFall ‘0905: Predicates and Conditional Statements 10 September 2009 Nick Leidenfrost

  2. Lecture Outline • Review • Classes & Objects • Access Modifiers • Object Variables vs. Primitive Variables • Logical Operands and Boolean Expressions • Zooming Out: Packages & Libraries • Relational Operators • Combined Boolean Operators • Conditional Statements • if / else • Quiz #1

  3. balance accountNum 5360.90 8 Bytes 104200121 4 Bytes Objects • Objects are instances, or examples of a class • Each object has memory allocated for it to store all of the fields (instance variables) defined in the class • We declare object variables using the class name as the type: public class BankAccount { protecteddouble balance; protectedint accountNum; … } BankAccount account;

  4. ObjectsCreation • Objects are created and initialized by constructors • Memory is allocated for object, constructor body is run for programmer-defined initialization • A default constructor is supplied by Java if you don’t define one • The constructor is invoked with the keyword new public class BankAccount { protecteddouble balance; protected int accountNum; public BankAccount () { } } Prior to this assignment, the object variable holds the value null BankAccount account = new BankAccount();

  5. ObjectsIn Action! • Once created, we can use the dot operatoron object variables to: • Reference accessible fields of the object • Invoke (call) methods on the object BankAccount account = new BankAccount(); double money = account.balance; // Get account.balance = money+100000; // Set account.withdraw(10000);

  6. ObjectsUsing Members (Fields / Methods) • Inside a class’ methods and constructor, members can be referenced or invoked directly, without the dot operator public double withdraw (double amount) { balance -= amount; // - or – setBalance(balance – amount); } public void setBalance (double newBalance) { balance = newBalance; }

  7. Your Computer’s Memory (RAM) Variables and AssignmentPrimitive Variables vs. Object Variables • Assignment Affects Object and Primitive Variables Differently When the constructor is invoked (called) Java allocates memory for the object. int myCount; String name; myCount = 2; name = new String(“Bob”); The object handle now refers to the newly created object. 0 2 4 bytes store null (Memory Address) 4 bytes “Bob”

  8. Your Computer’s Memory (RAM) Object AliasesTwo References to the Same Object • (Multiple References to the Same Object) (Memory Address) null String name = “Bob”; String aName; aName = name; name = null; String anotherName = “Bob”; “Bob” null (Memory Address) null (Memory Address) “Bob”

  9. banking PackagesThe Final Frontier • What are they and why should we create them? • Collection of classes, organized by functionality • Define encapsulation at a Class Level • Aided by access modifiers • Package names begin with lowercase letters by convention • Must be inside a directory (folder) of the same name Must be the first line of code (Only whitespace and comments can precede package declarations) // Comments here. package banking; public class BankAccount { … }

  10. eCommerce Sub-Packages • Further organization by functionality package banking.eCommerce; public class OnlineAccount { … } banking

  11. Libraries • A Library is really nothing more than a package that was written by somebody else • Usually compressed in a .jar file • Like a .zip file or a .tar file • Jar: Java Archive • The .jar file that contains the library is full of classfiles • (a .class file is the result when you compile a class / a .java file) [ Extracting rt.jar / Sun Java Library Documentation ]

  12. Using Libraries: The import Statement • The import statement tells Java you want to use an external Class or Package • Must precede all class declarations • … but after package declaration • Terminated with a semicolon public class MyBankApp { … } // Compile error! import banking.BankAccount // Correct import import banking.BankAccount; public class MyBankApp { … }

  13. Package Name Period Class Name Using Libraries …with fully qualified classnames • Instead of importing, we can refer to external classes explicitly with their fully qualified name • This is perfectly legal, but makes code slightly more difficult to read • Not as good from a style point of view as using import fully qualified name = banking.BankAccount public class MyBankApp { public void doSomething () { BankAccount b; // Compile Error! Not imported … } } banking.BankAccount b;

  14. MyClass OtherClass myPackage myPackage.subPackage anotherPackage Access Modifiers • Define who can use class members (fields & methods) • Allow us to encapsulate data • public • Everyone, and their dog • protected • Subclasses of this class, Classes in my package • Note:Subclasses can be in a different package! (Not shown in visual) • (not specified: default, a.k.a. package protected) • Classes in my package • private • Only other instances of this class

  15. Boolean Operators & ExpressionsReview • Boolean Operators ! // Not – Negate the value of the operator && // And – true if both operators are true || // Or – true if one or both operators are true ^ /* Exclusive Or (xor) – true if exactly one operator is true */ boolean a = true; boolean b = false; boolean negated = !a; boolean anded = a && b; boolean ored = a || b; boolean exored = a ^ b; // false // false // true // true

  16. Boolean Operators & Expressions • Boolean operators are used to produce a logical result from boolean-valued operands • Like arithmetic expressions (*+/%), boolean expressions can be complex • E.g. isDone || !found && atEnd • Like arithmetic operands, boolean operands have precedence • Highest ! && ^ || Lowest • … precedence can be overridden with parenthesis: • E.g. (isDone || !found) && atEnd

  17. Relational Operators • Used for comparing variables • Evaluate to a boolean result == // Equal to != // Not equal to < // Less than > // Greater than <= // Less than or equal to >= // Greater than or equal to int a = 1; int b = 2; boolean equal = (a == b); boolean lessThan = (a < b); // false // true

  18. Relational Operators • … have a lower precedence than arithmetic operators • Can be combined with boolean operators we already know to form complex expressions: int a = 1; int b = 2; boolean equal = a == b-1; // true boolean lessThan = a < b-1; // false int a = 1; int b = 2; boolean lessThanOrEqual = a < b || a == b; boolean lessThanEqual = a <= b;

  19. Relational OperatorsFloating Point Numbers • Computations often result in slight differences that may be irrelevant • The == operator only returns true if floating point numbers are exactly equal • In many situations, you might consider two floating point numbers to be "close enough" even if they aren't exactly equal

  20. Comparing Floating Point Values • To determine the equality of two doubles or floats, you may want to use the following technique: boolean equal = (Math.abs(f1 - f2) < TOLERANCE); • If 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

  21. Comparing Objects.equals (Pronounced “Dot equals”) • When comparing variables which are objects, the == operator compares the object references stored by the variables • trueonly when variables are aliases of each other • Two objects may be semantically equivalent, but not the same object • .equals allows a programmer to define equality String name = “Bob”; String otherName = “Bob”; boolean sameObject = (name == otherName); boolean equivalent = name.equals(otherName);

  22. Flow of Control • Flow of Control (a.k.a. control flow) is a fancy way of referring to the order of execution of statements • The order of statement execution through a method is linear - one statement after another in sequence • Some programming statements allow us to: • decide whether or not to execute a particular statement • execute a statement over and over, repetitively • These decisions are based on boolean expressions (or conditions) that evaluate to true or false

  23. The condition (a.ka. predicate) must be a boolean expression. It must evaluate to either true or false. if is a Java reserved word If the condition is true, the statement is executed. If it is false, the statement is skipped. The if Statement • The if statement has the following syntax: if ( condition ) statement;

  24. condition evaluated true false statement Control Flow of an if statement

  25. The if Statement • An example of an if statement: if (balance > amount) balance = balance - amount; System.out.println (amount + “ was withdrawn.”); • First the condition is evaluated -- the value of balance is either greater than amount, or it is not • If the condition is true, the assignment statement is executed -- if it isn’t, it is skipped. • Either way, the call to println is executed next

  26. Conditional Statements: Indentation • The statement controlled by the if statement is indented to indicate that relationship • The use of a consistent indentation style makes a program easier to read and understand • Although it makes no difference to the compiler, proper indentation is crucial if (balance > amount) balance-= amount; if (balance > amount) balance-= amount;

  27. The if-else Statement • An else clause can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2; • If the condition is true, statement1 is executed; if the condition is false, statement2 is executed • One or the other will be executed, but not both

  28. condition evaluated true false statement1 statement2 Control Flow of an if-elsestatement

  29. Indentation Revisited • Remember that indentation is for the human reader, and is ignored by the computer if (balance < amount) System.out.println ("Error!!"); errorCount++; Despite what is implied by the indentation, the increment will occur whether the condition is true or not So what if we want to conditionally execute multiple statements?

  30. Block Statements • Several statements can be grouped together into a block statement delimited by curly braces (‘{‘ and ‘}’) • A block statement can be used wherever a statement is called for in the Java syntax rules if (balance < amount){ System.out.println ("Error!!"); errorCount++; }

  31. Block Statements • In an if-else statement, the if portion, or the else portion, or both, could be block statements public double withdraw (double amount) { if (balance < amount){ System.out.println(“Error!!”); return 0; } else { System.out.println("Total: " + total); balance -= amount; } return amount; }

  32. Blocks Statements Scope • The term ‘scope’ describes the relevance of variables at a particular place in program execution • Variables declared in blocks leave scope (“die”) when the block closes if (balance < amount){ double shortage = amount – balance; System.out.println(“Error!”); } System.out.println(“Lacking “ + shortage); /* Compile error: ‘shortage’ has already left scope. */

  33. Nested if Statements • The statement executed as a result of an if statement or else clause could be another if statement • These are called nested if statements if (balance < amount) if (overdraftProtection()) borrow(amount-balance); else balance -= amount;

  34. 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 if (balance < amount) { if (overdraftProtection()) borrow(amount-balance); } else balance -= amount;

  35. Questions? • Quiz #1 • Lab 1.5 Assigned • Deals with: • String Manipulation • Interacting with Objects • Due Next Tuesday • Next time: • The switchstatement • A ternary conditional statement • I will be in Lab now

More Related