Download public static void

Document related concepts
no text concepts found
Transcript
Chapter 5 Methods
郝聚涛
[email protected]
Liang, Introduction to Java Programming,
Seventh Edition, (c) 2009 Pearson Education,
Inc. All rights reserved. 0136012671
1
Motivations
A method is a construct for grouping statements together to
perform a function. Using a method, you can write the code
once for performing the function in a program and reuse it by
many other programs.
For example, often you need to find the maximum between
two numbers. Whenever you need this function, you would
have to write the following code:
int result;
if (num1 > num2)
result = num1;
else
result = num2;
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
2
Objectives
 To define methods, invoke methods, and pass arguments to a method







(§5.2-5.5).
To develop reusable code that is modular, easy-to-read, easy-todebug, and easy-to-maintain. (§5.6).
To use method overloading and understand ambiguous overloading
(§5.7).
To design and implement overloaded methods (§5.8).
To determine the scope of variables (§5.9).
To know how to use the methods in the Math class (§§5.10-5.11).
To learn the concept of method abstraction (§5.12).
To design and implement methods using stepwise refinement (§5.12).
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
3
Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
4
Method Signature(方法签名)
Method signature is the combination of the method name and the
parameter list.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
5
Formal Parameters(形式参数)
The variables defined in the method header are known as
formal parameters.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
6
Actual Parameters(实际参数,实参)
When a method is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
7
Actual Parameters and Formal Parameters
Location of actual parameter or argument to formal parameter is important.
•Number of actual parameters must equal number of formal parameters.
•Type of actual parameter must match type of formal parameter.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
8
Return Value Type
A method may return a value. The returnValueType is the data type
of the value the method returns. If the method does not return a
value, the returnValueType is the keyword void. For example, the
returnValueType in the main method is void.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
9
Example Return Value Types
 Return type int

