Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Java Programming
Week 2:
Revision (decision and iteration), instance
methods and static method
(Textbook ch5, ch6 and ch8)
Chapter Goals
Review Decisions and Iteration
To understand the difference between
instance methods and static methods
To introduce the concept of static fields
To understand the scope rules for local
variables and instance fields
To learn about packages
COIT11134 -Java Programming
2
Decisions:
The if and else Statement
The if statement lets a program carry out different
actions depending on a condition:
if (amount <= balance)
balance = balance - amount;
The else statement allows an overflow condition, so when
the if fails the else will succeed.
if (amount <= balance)
balance = balance - amount;
else
balance = balance - OVERDRAFT_PENALTY;
COIT11134-Java Programming
Continued…
3
Relational Operators
Relational operators allow you to compare values:
Java
Math Notation
Description
>
>
Greater than
>=
≥
Greater than or equal
<
<
Less than
<=
≤
Less than or equal
==
=
Equal
!=
≠
Not equal
COIT11134-Java Programming
4
Comparing Strings
Don't use == for strings!
if (input == "Y") // WRONG!!!
Use equals method (because String is Object type in Java):
if (input.equals("Y"))
<==> tests identity and <equals> tests contents
Case insensitive test ("Y" or "y")
if (input.equalsIgnoreCase("Y"))
Continued…
COIT11134-Java Programming
5
Comparing Strings
s.compareTo(t) < 0 means
s comes before t in the dictionary (can be used in sorting)
"car" comes before "cargo"
All uppercase letters come before lowercase:
"Hello" comes before "car"
COIT11134-Java Programming
6
Comparing Objects
== tests for identity, equals for identical content
Rectangle box1 = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box1;
Rectangle box3 = new Rectangle(5, 10, 20, 30);
box1 != box3, but box1.equals(box3)
box1 == box2
Caveat: equals must be defined for the class
COIT11134-Java Programming
7
Object Comparison
Representation of the
objects which were just
evaluated.
Box1 and 2 reference the
same object.
Box3 is a new object with
the same properties.
COIT11134-Java Programming
8
Testing for null
null reference refers to no object
Can be used in tests:
if (init == null)
System.out.println(firstName + " " + lastName);
else
System.out.println(firstName + " " + init + lastName);
Use ==, not equals, to test for null
Continued…
COIT11134-Java Programming
9
The else if Statement
The else if condition, allows testing over multiple
statements:
if (richter >= 0) // always passes
r = "Generally not felt by people";
else if (richter >= 3.5) // not tested
r = "Felt by many people, no destruction
. . .
else
COIT11134-Java Programming
10
Continued…
Nested Branches
COIT11134-Java Programming
11
Using boolean Expressions
George Boole (1815-1864): pioneer in the study
of logic
value of expression amount < 1000 is true
or false.
boolean type: one of these 2 truth values
COIT11134-Java Programming
12
Using Boolean Expressions:
Predicate Method
A predicate method returns a boolean value
public boolean isOverdrawn()
{
return balance < 0;
}
Use in conditions to evaluate true or false:
if (harrysChecking.isOverdrawn()) . . .
Continued…
COIT11134-Java Programming
13
Using Boolean Expressions:
Predicate Method
Useful predicate methods in Character class:
isDigit
isLetter
isUpperCase
isLowerCase
Useful predicate methods in Scanner class:
hasNextInt() and hasNextDouble()
if (in.hasNextInt())
{
n = in.nextInt();
}
COIT11134-Java Programming
14
Using Boolean Expressions:
The Boolean Operators
&& and
if (0 < amount && amount < 1000) . . .
|| or
if (input.equals("S") || input.equals("M")) . . .
!
Not
if (! input.isDigit() ) . . .
COIT11134-Java Programming
15
while Loops
Used to execute a block of code repeatedly.
A condition controls how often the loop is executed
while (condition)
statement;
Most commonly, the statement is a block statement:
set of statements delimited by { }
COIT11134-Java Programming
16
Using while Loop
Using the while loop to calculate a persons age in days?
int age = 25;
int counter = 0;
int ageDays = 0;
//persons age
//increment counter
//variable for days
//loop 25 times and add 365 to days each time.
while (counter < age)
{
counter++;
ageDays = ageDays + 365;
}
System.out.println(“Age in days is: “ + ageDays);
COIT11134-Java Programming
17
do Loops
Executes loop body at least once:
do
statement
while (condition);
Example: Validate input
double value;
do
{
System.out.print("Please enter a positive number: ");
value = in.nextDouble();
}
while (value <= 0);
COIT11134-Java Programming
Continued…
18
do Loops
while and do loops can be used interchangeably:
boolean done = false;
while (!done)
{
System.out.print("Please enter a positive number: ");
value = in.nextDouble();
if (value > 0) done = true;
}
COIT11134-Java Programming
19
for Loops
for (initialization; condition; update)
statement
Example:
for (int i = 1; i <= ageYears; i++)
{
ageInDays = ageInDays + 365;
}
COIT11134-Java Programming
Continued…
20
for Loops
Equivalent to
initialization;
while (condition)
{ statement; update; }
Other examples:
for (years = n; years > 0; years--) . . .
for (x = -10; x <= 10; x = x + 0.5) . . .
COIT11134-Java Programming
21
File Investment.java
01:
02:
03:
04:
05:
06:
07:
08:
09:
10:
11:
12:
13:
14:
15:
16:
17:
18:
/**
A class to monitor the growth of an investment that
accumulates interest at a fixed annual rate
*/
public class Investment
{
/**
Constructs an Investment object from a starting
balance and interest rate.
@param aBalance the starting balance
@param aRate the interest rate in percent
*/
public Investment(double aBalance, double aRate)
{
balance = aBalance;
rate = aRate;
years = 0;
}
COIT11134-Java Programming
Continued…
22
File Investment.java
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
/**
Keeps accumulating interest until a target balance
has been reached.
@param targetBalance the desired balance
*/
public void waitForBalance(double targetBalance)
{
while (balance < targetBalance)
{
years++;
double interest = balance * rate / 100;
balance = balance + interest;
}
}
COIT11134-Java Programming
Continued…
23
File Investment.java
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
/**
Keeps accumulating interest for a given number of years.
@param n the number of years
*/
public void waitYears(int n)
{
for (int i = 1; i <= n; i++)
{
double interest = balance * rate / 100;
balance = balance + interest;
}
years = years + n;
}
/**
Gets the current investment balance.
@return the current balance
*/
COIT11134-Java Programming
Continued…24
File Investment.java
53:
54:
55:
56:
57:
58:
59:
60:
61:
public double getBalance()
{
return balance;
}
62:
63:
64:
65:
66:
67:
*/
public int getYears()
{
return years;
}
/**
Gets the number of years this investment has
accumulated interest.
@return the number of years since the start of the
investment
Continued…
COIT11134-Java Programming
25
File Investment.java
68:
69:
70:
71: }
private double balance;
private double rate;
private int years;
COIT11134-Java Programming
26
File InvestmentTester.java
01:
02:
03:
04:
05:
06:
07:
08:
09:
10:
11:
12:
13:
14:
15:
16:
17:
18:
/**
This program computes how much an investment grows in
a given number of years.
*/
public class InvestmentTester
{
public static void main(String[] args)
{
final double INITIAL_BALANCE = 10000;
final double RATE = 5;
final int YEARS = 20;
Investment invest = new Investment(INITIAL_BALANCE, RATE);
invest.waitYears(YEARS);
double balance = invest.getBalance();
System.out.printf("The balance after %d years is %.2f\n",
YEARS, balance);
}
}
COIT11134-Java Programming
27
Continued…
File Investment.java
The output of this java file would be:
The balance after 20 years is 26532.98
COIT11134-Java Programming
28
Loop and a half
Sometimes termination condition of a loop can only
be evaluated in the middle of the loop
Boolean values can be used to control the termination of a
loop:
boolean done = false;
while (!done)
{
Print prompt String input = read input;
if (end of input indicated)
done = true;
else
{
// Process input
}
}
COIT11134-Java Programming
29
File InputTester.java
01:
02:
03:
04:
05:
06:
07:
08:
09:
10:
11:
12:
13:
14:
15:
16:
import java.util.Scanner;
/**
This program computes the average and maximum of a set
of input values.
*/
public class InputTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
DataSet data = new DataSet();
boolean done = false;
while (!done)
{
Continued…
COIT11134-Java Programming
30
File InputTester.java
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31: }
System.out.print("Enter value, Q to quit: ");
String input = in.next();
if (input.equalsIgnoreCase("Q"))
done = true;
else
{
double x = Double.parseDouble(input);
data.add(x);
}
}
System.out.println("Average = " + data.getAverage());
System.out.println("Maximum = " + data.getMaximum());
}
COIT11134-Java Programming
31
Random Numbers and Simulations
A simulation involves repeatedly generating random
numbers, for use in an activity.
Random number generator
Random generator = new Random();
int n = generator.nextInt(a); // 0 <= n < a
double x = generator.nextDouble(); // 0 <= x < 1
Throw die (random number between 1 and 6)
int d = 1 + generator.nextInt(6);
COIT11134-Java Programming
32
Accessors, Mutators and Immutable
Classes
Accessor: does not change the state of the implicit
parameter double balance = account.getBalance();
Mutator: modifies the object on which it is invoked
account.deposit(1000);
Immutable class: has no mutator methods (e.g., String)
String name = "John Q. Public";
String uppercased = name.toUpperCase();
//name is not changed
It is safe to give out references to objects of immutable
classes; no code can modify the object at an unexpected
time
COIT11134 -Java Programming
33
Self Check 8.6
Is the substring method of the String class an
accessor or a mutator?
Answer: It is an accessor – calling substring doesn't
modify the string on which the method is invoked. In fact,
all methods of the String class are accessors.
COIT11134 -Java Programming
34
Self Check 8.7
Is the Rectangle class immutable?
Answer: No – translate is a mutator.
COIT11134 -Java Programming
35
Static Methods
Every method must be in a class
A static method is not invoked on an object
Why write a method that does not operate on an object?
Common reason: encapsulate some computation that
involves only numbers. Numbers aren't objects, you can't
invoke methods on them. E.g., x.sqrt() can never be
legal in Java
Continued
COIT11134 -Java Programming
36
Static Methods (cont.)
public class Financial
{
public static double percentOf(double p, double a)
{
return (p / 100) * a;
}
// More financial methods can be added here.
}
• Call with class name instead of object:
double tax = Financial.percentOf(taxRate, total);
• main is static – there aren't any objects yet
COIT11134 -Java Programming
37
Self Check 8.12
Suppose Java had no static methods. Then all methods
of the Math class would be instance methods. How
would you compute the square root of x?
Answer:
Math m = new Math();
y = m.sqrt(x);
COIT11134 -Java Programming
38
Self Check 8.13
Harry turns in his homework assignment, a program that
plays tic-tac-toe. His solution consists of a single class with
many static methods. Why is this not an object-oriented
solution?
Answer: In an object-oriented solution, the main method
would construct objects of classes Game, Player, and the
like. Most methods would be instance methods that
depend on the state of these objects.
COIT11134 -Java Programming
39
Static Fields
• A static field belongs to the class, not to any object of
the class. Also called class field
public class BankAccount
{
. . .
private double balance;
private int accountNumber;
private static int lastAssignedNumber = 1000;
}
• If lastAssignedNumber was not static, each instance of
BankAccount would have its own value of
lastAssignedNumber
Continued
COIT11134 -Java Programming
40
Static Fields (cont.)
public BankAccount()
{
// Generates next account number to be assigned
lastAssignedNumber++;
//Assigns field to account number of this bank account
accountNumber = lastAssignedNumber;
// Sets the instance field
}
• Minimize the use of static fields (static final fields are ok)
COIT11134 -Java Programming
41
Static Fields (cont.)
Three ways to initialize:
1. Do nothing. Field is initialized with 0 (for numbers), false (for
boolean values), or null (for objects)
2. Use an explicit initializer, such as
public class BankAccount
{
. . .
private static int lastAssignedNumber = 1000;
// Executed once when class is loaded
}
3. Use a static initialization block
COIT11134 -Java Programming
Continued
42
Static Fields (cont.)
Static fields should always be declared as private
Exception: Static constants, which may be either private
or public
public class BankAccount
{
. . .
public static final double OVERDRAFT_FEE = 5;
//Refer to it as BankAccount.OVERDRAFT_FEE
}
COIT11134 -Java Programming
43
A Static Field and Instance Fields
COIT11134 -Java Programming
44
Self Check 8.14
Name two static fields of the System class.
Answer: System.in and System.out.
COIT11134 -Java Programming
45
Self Check 8.15
Harry tells you that he has found a great way to avoid
those pesky objects: Put all code into a single class and
declare all methods and fields static. Then main can call
the other static methods, and all of them can access the
static fields. Will Harry's plan work? Is it a good idea?
Answer: Yes, it works. Static methods can access static
fields of the same class. But it is a terrible idea. As your
programming tasks get more complex, you will want to
use objects and classes to organize your programs.
COIT11134 -Java Programming
46
Scope of Local Variables
Scope of variable: Region of program in which the
variable can be accessed
Scope of a local variable extends from its declaration
to end of the block that encloses it
Continued
COIT11134 -Java Programming
47
Scope of Local Variables (cont.)
Sometimes the same variable name is used in two
methods:
public class RectangleTester
{
public static double area(Rectangle rect)
{
double r = rect.getWidth()* rect.getHeight();
return r;
}
public static void main(String[] args)
{
Rectangle r = new Rectangle(5, 10, 20, 30);
double a = area(r);
System.out.println(r);
}
}
COIT11134 -Java Programming
48
Scope of Local Variables (cont.)
These variables are independent from each other; their
scopes are disjoint
Scope of a local variable cannot contain the definition of
another variable with the same name
Rectangle r = new Rectangle(5, 10, 20, 30);
if (x >= 0)
{
double r = Math.sqrt(x);
// Error - can't declare another variable called r
// here . .
}
Continued
COIT11134 -Java Programming
49
Scope of Local Variables (cont.)
However, can have local variables with identical names if
scopes do not overlap
if (x >= 0)
{
double r = Math.sqrt(x);
. . .
} // Scope of r ends here
else
{
Rectangle r = new Rectangle(5, 10, 20, 30);
// OK - it is legal to declare another r here
. . .
}
COIT11134 -Java Programming
50
Scope of Class Members
Private members have class scope: You can access all
members in any method of the class
Must qualify public members outside scope
Math.sqrt
harrysChecking.getBalance()
Inside a method, no need to qualify fields or methods
that belong to the same class
Continued
COIT11134 -Java Programming
51
Scope of Class Members (cont.)
An unqualified instance field or method name refers to the
this parameter
public class BankAccount
{
public void transfer(double amount, BankAccount other)
{
withdraw(amount); // i.e., this.withdraw(amount);
other.deposit(amount);
}
. . .
}
COIT11134 -Java Programming
52
Overlapping Scope
A local variable can shadow a field with the same name
Local scope wins over class scope
public class Coin
{ . . .
public double getExchangeValue(double exchangeRate)
{
double value; // Local variable
. . .
return value;
}
private String name;
private double value; // Field with the same name
}
COIT11134 -Java Programming
Continued
53
Overlapping Scope (cont.)
Access shadowed fields by qualifying them with the this
reference
value = this.value * exchangeRate;
COIT11134 -Java Programming
54
File BankAccount.java
public class BankAccount
{
public BankAccount()
{
balance = 0;
}
public BankAccount(double initialBalance)
{
balance = initialBalance;
}
public void deposit(double amount)
{
double newBalance = balance + amount;
balance = newBalance;
}
public void withdraw(double amount)
{
double newBalance = balance - amount;
balance = newBalance;
}
public double getBalance()
{
return balance;
}
private double balance;
}
COIT11134 -Java Programming
Continued… 55
Self Check 8.16
Consider the deposit method of the BankAccount class.
What is the scope of the variables amount and newBalance?
Answer: The scope of amount is the entire deposit
method. The scope of newBalance starts at the point at
which the variable is defined and extends to the end of the
method.
COIT11134 -Java Programming
56
Self Check 8.17
What is the scope of the balance field of the BankAccount
class?
Answer: It starts at the beginning of the class and ends at
the end of the class.
COIT11134 -Java Programming
57
Organizing Related Classes into
Packages
Package: Set of related classes
To put classes in a package, you must place a line
package packageName;
as the first instruction in the source file containing the
classes
Package name consists of one or more identifiers
separated by periods
Continued
COIT11134 -Java Programming
58
Organizing Related Classes into
Packages (cont.)
For example, to put the Financial class introduced into a
package named com.horstmann.bigjava,
the Financial.java file must start as follows:
package com.horstmann.bigjava;
public class Financial
{
. . .
}
Default package has no name, no package statement
COIT11134 -Java Programming
59
Important Packages in the Java Library
Package
Purpose
Sample Class
java.lang
Language support
Math
java.util
Utilities
Random
java.io
Input and output
PrintStream
java.awt
Abstract Windowing Toolkit
Color
java.applet
Applets
Applet
java.net
Networking
Socket
java.sql
Database Access
ResultSet
javax.swing
Swing user interface
JButton
org.omg.CORBA
Common Object Request Broker
Architecture
IntHolder
COIT11134 -Java Programming
60
Syntax 8.2 Package Specification
package packageName;
Example:
package com.horstmann.bigjava;
Purpose:
To declare that all classes in this file belong to a particular
package.
COIT11134 -Java Programming
61
Importing Packages
Can always use class without importing
java.util.Scanner in = new
java.util.Scanner(System.in);
Tedious to use fully qualified name
Import lets you use shorter class name
import java.util.Scanner; . . .
Scanner in = new Scanner(System.in)
Can import all classes in a package
import java.util.*;
Never need to import java.lang
COIT11134 -Java Programming
62
Package Names and Locating Classes
You don't need to import other classes in the same
package
Use packages to avoid name clashes
java.util.Timer vs. javax.swing.Timer
Package names should be unambiguous
Recommendation: start with reversed domain name
com.horstmann.bigjava
Path name should match package name
com/horstmann/bigjava/Financial.java
Continued
COIT11134 -Java Programming
63
Base Directories and Subdirectories for
Packages
COIT11134 -Java Programming
64
Self Check 8.18
Which of the following are packages?
a. java
b. java.lang
c. java.util
d. java.lang.Math
Answer:
a. No
b. Yes
c. Yes
d. No
COIT11134 -Java Programming
65
Self Check 8.19
Is a Java program without import statements limited to
using the default and java.lang packages?
Answer: No – you simply use fully qualified names for all
other classes, such as java.util.Random and
java.awt.Rectangle.
COIT11134 -Java Programming
66
References
Horstmann, Big Java, 2007, Wiley & Sons
COIT11134 -Java Programming
67