cse 501n fall ‘09 05: predicates and conditional statements
DESCRIPTION
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 - PowerPoint PPT PresentationTRANSCRIPT
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
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 {
protected double balance;protected int accountNum;
…}
balance
accountNum
5360.90
104200121
4 B
yte
s8
By
tes
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 newBankAccount account = new BankAccount();
public class BankAccount {
protected double balance;protected int accountNum;
public BankAccount () {}
}
Prior to this assignment, the
object variable holds the value null
5
ObjectsIn Action!
Once created, we can use the dot operator on object variables to:Reference accessible fields of the object
Invoke (call) methods on the object
BankAccount account = new BankAccount();double money = account.balance; // Getaccount.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
Variables and AssignmentPrimitive Variables vs. Object Variables
Assignment Affects Object and Primitive Variables Differently
Your Computer’s Memory(RAM)
0
4 by
tes
int myCount;String name;
myCount = 2;name = new String(“Bob”); null
4 by
tes
“Bob”
store 2
(Memory Address)
When the constructor is invoked (called) Java
allocates memory for the object.
The object handle now refers to the newly created object.
8
Object AliasesTwo References to the Same Object
(Multiple References to
the Same Object)
String name = “Bob”;String aName;aName = name;name = null;String anotherName = “Bob”;
Your Computer’s Memory(RAM)
(Memory Address)
“Bob”
null(Memory Address)
null
“Bob”
(Memory Address)
null
9
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// Comments here.package banking;
public class BankAccount {
…
}
Must be the first line of code
(Only whitespace and comments can precede package declarations)
banking
10
Sub-Packages
Further organization by functionality
package banking.eCommerce;
public class OnlineAccount {
…
}banking
eCommerce
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// Correct importimport banking.BankAccount;
public class MyBankApp {…
}
public class MyBankApp {…
}
// Compile error!import banking.BankAccount
13
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
public class MyBankApp {
public void doSomething () {BankAccount b; // Compile Error! Not imported…
}}
fully qualified name = banking.BankAccountPackage NamePeriod Class Name
banking.BankAccount b;
14
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
MyClass
myPackage
anotherPackage
myPackage.subPackage
OtherClass
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; // trueboolean 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 true only 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 if Statement
The if statement has the following syntax:
if ( condition ) statement;
if is a Javareserved word
The condition (a.ka. predicate) must be a boolean expression. It must evaluate to either true or false.
If the condition is true, the statement is executed.If it is false, the statement is skipped.
24
Control Flow of an if statement
conditionevaluated
statement
truefalse
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
Control Flow of an if-else statement
conditionevaluated
statement1
true false
statement2
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 switch statement A ternary conditional statement
I will be in Lab now