public static int max(int a, int b) {


public static double max(int a, int b) {


Returns type integer
Returns type double
public static void printn(String c) {

Does not return a value, so no return statement in
this method.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
10
Method body
The method body is the code executed to produce the results.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
11
Modifiers
Identifies how the method is used:
•public: any other program has access to this method
•static: static methods can be called without creating an instance of the class
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
12
Modifiers
 Java modifiers



public: all methods have access to the method
protected: only methods in the same package
have access to the method
private: only methods in the same class has
access to the method
 Java structure



Package: contains one or more classes
Class: contains one or more methods
Subclass: derived from a class
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
13
Calling Methods
Listing 5.1 Testing the max method
This program demonstrates calling a method max
to return the largest of the int values
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
14
TestMax
public class TestMax {
/** Main method */
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
System.out.println("The maximum between " + i + " and " + j + " is " + k);
}
/** Return the max between two numbers */
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
return (x>y)?x:y;
result = num1;
else
result = num2;
return result;
Run
TestMax
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
15
animation
Calling Methods, cont.
pass the value of i
pass the value of j
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
16
animation
Trace Method Invocation
i is now 5
i
5
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
17
animation
Trace Method Invocation
j is now 2
i
5
j
2
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
18
animation
Trace Method Invocation
invoke max(i, j)
i
5
j
2
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
19
animation
Trace Method Invocation
invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2
i
5
j
2
num1 num2
5
2
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
20
animation
Trace Method Invocation
declare variable result
i
5
j
2
num1 num2 result
5
2
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
21
animation
Trace Method Invocation
(num1 > num2) is true since num1
is 5 and num2 is 2
i
5
j
2
num1 num2 result
5
2
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
22
animation
Trace Method Invocation
result is now 5
i
5
j
2
num1 num2 result
5
2
5
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
23
animation
Trace Method Invocation
return result, which is 5
i
5
j
2
num1 num2 result
5
2
5
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
24
animation
Trace Method Invocation
return max(i, j) and assign the
return value to k
i
5
j
2
k
5
num1 num2 result
5
2
5
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
25
animation
Trace Method Invocation
Execute the print statement
i
5
j
2
k
5
num1, num2, and result no
longer exist
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
26
CAUTION
A return statement is required for a value-returning method. The method
shown below in (a) is logically correct, but it has a compilation error
because the Java compiler thinks it possible that this method does not
return any value.
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else if (n < 0)
return –1;
}
(a)
Should be
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else
return –1;
}
(b)
To fix this problem, delete if (n < 0) in (a), so that the compiler will see a
return statement to be reached regardless of how the if statement is
evaluated.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
27
Reuse Methods from Other Classes
NOTE: One of the benefits of methods is for reuse. The max
method can be invoked from any class besides TestMax. If you
create a new class Test, you can invoke the max method using
ClassName.methodName (e.g., TestMax.max).
public class Test {
public static void main(String[] args) {
int a = 4;
int b = 8;
int c = TestMax.max(a,b);
System.out.println("The largest of " + a + " and " + b + " is " + c);
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
28
Call Stacks
pass the value of i
pass the value of j
Each time a method is invoked, the system stores parameters and variables in an area
of memory, known as a stack, which stores elements in last-in first-out fashion.
When a method calls another method, the caller's stack space is kept intact, and new
space is created to handle the new method call. When a method finishes its work and
returns to its caller, its associated space is released.
Space required for
the max method
num2: 2
num1: 5
Space required for
the max method
result: 5
num2: 2
num1: 5
Space required for
the main method
k:
j: 2
i: 5
Space required for
the main method
k:
j:
2
i:
5
Space required for
the main method
k:
j:
2
i:
5
Space required for
the main method
k:
5
j:
2
i:
5
(a) The main
method is invoked.
(b) The max
method is invoked.
(c) The max method
is being executed.
(d) The max method is
finished and the return
value is sent to k.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Stack is empty
(e) The main
method is finished.
29
animation
Trace Call Stack
i is declared and initialized
i: 5
The main method
is invoked.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
30
animation
Trace Call Stack
j is declared and initialized
j: 2
i: 5
The main method
is invoked.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
31
animation
Trace Call Stack
Declare k
Space required for the
main method
k:
j: 2
i: 5
The main method
is invoked.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
32
animation
Trace Call Stack
Invoke max(i, j)
Space required for the
main method
k:
j: 2
i: 5
The main method
is invoked.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
33
animation
Trace Call Stack
pass the values of i and j to num1
and num2
num2: 2
num1: 5
Space required for the
main method
k:
j: 2
i: 5
The max method is
invoked.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
34
animation
Trace Call Stack
pass the values of i and j to num1
and num2
result:
num2: 2
num1: 5
Space required for the
main method
k:
j: 2
i: 5
The max method is
invoked.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
35
animation
Trace Call Stack
(num1 > num2) is true
result:
num2: 2
num1: 5
Space required for the
main method
k:
j: 2
i: 5
The max method is
invoked.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
36
animation
Trace Call Stack
Assign num1 to result
Space required for the
max method
result: 5
num2: 2
num1: 5
Space required for the
main method
k:
j: 2
i: 5
The max method is
invoked.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
37
animation
Trace Call Stack
Return result and assign it to k
Space required for the
max method
result: 5
num2: 2
num1: 5
Space required for the
main method
k:5
j: 2
i: 5
The max method is
invoked.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
38
animation
Trace Call Stack
Execute print statement
Space required for the
main method
k:5
j: 2
i: 5
The main method
is invoked.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
39
void Method Example
This type of method does not return a value. The method
performs some actions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
40
TestVoidMethod
public class TestVoidMethod {
public static void main(String[] args) {
System.out.print("The grade is ");
printGrade(78.5);
}
public static void printGrade(double score) {
if (score >= 90.0) {
System.out.println('A');
}
else if (score >= 80.0) {
System.out.println('B');
}
else if (score >= 70.0) {
System.out.println('C');
}
else if (score >= 60.0) {
System.out.println('D');
}
else {
System.out.println('F');
}
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
41
Passing Parameters
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
Suppose you invoke the method using
nPrintln(“Welcome to Java”, 5);
What is the output?
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
Suppose you invoke the method using
nPrintln(“Computer Science”, 15);
What is the output?
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
42
Pass by Value(值传递)
• Pass the value of the variable, not the memory
location
• Make changes to value will not change the
value in the original variable
Listing 5.2 Testing Pass by value
This program demonstrates passing values to the
methods.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
43
TestPassByValue
public class TestPassByValue {
/** Main method */
public static void main(String[] args) {
// Declare and initialize variables
int num1 = 1;
int num2 = 2;
System.out.println("Before invoking the swap method, num1 is " + num1 +
" and num2 is " + num2);
// Invoke the swap method to attempt to swap two variables
swap(num1, num2);
System.out.println("After invoking the swap method, num1 is " + num1 +
" and num2 is " + num2);
}
/** Swap two variables */
public static void swap(int n1, int n2) {
System.out.println("\tInside the swap method");
System.out.println("\t\tBefore swapping n1 is " + n1 + " n2 is " + n2);
// Swap n1 with n2
int temp = n1;
n1 = n2;
html
n2 = temp;
System.out.println("\t\tAfter swapping n1 is " + n1 + " n2 is " + n2);
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
run
44
Pass by Value, cont.
The values of num1 and num2 are
passed to n1 and n2. Executing swap
does not affect num1 and num2.
Space required for the
swap method
temp:
n2: 2
n1: 1
Space required for the
main method
num2: 2
num1: 1
The main method
is invoked
Space required for the
main method
num2: 2
num1: 1
The swap method
is invoked
Space required for the
main method
num2: 2
num1: 1
The swap method
is finished
Stack is empty
The main method
is finished
After the swap, n2 = 1 and n1 = 2
But the values in num1 and num2
do not change
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
45
Modularizing Code
Methods can be used to reduce redundant coding
and enable code reuse.
Methods can also be used to modularize code and
improve the quality of the program.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
46
GreatestCommonDivisorMethod
import java.util.Scanner;
public class GreatestCommonDivisorMethod {
/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter first integer: ");
int n1 = input.nextInt();
System.out.print("Enter second integer: ");
int n2 = input.nextInt();
System.out.println("The greatest common divisor for " + n1 + " and " + n2 +
" is " + gcd(n1, n2));
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
47
GreatestCommonDivisorMethod (cont.)
/** Return the gcd of two integers */
public static int gcd(int n1, int n2) {
int gcd = 1;
// Initial gcd is 1
int k = 1;
// Possible gcd
while (k <= n1 && k <= n2) {
if (n1 % k == 0 && n2 % k == 0)
gcd = k;
// Update gcd
k++;
}
return gcd;
// Return gcd
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
48
PrimeNumberMethod
public class PrimeNumberMethod {
public static void main(String[] args) {
final int NUMBER_OF_PRIMES = 50;
// Number of primes to display
final int NUMBER_OF_PRIMES_PER_LINE = 10;
// Display 10 per line
int count = 0;
// Count the number of prime numbers
int number = 2;
// A number to be tested for primeness
System.out.println("The first 50 prime numbers are \n");
// Repeatedly find prime numbers
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
49
PrimeNumberMethod (cont)
while (count < NUMBER_OF_PRIMES) {
// Print the prime number and increase the count
if (isPrime(number)) {
count++;
// Increase the count
if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
// Print the number and advance to the new line
System.out.printf("%-5s\n", number);
}
else
System.out.printf("%-5s", number);
}
// Check if the next number is prime number++;
}
}
/** Check whether number is prime */
number++;
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
50
PrimeNumberMethod (cont)
public static boolean isPrime(int number) {
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) {
// If true, number is not prime
return false;
// number is not a prime
}
}
return true;
// number is prime
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
51
Overloading Methods(重载)
Listing 5.3 Overloading the max Method
public static double max(double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
52
TestMethodOverload
public class TestMethodOverloading {
/** Main method */
public static void main(String[] args) {
// Invoke the max method with int parameters
System.out.println("The maximum between 3 and 4 is " + max(3, 4));
// Invoke the max method with the double parameters
System.out.println("The maximum between 3.0 and 5.4 is " + max(3.0, 5.4));
// Invoke the max method with three double parameters
System.out.println("The maximum between 3.0, 5.4, and 10.14 is " + max(3.0, 5.4, 10.14));
}
/** Return the max between two int values */
public static int max(int num1, int num2) {
if (num1 > num2)
return num1;
else return num2;
}
/** Find the max between two double values */
TestMethodOverload
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
run
53
TestMethodOverload (cont)
public static double max(double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
/** Return the max among three double values */
public static double max(double num1, double num2, double num3) {
return max(max(num1, num2), num3);
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
54
 If you call max with int parameters, the max method that
expects int parameters will be invoked;


max(3, 4);
public static int max(int num1, int num2)
 if you call max with double parameters, the max method
that expects double parameters will be invoked.


max(3.0, 5.4));
public static double max(double num1, double num2)
 This is referred to as method overloading; that is, two
methods have the same name but different parameter
lists within one class. The Java compiler determines
which method is used based on the method signature.
 Overloaded methods must have different parameter lists.
You cannot overload methods based on different
modifiers or return types.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
55
max(3, 4); -----public static int max(int num1, int
num2)
 max(3.0, 5.4)); -----public static double max(double
num1, double num2)
------------------------------------------------------------------- max(3, 4); -----public static double max(double num1,
double num2)(自动转型)
 max((int)3.0,(int) 5.4)); -----public static int
max(int num1, int num2)

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
56
Ambiguous Invocation
Sometimes there may be two or more
possible matches for an invocation of a
method, but the compiler cannot determine
the most specific match. This is referred to
as ambiguous invocation.
 Ambiguous invocation is a compilation
error.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
57
Ambiguous Invocation(歧义调用)
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1, 2));
}
public static double max(int num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
Compiler cannot
determine if 1 is
an integer or a
double value and
if 2 is an int or
double value.
This will produce
a compile error.
public static double max(double num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
58
Scope of Local Variables
 A local variable(局部变量): a variable
defined inside a method.
 Scope(作用域): the part of the program
where the variable can be referenced.
 The scope of a local variable starts from its
declaration and continues to the end of the
block that contains the variable.
 A local variable must be declared before it
can be used.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
59
Scope of Local Variables, cont.
You can declare a local variable with the same
name multiple times in different non-nesting
blocks in a method, but you cannot declare a
local variable twice in nested blocks.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
60
Scope of Local Variables, cont.
A variable declared in the initial action part of a for loop
header has its scope in the entire loop.
 a variable declared inside a for loop body has its scope
limited in the loop body from its declaration and to the end
of the block that contains the variable.
The scope of i
The scope of j
public static void method1() {
.
.
for (int i = 1; i < 10; i++) {
.
.
int j;
.
.
.
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
61
Scope of Local Variables, cont.
It is fine to declare i in two
non-nesting blocks
public static void method1() {
int x = 1;
int y = 1;
It is wrong to declare iin
two nesting blocks
public static void method2()
{
int i = 1;
int sum = 0;
for (int i = 1; i < 10; i++) {
x += i;
}
}
for (int i = 1; i < 10; i++) {
y += i;
}
for (int i = 1; i < 10; i++) {
sum += i;
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
62
Scope of Local Variables, cont.
// Fine with no errors
public static void correctMethod() {
int x = 1;
int y = 1;
// i is declared
for (int i = 1; i < 10; i++) {
x += i;
}
// i is declared again
for (int i = 1; i < 10; i++) {
y += i;
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
63
Scope of Local Variables, cont.
// With no errors
public static void incorrectMethod() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
int x = 0; //this x will go away when for ends
x += i;
}
System.out.println(“X = “ + x);
}
X=1
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
64
局部变量声明
 局部变量的一般形式如下
[变量修饰符] 变量类型 变量名;
1. 变量修饰符可以是final,表示这是常量。
2. 变量类型可以是Java中任意合法的基本类型或复
合类型。
3. 变量名是用户自定义标识符,遵循标识符的一般
规则。
4. 可以在一行中定义多个局部变量,以逗号分隔。
5. 定义变量时可以同时赋初值。
6. 局部变量必须要先定义后使用。
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
65
局部变量与成员变量区别
1. 局部变量没有访问权限修饰符,不能用public、private和protected来
2.
3.
4.
5.
6.
7.
修饰。这是因为它只能在定义它的方法内部使用。
局部变量不能用static修饰,没有"静态局部变量",这是Java和C/C++
的一个细微差别。
系统不会自动为局部变量赋初值,但对于成员变量,系统会自动赋初
值。基本类型的值为0,复合类型的值为null。
局部变量的作用域仅限于定义它的方法,在该方法的外部无法访问它。
成员变量的作用域在整个类内部都是可见的,所有成员方法都可以使
用它。如果访问权限允许,还可以在类的外部使用成员变量。
局部变量的生存周期与方法的执行期相同。当方法执行到定义局部变
量的语句时,局部变量被创建;执行到它所在的作用域的最后一条语
句时,局部变量被销毁。类的成员变量,如果是实例成员变量,它和
对象的生存期相同。而静态成员变量的生存期是整个程序运行期。
在同一个方法中,不允许有同名的局部变量。在不同的方法中,可以
有同名的局部变量,它们互不干涉。
局部变量可以和成员变量同名,且在使用时,局部变量具有更高的优
先级。
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
66
 public class localVariable{
public void method_1(){
int va = 0;
//正确
public int pva;
//错误,不能有访问权限
static int sa;
//错误,不能是静态的
final int CONST = 10; //正确,可以是常量
double va =0.0;
//错误,与前面的va同名
vb = 100.0;
//错误,vb还未定义
double vb;
vb = 100.0;
//正确,现在可以使用了
}
public void method_2(){
va = 0;
//错误,method_1()中的变量va在此不可用
int CONST = 100; //正确,它与method_1()中的CONST
不同
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
67
 public class localVSmember{
private int iVar = 100;
public void method_1(){
int iVar;
//正确可以与成员变量同名
iVar = 200;
//这里访问的是局部变量
this.iVar = 300; //这里访问的是成员变量
}
public void method_2(){
iVar = 400; //这里访问的是成员变量
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
68
Method Abstraction
You can think of the method body as a black box
that contains the detailed implementation for the
method.
Optional arguments
for Input
Optional return
value
Method Header
Black Box
Method body
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
69
Benefits of Methods
• Write a method once and reuse it anywhere.
• Information hiding. Hide the implementation
from the user.
• Reduce complexity.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
70
The Math Class
 Java has predefined classes and methods
 Java API
Definition  http://java.sun.com/j2se/1.5.0/docs/api/index.html
Example  http://www.java2s.com/Code/JavaAPI/CatalogJavaAPI.htm
 java.lang contains Math class
 import java.lang.Math;
 Class constants:
 PI
 E 自然对数的底
 Class methods:
 Trigonometric Methods 三角函数方法
 Exponent Methods
指数函数方法
 min, max, abs, and random Methods
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
71
Trigonometric Methods
 sin(double a)
 cos(double a)
 tan(double a)
 acos(double a)
 asin(double a)
 atan(double a)
 a is in Radians
To convert degrees to Radians (弧
度) use
Examples:
Math.sin(0) returns 0.0
Math.sin(Math.PI / 6)
returns 0.5
Math.sin(Math.PI / 2)
returns 1.0
Math.cos(0) returns 1.0
Math.cos(Math.PI / 6)
returns 0.866
Math.cos(Math.PI / 2)
returns 0
a = Math.toRadians(degrees)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
72
Exponent Methods
 exp(double a)
Returns e raised to the power of
a.
 log(double a)
Returns the natural logarithm of
a.
 log10(double a)
Returns the 10-based logarithm
of a.
Examples:
Math.exp(1) returns 2.71
Math.log(2.71) returns 1.0
Math.pow(2, 3) returns 8.0
Math.pow(3, 2) returns 9.0
Math.pow(3.5, 2.5) returns
22.91765
Math.sqrt(4) returns 2.0
Math.sqrt(10.5) returns 3.24
 pow(double a, double b)
Returns a raised to the power of
b.
 sqrt(double a)
Returns the square root of a.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
73
Rounding Methods(取整)
 double ceil(double x)
x rounded up to its nearest integer. This integer is returned as a
double value.
 double floor(double x)
x is rounded down to its nearest integer. This integer is
returned as a double value.
 double rint(double x)
x is rounded to its nearest integer. If x is equally close to two
integers, the even one is returned as a double.
 int round(float x)
Return (int)Math.floor(x+0.5).
 long round(double x)
Return (long)Math.floor(x+0.5).
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
74
Rounding Methods Examples
Math.ceil(2.1) returns 3.0
Math.ceil(2.0) returns 2.0
Math.ceil(-2.0) returns –2.0
Math.ceil(-2.1) returns -2.0
Math.floor(2.1) returns 2.0
Math.floor(2.0) returns 2.0
Math.floor(-2.0) returns –2.0
Math.floor(-2.1) returns -3.0
Math.rint(2.1) returns 2.0
Math.rint(2.0) returns 2.0
Math.rint(-2.0) returns –2.0
Math.rint(-2.1) returns -2.0
Math.rint(2.5) returns 2.0
Math.rint(-2.5) returns -2.0
Math.round(2.6f) returns 3
Math.round(2.0) returns 2
Math.round(-2.0f) returns -2
Math.round(-2.6) returns -3
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
75
min, max, and abs
 max(a, b)and min(a, b)
Returns the maximum or
minimum of two parameters.
 abs(a)
Returns the absolute value of
the parameter.
 random()
Returns a random double
value
in the range [0.0, 1.0).
Examples:
Math.max(2, 3) returns 3
Math.max(2.5, 3) returns
3.0
Math.min(2.5, 3.6) returns
2.5
Math.abs(-2) returns 2
Math.abs(-2.1) returns 2.1
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
76
The random Method
Generates a random double value greater than or equal to 0.0 and less
than 1.0 (0 <= Math.random() < 1.0).
Examples:
(int)(Math.random() * 10)
Returns a random integer
between 0 and 9.
50 + (int)(Math.random() * 50)
Returns a random integer
between 50 and 99.
In general,
a + Math.random() * b
Returns a random number between
a and a + b, excluding a + b.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
77
Case Study: Generating Random Characters
As introduced in Section 2.9, each character has a unique
Unicode between 0 and FFFF in hexadecimal (65535 in
decimal).
To generate a random character is to generate a random
integer between 0 and 65535 using the following expression:
(note that since 0 <= Math.random() < 1.0, you have to add 1
to 65535.)
(int)(Math.random() * (65535 + 1))
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
78
Case Study: Generating Random Characters, cont.
Now let us consider how to generate a random
lowercase letter.
The Unicode for lowercase letters are consecutive
integers starting from the Unicode for 'a', then for 'b',
'c', ..., and 'z'.
The Unicode for 'a' is

(int)'a'
So, a random integer between (int)'a' and (int)'z' is

(int)((int)'a' + Math.random() * ((int)'z' - (int)'a' + 1)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
79
Case Study: Generating Random Characters, cont.
Now let us consider how to generate a random
lowercase letter. The Unicode for lowercase letters
are consecutive integers starting from the Unicode
for 'a', then for 'b', 'c', ..., and 'z'. The Unicode for 'a' is
(int)'a'
So, a random integer between (int)'a' and (int)'z' is
(int)((int)'a' + Math.random() * ((int)'z' - (int)'a' + 1)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
80
Case Study: Generating Random Characters, cont.
As discussed in Section 2.9.4, all numeric operators
can be applied to the char operands.
The char operand is cast into a number if the other
operand is a number or a character. So, the
preceding expression can be simplified as follows:

'a' + Math.random() * ('z' - 'a' + 1)

So a random lowercase letter is

(char)('a' + Math.random() * ('z' - 'a' + 1))
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
81
Case Study: Generating Random Characters, cont.
To generalize the foregoing discussion, a random character
between any two characters ch1 and ch2 with ch1 < ch2 can
be generated as follows:
(char)(ch1 + Math.random() * (ch2 – ch1 + 1))
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
82
The RandomCharacter Class
// RandomCharacter.java: Generate random characters
public class RandomCharacter {
/** Generate a random character between ch1 and ch2 */
public static char getRandomCharacter(char ch1, char ch2)
{
return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
}
/** Generate a random lowercase letter */
public static char getRandomLowerCaseLetter() {
return getRandomCharacter('a', 'z');
}
html
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
83
/** Generate a random uppercase letter */
public static char getRandomUpperCaseLetter() {
return getRandomCharacter('A', 'Z');
}
/** Generate a random digit character */
public static char getRandomDigitCharacter() {
return getRandomCharacter('0', '9');
}
/** Generate a random character */
public static char getRandomCharacter() {
return getRandomCharacter('\u0000', '\uFFFF');
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
84
TestRandomCharacter.java
public class TestRandomCharacter {
/** Main method */
public static void main(String args[]) {
final int NUMBER_OF_CHARS = 175;
final int CHARS_PER_LINE = 25;
// Print random characters between 'a' and 'z', 25 chars per line
for (int i = 0; i < NUMBER_OF_CHARS; i++) {
char ch = RandomCharacter.getRandomLowerCaseLetter();
if ((i + 1) % CHARS_PER_LINE == 0)
System.out.println(ch);
else System.out.print(ch);
}
}
}
html
run
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
85
Stepwise Refinement (逐步求精)
The concept of method abstraction can be applied
to the process of developing programs.
When writing a large program, you can use the
“divide and conquer” (分治)strategy, also known
as stepwise refinement, to decompose it into
subproblems.
The subproblems can be further decomposed into
smaller, more manageable problems.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
86
PrintCalender Case Study
Let us use the PrintCalendar example to demonstrate the
stepwise refinement approach.
run
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
87
Design Diagram
printCalendar
(main)
printMonth
readInput
printMonthTitle
printMonthBody
/** Main method */
public static void main(String[] args) {
//readInput box
getStartDay
getMonthName
// Prompt the user
to enter year
String yearString = JOptionPane.showInputDialog( "Enter full year (e.g., 2001):");
// Convert string into integer
int year = Integer.parseInt(yearString);
getTotalNumOfDays
// Prompt the user to enter month
String monthString = JOptionPane.showInputDialog(
"Enter month in number between 1 and 12:");
// Convert string into integer
getNumOfDaysInMonth
int month = Integer.parseInt(monthString);
//end of readInput box
// Print calendar for the month of the year
printMonth(year, month); //this is a call to printMonth method
isLeapYear
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
88
Design Diagram
printCalendar
(main)
/** A stub for printMonth may look like this */
public static void printMonth(int year, int month) {
System.out.print(month + " " + year);
}
printMonth
readInput
printMonthTitle
printMonthBody
/** A stub for printMonthTitle
may look like this */
getMonthName
public static void printMonthTitle(int year, int month) {
}
getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
89
Design Diagram
printCalendar
(main)
printMonth
readInput
printMonthTitle
getMonthName
/** A stub for getMonthName may look like this */
public static String getMonthName(int month) {
printMonthBody
getStartDay
getTotalNumOfDays
return "January"; // a dummy value
getNumOfDaysInMonth
}
isLeapYear
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
90
Design Diagram
printCalendar
(main)
printMonth
readInput
printMonthTitle
printMonthBody
getStartDay
getMonthName
/** A stub for getStartDay may getTotalNumOfDays
look like this */
public static int getStartDay(int year, int month) {
return 1; // a dummy value
getNumOfDaysInMonth
}
/** A stub for getNumberOfDaysInMonth may look like this */
public static int getNumberOfDaysInMonth(int year, int month) {
isLeapYear
return 31; // a dummy value
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
91
Design Diagram
printCalendar
(main)
printMonth
readInput
printMonthTitle
getMonthName
printMonthBody
getStartDay
getTotalNumOfDays
/** A stub for getTotalNumberOfDays may look like this */
public static int getTotalNumberOfDays(int year, int month) {
getNumOfDaysInMonth
return 10000; // a dummy value
}
isLeapYear
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
92
Design Diagram
printCalendar
(main)
printMonth
readInput
printMonthTitle
getMonthName
printMonthBody
getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
/** A stub for isLeapYear may look like this */
public static boolean isLeapYear(int year) {
return true; // a dummy value
}
isLeapYear
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
93
Implementation: Top-Down
•Top-down approach is to implement one method in the
structure chart at a time from the top to the bottom. Stubs
can be used for the methods waiting to be implemented..
•Implement the main method first and then use a stub for
the printMonth method. For example, let printMonth
display the year and the month in the stub. Thus, your
program may begin like this:
Stub 存根,未完善方法
A stub is a simple but incomplete version of a method.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
94
Skeleton for PrintCalendar
// PrintCalendar.java: Print a calendar for a given month in a year
import javax.swing.*;
public class PrintCalendar {
/** Main method */
public static void main(String[] args) {
//readInput box
// Prompt the user to enter year
String yearString = JOptionPane.showInputDialog( "Enter full year (e.g., 2001):");
// Convert string into integer
int year = Integer.parseInt(yearString);
// Prompt the user to enter month
String monthString = JOptionPane.showInputDialog(
"Enter month in number between 1 and 12:");
// Convert string into integer
int month = Integer.parseInt(monthString);
//end of readInput box
// Print calendar for the month of the year
printMonth(year, month); //this is a call to printMonth method
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
95
Skeleton for PrintCalendar cont.
/** A stub for printMonth may look like this */
public static void printMonth(int year, int month) {
System.out.print(month + " " + year);
}
/** A stub for printMonthTitle may look like this */
public static void printMonthTitle(int year, int month) {
}
/** A stub for getMonthName may look like this */
public static String getMonthName(int month) {
return "January"; // a dummy value
}
/** A stub for getStartDay may look like this */
public static int getStartDay(int year, int month) {
return 1; // a dummy value
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
96
Skeleton for PrintCalendar cont.
/** A stub for getNumberOfDaysInMonth may look like this */
public static int getNumberOfDaysInMonth(int year, int month) {
return 31; // a dummy value
}
/** A stub for getTotalNumberOfDays may look like this */
public static int getTotalNumberOfDays(int year, int month) {
return 10000; // a dummy value
}
/** A stub for isLeapYear may look like this */
public static boolean isLeapYear(int year) {
return true; // a dummy value
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
97
Implementation: Bottom-Up
Bottom-up approach is to implement one method in the
structure chart at a time from the bottom to the top.
For each method implemented, write a test program to
test it.
 Both top-down and bottom-up methods are fine. Both
approaches implement the methods incrementally and
help to isolate programming errors and makes debugging
easy. Sometimes, they can be used together.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
98
PrintCalendar.java
import java.util.Scanner;
public class PrintCalendar {
/** Main method */
public static void main(String[] args) {
// Prompt the user to enter year
Scanner input = new Scanner(System.in);
// Prompt the user to enter year
System.out.print("Enter full year (e.g., 2001): ");
int year = input.nextInt();
// Prompt the user to enter month
System.out.print("Enter month in number between 1 and 12: ");
int month = input.nextInt();
// Print calendar for the month of the year
printMonth(year, month);
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
99
PrintCalendar.java
/** Print the calendar for a month in a year */
static void printMonth(int year, int month) {
// Print the headings of the calendar
printMonthTitle(year, month);
// Print the body of the calendar
printMonthBody(year, month);
}
/** Print the month title, e.g., May, 1999 */
static void printMonthTitle(int year, int month) {
System.out.println(" " + getMonthName(month) + " " + year);
System.out.println("-----------------------------");
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
100
PrintCalendar.java
/** Get the English name for the month */
static String getMonthName(int month) {
String monthName = null;
switch (month) {
case 1: monthName = "January"; break;
case 2: monthName = "February"; break;
case 3: monthName = "March"; break;
case 4: monthName = "April"; break;
case 5: monthName = "May"; break;
case 6: monthName = "June"; break;
case 7: monthName = "July"; break;
case 8: monthName = "August"; break;
case 9: monthName = "September"; break;
case 10: monthName = "October"; break;
case 11: monthName = "November"; break;
case 12: monthName = "December";
}
return monthName;
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
101
PrintCalendar.java
/** Print month body */
static void printMonthBody(int year, int month) {
// Get start day of the week for the first date in the month
int startDay = getStartDay(year, month);
// Get number of days in the month
int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month);
// Pad space before the first day of the month
int i = 0;
for (i = 0; i < startDay; i++)
System.out.print(“ “);
for (i = 1; i <= numberOfDaysInMonth; i++) {
if (i < 10)
System.out.print(“ “ + i);
else
System.out.print(“ “ + i);
if ((i + startDay) % 7 == 0)
System.out.println();
}
System.out.println();
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
102
PrintCalendar.java
/** Get the start day of month/1/year */
static int getStartDay(int year, int month) {
final int START_DAY_FOR_JAN_1_1800 = 3;
// Get total number of days from 1/1/1800 to month/1/year
int totalNumberOfDays = getTotalNumberOfDays(year, month);
// Return the start day for month/1/year
return (totalNumberOfDays + START_DAY_FOR_JAN_1_1800) % 7;
}
/** Get the total number of days since January 1, 1800 */
static int getTotalNumberOfDays(int year, int month) {
int total = 0;
// Get the total days from 1800 to 1/1/year
for (int i = 1800; i < year; i++)
if (isLeapYear(i))
total = total + 366;
else
total = total + 365;
// Add days from Jan to the month prior to the calendar month
for (int i = 1; i < month; i++)
total = total + getNumberOfDaysInMonth(year, i);
return total;
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
103
PrintCalendar.java
/** Get the number of days in a month */
static int getNumberOfDaysInMonth(int year, int month) {
if (month == 1 || month == 3 || month == 5 || month == 7
|| month == 8 || month == 10 || month == 12)
return 31;
if (month == 4 || month == 6 || month == 9 || month == 11)
return 30;
if (month == 2)
return isLeapYear(year) ? 29 : 28;
return 0; // If month is incorrect
}
/** Determine if it is a leap year */
static boolean isLeapYear(int year) {
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}
}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
104
Packages
 There are four reasons for using packages
1. To locate classes. Classes with similar functions can be
placed in the same package to make them easy to locate.
2. To avoid naming conflicts. two classes with the same
name. To prevent this, put your classes into packages so
that they can be referenced through package names.
3. To distribute software conveniently. Packages group
related classes so that they can be easily distributed.
4. To protect classes. Packages provide protection so that
the protected members of the classes are accessible to
the classes in the same package, but not to the external
classes.

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
105
Package-Naming Conventions
 Packages are hierarchical, and you can have packages
within packages.

For example, java.lang.Math
 Java designers recommend that you use your Internet
domain name in reverse order as a package prefix
 create a package named mypackage on a host machine
with the Internet domain name prenhall.com.
To follow the naming convention, you would name the
entire package com.prenhall.mypackage.
 By convention, package names are all in lowercase.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
106
Package Directories
 Java expects one-to-one mapping of the
package name and the file system directory
structure
set classpath=.;c:\book;
You can add as many directories as necessary in classpath. The
order in which the directories are specified is the order in which
the classes are searched. If you have two classes of the same
name in different directories, Java uses the first one it finds.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
107
Putting Classes into Packages
 package packagename;

the first noncomment and nonblank statement in
the program
1. Create Format.java and save it into
c:\book\com\prenhall\mypackage.
package com.prenhall.mypackage;
public class Format {
public static double format( double number, int numberOfDecimalDigits) {
return Math.round(number * Math.pow(10, numberOfDecimalDigits)) /
Math.pow(10, numberOfDecimalDigits); } }
2. Compile Format.java and place it in
c:\book\com\prenhall\mypackage.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
108
Using Classes from Packages
 There are two ways to use classes from a
package
1. One way is to use the fully qualified name of the
class
com.prenhall.mypackage.Format
2. use the import statement
 import javax.swing.*; called an import on demand
 import javax.swing.JOptionPane;
 The program uses an import statement to get the
class. You cannot import entire packages,
 such as com.prenhall.*.*
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
109