CSE 501N Fall ‘08 04: Predicates and Conditional Statements
Download
Report
Transcript CSE 501N Fall ‘08 04: Predicates and Conditional Statements
CSE 501N
Fall ‘09
05: Predicates and Conditional
Statements
10 September 2009
Nick Leidenfrost
1
Lecture Outline
Review
Classes & Objects
Access Modifiers
Object Variables vs. Primitive Variables
Logical Operands and Boolean Expressions
Zooming Out: Packages & Libraries
Relational Operators
Combined
Conditional Statements
if
Boolean Operators
/ else
Quiz #1
2
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
public class BankAccount {
}
balance
8 Bytes
…
5360.90
accountNum
4 Bytes
protected double balance;
protected int accountNum;
104200121
We declare object variables using the class name
as the type:
BankAccount account;
3
Objects
Creation
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
public class BankAccount {
protected double balance;
protected int accountNum;
public BankAccount Prior
() to
{ this
}
assignment, the
}
object variable holds
the value null
The constructor is invoked with the keyword new
BankAccount account = new BankAccount();
4
Objects
In Action!
Once created, we can use the dot operator on
object variables to:
Reference accessible fields of the object
BankAccount account = new BankAccount();
double money = account.balance;
// Get
account.balance = money+100000;
// Set
Invoke
(call) methods on the object
account.withdraw(10000);
5
Objects
Using 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;
}
6
Variables and Assignment
Primitive Variables vs. Object Variables
Assignment Affects Object and Primitive
Variables Differently
int myCount;
String name;
Your Computer’s Memory
When the constructor is
(RAM)
invoked (called) Java
allocates
memory
fornow
the refers to
The object
handle
object.
2
0
the
store newly created object.
myCount = 2;
name = new String(“Bob”);
4 bytes 4 bytes
(Memory Address)
null
“Bob”
7
Object Aliases
Two 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)
null
(Memory Address)
“Bob”
(Memory Address)
null
(Memory Address)
null
“Bob”
8
Packages
The Final Frontier
What are they and why should we create them?
Collection of classes, organized by functionality
Define encapsulation
a Class
Must be theatfirst
line ofLevel
code
(Only
whitespace and
Aided by access
modifiers
comments can precede
namespackage
begindeclarations)
with lowercase
Package
letters by
convention
Must be inside a directory (folder) of the same name
// Comments here.
package banking;
public class BankAccount {
…
}
banking
9
Sub-Packages
Further organization by functionality
package banking.eCommerce;
public class OnlineAccount {
…
}
eCommerce
banking
10
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 ]
11
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 import
import banking.BankAccount;
public class MyBankApp {
…
}
public class MyBankApp {
…
}
// Compile error!
import banking.BankAccount
12
Using Libraries
…with fully qualified classnames
Instead of importing, we can refer to external
classes explicitly with their fully qualified name
fully qualified name = banking.BankAccount
public class MyBankApp {
Package Name
Period Class Name
public void doSomething () {
BankAccount b; // Compile
Error! Not imported
banking.BankAccount
b;
…
}
}
This is perfectly legal, but makes code slightly
more difficult to read
Not as good from a style point of view as using import13
Access Modifiers
Define who can use class members (fields &
methods)
Allow us to encapsulate data
public
myPackage
Subclasses of this class, Classes in my
package
Note: Subclasses can be in a different
package! (Not shown in visual)
myPackage.subPackage
(not specified: default, a.k.a. package
protected)
OtherClass
protected
Everyone, and their dog
MyClass
Classes in my package
private
Only other instances of this class
anotherPackage
14
Boolean Operators & Expressions
Review
!
&&
||
^
Boolean Operators
//
//
//
/*
boolean
boolean
boolean
boolean
boolean
boolean
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 */
a = true;
b = false;
negated = !a;
anded = a && b;
ored = a || b;
exored = a ^ b;
//
//
//
//
false
false
true
true
15
Boolean Operators & Expressions
Boolean operators are used to produce a logical result
from boolean-valued operands
Like arithmetic expressions (*+/%), boolean expressions
can be complex
isDone || !found && atEnd
Like arithmetic operands, boolean operands have
precedence
E.g.
Highest
!
&& ^ ||
Lowest
… precedence can be overridden with parenthesis:
E.g.
(isDone || !found) && atEnd
16
Relational Operators
Used for comparing variables
Evaluate to a boolean result
==
!=
<
>
<=
>=
int a =
int b =
boolean
boolean
//
//
//
//
//
//
Equal to
Not equal to
Less than
Greater than
Less than or equal to
Greater than or equal to
1;
2;
equal = (a == b);
// false
lessThan = (a < b); // true
17
Relational Operators
… have a lower precedence than arithmetic
operators
int a =
int b =
boolean
boolean
1;
2;
equal = a == b-1;
// true
lessThan = a < b-1; // false
Can be combined with boolean operators we
already know to form complex expressions:
int a =
int b =
boolean
boolean
1;
2;
lessThanOrEqual = a < b || a == b;
lessThanEqual = a <= b;
18
Relational Operators
Floating Point Numbers
Computations often result in slight
differences that may be irrelevant
== operator only returns true if floating
point numbers are exactly equal
The
In many situations, you might consider two
floating point numbers to be "close
enough" even if they aren't exactly equal
19
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
20
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);
21
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
22
The if Statement
The if statement has the following syntax:
if is a Java
reserved word
The condition (a.ka. predicate)
must be a boolean expression. It
must evaluate to either true or
false.
if ( condition )
statement;
If the condition is true, the statement is executed.
If it is false, the statement is skipped.
23
Control Flow of an if statement
condition
evaluated
true
false
statement
24
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
25
Conditional Statements: Indentation
The statement controlled by the if statement is
indented to indicate that relationship
if (balance > amount)
balance-= amount;
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;
26
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
27
Control Flow of an if-else statement
condition
evaluated
true
false
statement1
statement2
28
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?
29
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++;
}
30
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;
}
31
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. */
32
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;
33
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;
34
Questions?
Quiz #1
Lab 1.5 Assigned
Deals with:
Due Next Tuesday
Next time:
String Manipulation
Interacting with Objects
The switch statement
A ternary conditional statement
I will be in Lab now
35