350 likes | 473 Views
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
E N D
CSE 501NFall ‘0905: 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 • Relational Operators • Combined Boolean Operators • Conditional Statements • if / else • Quiz #1
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;
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();
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);
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; }
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”
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”
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 { … }
eCommerce Sub-Packages • Further organization by functionality package banking.eCommerce; public class OnlineAccount { … } banking
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 ]
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 { … }
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;
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
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
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
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
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;
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
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
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);
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
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;
condition evaluated true false statement Control Flow of an if statement
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
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;
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
condition evaluated true false statement1 statement2 Control Flow of an if-elsestatement
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?
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++; }
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; }
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. */
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;
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;
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