Chapter 6

Report
1
Chapter 6 - Methods
Outline
6.1
6.2
6.3
6.4
6.5
6.6
6.7
6.8
6.9
6.10
6.11
6.12
6.13
6.14
6.15
Introduction
Program Modules in Java
Math-Class Methods
Method Declarations
Argument Promotion
Java API Packages
Random-Number Generation
Example: A Game of Chance
Scope of Declarations
Methods of Class JApplet
Method Overloading
Recursion
Example Using Recursion: The Fibonacci Series
Recursion vs. Iteration
(Optional Case Study) Thinking About Objects: Identifying
Class Operations
 2003 Prentice Hall, Inc. All rights reserved.
2
6.1
Introduction
• Modules
– Small pieces of a problem
• e.g., divide and conquer
– Facilitate design, implementation, operation and
maintenance of large programs
 2003 Prentice Hall, Inc. All rights reserved.
3
6.2
Program Modules in Java
• Modules in Java
– Methods
– Classes
• Java API provides several modules
• Programmers can also create modules
– e.g., programmer-defined methods
• Methods
– Invoked by a method call
– Returns a result to calling method (caller)
– Similar to a boss (caller) asking a worker (called method) to
complete a task
 2003 Prentice Hall, Inc. All rights reserved.
4
boss
worker1
worker4
worker2
worker3
worker5
Fig. 6.1 Hierarchical boss-method/worker-method relationship.
 2003 Prentice Hall, Inc. All rights reserved.
5
6.3
Math-Class Methods
• Class java.lang.Math
– Provides common mathematical calculations
– Calculate the square root of 900.0:
• Math.sqrt( 900.0 )
– Method sqrt belongs to class Math
• Dot (.) allows access to method sqrt
– The argument 900.0 is located inside parentheses
 2003 Prentice Hall, Inc. All rights reserved.
6
M ethod
abs( x )
D escription
absolute value of x (this m ethod also has float, int and long versions)
ceil( x )
rounds x to the sm allest integer not less than x
cos( x )
exp( x )
trigonom etric cosine of x (x is in radians)
exponential m ethod ex
floor( x )
rounds x to the largest integer not greater than x
log( x )
natural logarithm of x (base e)
max( x, y )
pow( x, y )
larger value of x and y (this m ethod also has float, int and long
versions)
sm aller value of x and y (this m ethod also has float, int and long
versions)
x raised to the pow er y (xy)
sin( x )
sqrt( x )
trigonom etric sine of x (x is in radians)
square root of x
tan( x )
trigonom etric tangent of x (x is in radians)
min( x, y )
Fig. 6.2 Math -class m ethods.
 2003 Prentice Hall, Inc. All rights reserved.
E xam ple
abs( 23.7 ) is 23.7
abs( 0.0 ) is 0.0
abs( -23.7 ) is 23.7
ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0
cos( 0.0 ) is 1.0
exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
floor( 9.2 ) is 9.0
floor( -9.8 ) is -10.0
log( Math. E ) is 1.0
log( Math. E * Math.E ) is 2.0
max( 2.3, 12.7 ) is 12.7
max( -2.3, -12.7 ) is -2.3
min( 2.3, 12.7 ) is 2.3
min( -2.3, -12.7 ) is -12.7
pow( 2.0, 7.0 ) is 128.0
pow( 9.0, 0.5 ) is 3.0
sin( 0.0 ) is 0.0
sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( 0.0 ) is 0.0
7
6.4
Methods Declarations
• Methods
– Allow programmers to modularize programs
• Makes program development more manageable
• Software reusability
• Avoid repeating code
– Local variables
• Declared in method declaration
– Parameters
• Communicates information between methods via method calls
 2003 Prentice Hall, Inc. All rights reserved.
8
6.4
Method Declarations (Cont.)
• Programmers can write customized methods
 2003 Prentice Hall, Inc. All rights reserved.
9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Outline
// Fig. 6.3: SquareIntegers.java
// Creating and using a programmer-defined method.
import java.awt.Container;
import javax.swing.*;
Declare result to store
square of number
SquareIntegers.
java
public class SquareIntegers extends JApplet {
// set up GUI and calculate squares of integers from 1 to 10
Method init invokes
public void init()
method square (next slide)
{
// JTextArea to display results
JTextArea outputArea = new JTextArea();
// get applet's content pane (GUI component display area)
Container container = getContentPane();
// attach outputArea to container
container.add( outputArea );
int result;
String output = "";
// store result of call to method
// String containing results
Line 21
Declare result to
store square of number
Line 26
Method init invokes
method square
Method square returns int
Line 26
that result
stores
Method square
returns int that
square
result stores
// loop 10 times
for ( int counter = 1; counter <= 10; counter++ ) {
result = square( counter ); // method call
// append result to String output
output += "The square of " + counter + " is " + result + "\n";
} // end for
 2003 Prentice Hall, Inc.
All rights reserved.
10
32
33
34
35
36
37
38
39
40
41
42
43
44
outputArea.setText( output );
// place results in JTextArea
} // end method init
// square method declaration
public int square( int y )
{
return y * y; // return square of y
} // end method square
} // end class SquareIntegers
Outline
SquareIntegers.
java
y is the parameter of
method square
Method square
returns the square of y
Line 38
y is the parameter of
method square
Line 40
Method square
returns the square of y
 2003 Prentice Hall, Inc.
All rights reserved.
11
6.4
Method Declarations (cont.)
• General format of method declaration:
return-value-type method-name( parameter1, parameter2, …, parameterN )
{
declarations and statements
}
• Method can also return values:
return expression;
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
12
// Fig. 6.4: MaximumTest.java
// Finding the maximum of three floating-point numbers.
import java.awt.Container;
import javax.swing.*;
Outline
Maximum.java
User inputs three Strings
public class MaximumTest extends JApplet {
// initialize applet by obtaining user input and creating GUI
public void init()
{
// obtain user input
String s1 = JOptionPane.showInputDialog(
"Enter first floating-point value" );
String s2 = JOptionPane.showInputDialog(
"Enter second floating-point value" );
Convert Strings
String s3 = JOptionPane.showInputDialog(
"Enter third floating-point value" );
// convert user input to double values
double number1 = Double.parseDouble( s1 );
double number2 = Double.parseDouble( s2 );
double number3 = Double.parseDouble( s3 );
Lines 13-18
User inputs three
Strings
Lines 21-23
Convert Strings to
doubles
to doubles
Line 25
Method init passes
doubles as
arguments to method
Method maximum
init passes
doubles as arguments to
method maximum
double max = maximum( number1, number2, number3 ); // method call
// create JTextArea to display results
JTextArea outputArea = new JTextArea();
// display numbers and maximum value
outputArea.setText( "number1: " + number1 + "\nnumber2: " +
number2 + "\nnumber3: " + number3 + "\nmaximum is: " + max );
 2003 Prentice Hall, Inc.
All rights reserved.
13
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// get applet's GUI component display area
Container container = getContentPane();
// attach outputArea to Container c
container.add( outputArea );
Outline
Maximum.java
Method maximum returns value
Line 46
from method max of class Math
Method maximum
// maximum method uses Math class method max to help
returns value from
// determine maximum value
method max of class
public double maximum( double x, double y, double z )
Math
{
} // end method init
return Math.max( x, Math.max( y, z ) );
} // end method maximum
} // end class Maximum
 2003 Prentice Hall, Inc.
All rights reserved.
14
6.5
Argument Promotion
• Coercion of arguments
– Forcing arguments to appropriate type to pass to method
• e.g., System.out.println( Math.sqrt( 4 ) );
– Evaluates Math.sqrt( 4 )
– Then evaluates System.out.println()
• Promotion rules
– Specify how to convert types without data loss
 2003 Prentice Hall, Inc. All rights reserved.
15
T yp e
d o u b le
flo at
lo n g
in t
ch ar
sh o rt
by te
b o o lean
V a lid p ro m o tio n s
N one
d o u b le
flo at o r d o u b le
lo n g , flo at o r d ou b le
in t, lo n g , float o r d o u b le
in t, lo n g , float o r d o u b le
sh o rt, int, lo n g , flo at o r d o u b le
N o n e (b o o lean valu es are n o t co nsid ered to be
n u m b ers in Jav a)
F ig . 6 .5 A llo w e d p ro m o tio n s fo r p rim itiv e typ e s .
 2003 Prentice Hall, Inc. All rights reserved.
16
6.6
Java API Packages
• Packages
– Classes grouped into categories of related classes
– Promotes software reuse
– import statements specify classes used in Java programs
• e.g., import javax.swing.JApplet;
 2003 Prentice Hall, Inc. All rights reserved.
17
P a ck a g e
java.applet
D e s c rip tio n
java.awt
T h e Ja va A b stra ct W in do w To o lkit P a ckag e co n tain s th e classes an d interfaces req u ired to create an d m an ip u late
G U Is in Java 1 .0 and 1 .1. In Java 2 , th e S w in g G U I co m p o n en ts o f th e j a v a x . s w i n g p ackag es are o ften u sed
in stead .
java.awt.event
T h e Ja va A b stra ct W in do w To o lkit E ven t P a cka g e con tain s classes an d in terfaces th at en ab le even t han d lin g fo r
G U I co m p o n en ts in bo th th e j a va . a w t an d j a v a x . s w i n g p ackag es.
java.io
T h e Ja va In pu t/O utpu t P a cka g e co n tain s classes th at en ab le p ro gram s to inp u t an d ou tpu t d ata (see C h ap ter 17 ,
F iles an d S tream s).
java.lang
T h e Ja va L an gu ag e P a ckag e co n tain s classes an d in terfaces (d iscu ssed th rou gh ou t th is text) th at are req u ired b y
m an y Jav a p ro gram s. T h is p ackag e is im p o rted b y th e co m p iler in to all p ro gram s.
java.net
T h e Ja va N etw o rkin g P a ckag e con tain s classes th at en ab le p ro gram s to co m m u n icate via n etw o rk s (see
C h ap ter 18 , N etw o rkin g).
java.text
T h e Ja va T ext P a ckag e co n tain s classes an d in terfaces th at en ab le a Java p ro gram to m an ip u l ate n u m b ers, d ates,
ch aracters an d strin gs. T h e p ackage p ro vid es m an y o f Jav a’s in ternatio n alization cap ab ilities th at en ab le a
p ro gram to b e cu sto m ized to a specific lo cale (e.g., an ap p let m ay d isp lay strin gs in d ifferen t lan gu ages, b ased o n
th e u ser’s co un try).
java.util
T h e Ja va U tilities P a cka g e con tain s u tility classes an d in terfaces, su ch as d ate and tim e m an ip u lation s, rand o m n u m b er p ro cessin g cap ab ilities w ith class R a n d o m , sto rin g an d p ro cessin g large am o u n ts o f d ata an d b reakin g
strin gs in to sm a ller p ieces called to ken s w ith class S t r i n g T o k e n i z e r (see C h ap ter 2 0 ; D ata Stru ctu res,
C h ap ter 21 , Java U tilities P ackag e an d B it M an ip u latio n ; an d C h apter 2 2 , C o llectio n s).
javax.swing
T h e Ja va S w ing G U I C o m p on en ts P a cka g e con tain s classes an d interface s fo r Java’s S w in g G U I co m p o n en ts th at
p ro vid e sup po rt fo r p o rtab le G U Is.
javax.swing.event
T h e Ja va S w ing E ven t P a ckag e co n tain s classes an d in terfaces th at en ab le even t h and lin g fo r G U I co m p o n en ts in
p ackag e j a v a x . s w i n g .
F ig . 6 .6
T h e Ja va A p plet P a ckag e con tains th e A p p l e t class an d several in terfaces th at en ab le ap p let/b ro w ser in teraction
an d th e p layin g o f au d io clip s. In Java 2 , class j a v a x . s w i n g . J A p p l e t is u sed to d efin e an ap plet th at u ses th e
S w in g G U I co m p o n en ts.
J a va A P I pa ck a g es (a s ub s et).
 2003 Prentice Hall, Inc. All rights reserved.
18
6.7
Random-Number Generation
• Java random-number generators
– Math.random()
• ( int ) ( Math.random() * 6 )
– Produces integers from 0 - 5
– Use a seed for different random-number sequences
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
19
// Fig. 6.7: RandomIntegers.java
// Shifted, scaled random integers.
import javax.swing.JOptionPane;
Outline
RandomIntegers.
java
public class RandomIntegers {
public static void main( String args[] )
{
int value;
String output = "";
Produce integers in range 1-6
// loop 20 times
for ( int counter = 1; counter <= 20; counter++ ) {
// pick random integer between 1 and 6
value = 1 + ( int ) ( Math.random() * 6 );
output += value + "
";
// append value to output
Line 16
Produce integers in
range 1-6
Line 16
Math.random
returns doubles. We
cast the double as an
int
// if counter divisible by 5, append newline toMath.random
String output returns doubles.
if ( counter % 5 == 0 )
We cast the double as an int
output += "\n";
} // end for
 2003 Prentice Hall, Inc.
All rights reserved.
26
27
28
29
30
31
32
33
34
20
JOptionPane.showMessageDialog( null, output,
"20 Random Numbers from 1 to 6",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate application
Outline
RandomIntegers.
java
} // end main
} // end class RandomIntegers
 2003 Prentice Hall, Inc.
All rights reserved.
21
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Outline
// Fig. 6.8: RollDie.java
// Roll a six-sided die 6000 times.
import javax.swing.*;
RollDie.java
public class RollDie {
public static void main( String args[] )
{
Produce integers
int frequency1 = 0, frequency2 = 0, frequency3 = 0,
frequency4 = 0, frequency5 = 0, frequency6 = 0, face;
Line 14
in range 1-6Produce integers in
range 1-6
// summarize results
for ( int roll = 1; roll <= 6000; roll++ ) {
face = 1 + ( int ) ( Math.random() * 6 );
// determine roll value and increment appropriate counter
switch ( face ) {
case 1:
++frequency1;
break;
Lines 17-43
Increment appropriate
frequency counter,
depending on
randomly generated
number
Increment appropriate frequency counter,
depending on randomly generated number
case 2:
++frequency2;
break;
case 3:
++frequency3;
break;
 2003 Prentice Hall, Inc.
All rights reserved.
22
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
case 4:
++frequency4;
break;
case 5:
++frequency5;
break;
Outline
RollDie.java
case 6:
++frequency6;
break;
} // end switch
} // end for
JTextArea outputArea = new JTextArea();
outputArea.setText( "Face\tFrequency" + "\n1\t" + frequency1 +
"\n2\t" + frequency2 + "\n3\t" + frequency3 +
"\n4\t" + frequency4 + "\n5\t" + frequency5 +
"\n6\t" + frequency6 );
JOptionPane.showMessageDialog( null, outputArea,
"Rolling a Die 6000 Times", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate application
} // end main
} // end class RollDie
 2003 Prentice Hall, Inc.
All rights reserved.
23
 2003 Prentice Hall, Inc. All rights reserved.
24
6.8
Example: A Game of Chance
• Craps simulation
– Roll dice first time
• If sum equals 7 or 11, the player wins
• If sum equals 2, 3 or 12, the player loses
• Any other sum (4, 5, 6, 8, 9, 10) is that player’s point
– Keep rolling dice until…
• Sum matches player point
– Player wins
• Sum equals 7
– Player loses
 2003 Prentice Hall, Inc. All rights reserved.
25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Outline
// Fig. 6.9: Craps.java
// Craps.
import java.awt.*;
import java.awt.event.*;
// Container, FlowLayout
// ActionEvent, ActionListener
import javax.swing.*;
// JApplet, JButton, JLabel, JTextField
public class Craps extends JApplet implements ActionListener {
// constant variables for game status
final int WON = 0, LOST = 1, CONTINUE = 2;
boolean firstRoll = true;
int sumOfDice = 0;
int myPoint = 0;
int gameStatus = CONTINUE;
//
//
//
//
Craps.java
Line 24
Method init starts
JApplet and
initializes GUI
true if first roll of dice
sum of the dice
point if no win or loss on first roll
game not over yet
// graphical user interface components
JLabel die1Label, die2Label, sumLabel, pointLabel;
JTextField die1Field, die2Field, sumField, pointField;
JButton rollButton;
Method init starts JApplet
and initializes GUI (Chapter 12
covers GUI in detail)
// set up GUI components
public void init()
{
// obtain content pane and change its layout to FlowLayout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
 2003 Prentice Hall, Inc.
All rights reserved.
26
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// create label and text field for die 1
die1Label = new JLabel( "Die 1" );
container.add( die1Label );
die1Field = new JTextField( 10 );
die1Field.setEditable( false );
container.add( die1Field );
// create label and text field for die 2
die2Label = new JLabel( "Die 2" );
container.add( die2Label );
die2Field = new JTextField( 10 );
die2Field.setEditable( false );
container.add( die2Field );
// create label and text field for sum
sumLabel = new JLabel( "Sum is" );
container.add( sumLabel );
sumField = new JTextField( 10 );
sumField.setEditable( false );
container.add( sumField );
// create label and text field for point
pointLabel = new JLabel( "Point is" );
container.add( pointLabel );
pointField = new JTextField( 10 );
pointField.setEditable( false );
container.add( pointField );
Outline
JTextField that
output dice results
JTextField that
output dice results
JTextField that
outputs sum of dice
Craps.java
Lines 33
JTextField that
output dice results
Line 40
JTextField that
output dice results
Line 47
JTextField that
outputs sum of dice
Line 54
JTextField that
outputs player’s point
JTextField that
outputs player’s point
 2003 Prentice Hall, Inc.
All rights reserved.
27
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// create button user clicks to roll dice
rollButton = new JButton( "Roll Dice" );
rollButton.addActionListener( this );
container.add( rollButton );
Outline
JButton for rolling dice Craps.java
} // end method init
// process one roll of dice
public void actionPerformed( ActionEvent actionEvent )
{
sumOfDice = rollDice(); // roll Method
dice
invoked when
// first roll of dice
if ( firstRoll ) {
Line 59
JButton for rolling
dice
user presses JButton
Line 66
Invoke method rollDice
Method invoked when
user presses
JButton
switch ( sumOfDice ) {
// win on first roll
case 7:
If sum is 7 or 11, user wins
case 11:
gameStatus = WON;
pointField.setText( "" ); // clear point field
break;
// lose on first roll
If user rolls 2, 3 or 12, user loses
case 2:
case 3:
case 12:
gameStatus = LOST;
pointField.setText( "" ); // clear point field
break;
Line 68
Invoke method
rollDice
Lines 76-80
If sum is 7 or 11, user
wins
Lines 83-88
If user rolls 2, 3 or
12, user loses
 2003 Prentice Hall, Inc.
All rights reserved.
28
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
If sum is 4, 5, 6, 8, 9 or
// remember point
sum is the point
default:
gameStatus = CONTINUE;
myPoint = sumOfDice;
pointField.setText( Integer.toString( myPoint ) );
firstRoll = false;
break;
} // end switch
Outline
10, that
Craps.java
Lines 91-96
If sum is 4, 5, 6, 8, 9
or 10, that sum is the
point
} // end if part of if...else
else { // subsequent roll of dice
// determine game status
if ( sumOfDice == myPoint )
gameStatus = WON;
else
if ( sumOfDice == 7 )
gameStatus = LOST;
// win by making point
Lines 105-109
If sum equals point,
user wins; If sum
equals 7, user loses
If sum equals point, user wins;
If sum equals 7, user loses
// lose by rolling 7
} // end else part of if...else
displayMessage();
// display message indicating game status
} // end method actionPerformed
 2003 Prentice Hall, Inc.
All rights reserved.
29
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
// roll dice, calculate sum and
display
results
Method
rollDice
uses Math.random
public int rollDice()
to simulate rolling two dice
{
// pick random die values
int die1 = 1 + ( int ) ( Math.random() * 6 );
int die2 = 1 + ( int ) ( Math.random() * 6 );
int sum = die1 + die2;
// sum die values
// display results in textfields
die1Field.setText( Integer.toString( die1 ) );
die2Field.setText( Integer.toString( die2 ) );
sumField.setText( Integer.toString( sum ) );
return sum;
return dice sum
// return sum of dice
Outline
Craps.java
Lines 121-122
Method rollDice
uses Math.random
to simulate rolling two
dice
Line 131
return dice sum
} // end method rollDice
// determine game status; display appropriate message in status bar
public void displayMessage()
{
// game should continue
if ( gameStatus == CONTINUE )
showStatus( "Roll again." );
 2003 Prentice Hall, Inc.
All rights reserved.
30
142
143
144
145
146
147
148
149
150
151
152
153
154
155
else { // game won or lost
if ( gameStatus == WON )
showStatus( "Player wins. Click Roll Dice to play again." );
else
showStatus( "Player loses. Click Roll Dice to play again." );
firstRoll = true;
Outline
Craps.java
// next roll is first roll of new game
} // end else part of if...else
} // end method displayMessage
} // end class Craps
 2003 Prentice Hall, Inc.
All rights reserved.
31
Outline
Craps.java
 2003 Prentice Hall, Inc.
All rights reserved.
32
6.9 Scope of Declarations
• Scope
– Portion of the program that can reference an entity by its
name
– Basic scope rules
•
•
•
•
Scope of a parameter declaration
Scope of a local-variable declaration
Scope of a label in a labeled break or continue statement
Scope of a local-variable declaration that appears in the
initialization section of a for statement’s header
• Scope of a method or field of a class
 2003 Prentice Hall, Inc. All rights reserved.
33
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Outline
// Fig. 6.10: Scoping.java
// A scoping example.
import java.awt.Container;
import javax.swing.*;
Field x has class scope
Line 11
field x
public class Scoping extends JApplet {
JTextArea outputArea;
// field that is accessible to all methods of this class
int x = 1;
// create applet's GUI
public void init()
{
outputArea = new JTextArea();
Container container = getContentPane();
container.add( outputArea );
} // end method init
Scoping.java
Line 26
Local variable x
Line 28
Method start uses
local variable x
Local variable x has block scope
// method start called after init completes; start calls
// methods useLocal and useField
Method start uses
public void start()
local variable x
{
int x = 5;
// local variable in method start that shadows field x
outputArea.append( "local x in start is " + x );
 2003 Prentice Hall, Inc.
All rights reserved.
34
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
useLocal();
useField();
useLocal();
useField();
//
//
//
//
Outline
useLocal has local x
useInstance uses Scoping's field x
useLocal reinitializes local x
Scoping's field x retains its value
Scoping.java
outputArea.append( "\n\nlocal x in start is " + x );
} // end method start
Re-create
variable
x x during each call
// useLocal creates and initializes
local
variable
public void useLocal()
and initialize it to 25
{
int x = 25; // initialized each time useLocal is called
outputArea.append( "\n\nlocal
" after entering useLocal"
++x;
outputArea.append( "\nlocal x
" before exiting useLocal"
x in useLocal is " + x +
);
in useLocal is " + x +
);
Line 42
Recreate variable x
and initialize it to 25
Lines 40-50
Method useLocal
uses local variable x
Method useLocal
uses local variable x
} // end method useLocal
 2003 Prentice Hall, Inc.
All rights reserved.
35
52
53
54
55
56
57
58
59
60
61
62
63
// useField modifies Scoping's field x during each call
public void useField()
{
outputArea.append( "\n\nfield x is " + x +
" on entering useField" );
x *= 10;
outputArea.append( "\nfield x is " + x +
" on exiting useField" );
} // end method useInstance
Outline
Scoping.java
Lines 53-61
Method useField
Method useField
uses field x
uses field x
} // end class Scoping
 2003 Prentice Hall, Inc.
All rights reserved.
36
6.16 Methods of Class JApplet
• Java API defines several JApplet methods
– Defining methods of Fig. 6.11 in a JApplet is called
overriding those methods.
 2003 Prentice Hall, Inc. All rights reserved.
37
M e th o d
p ub lic vo id
init()
W he n th e m e th o d is c a lle d a n d its p u rp o s e
T his m etho d is called o nce b y the ap p let co ntainer w h e n an a p p let is lo ad ed fo r executio n. It p erfo rm s in itializatio n o f a n
ap p let. T yp ical actio n s p erfo rm ed here are initia lizing fiel d s, creating G U I co m p o ne nts, lo ad ing so und s to p la y, lo ad ing im age s
to d isp lay (see C hap ter 1 9 , M ultim ed ia) and creatin g thread s (see C hap ter 1 6 , M ultithread ing).
p ub lic vo id
start()
T his m etho d is called after the i n i t m e tho d co m p letes e xe cutio n. In a d d itio n, if the b ro w ser user v isits ano ther W eb site and
later returns to the H T M L p ag e o n w hic h the ap p let resid es, m etho d s t a r t is called a gain . T he m etho d p erfo rm s an y tasks
that m u st b e co m p leted w he n the ap p let is lo ad ed fo r the first tim e and that m u st b e p erfo rm ed every tim e the H T M L p age o n
w h ic h the ap p let resid es is re v isited . T yp ical actio n s p erfo rm ed here includ e startin g an a nim atio n (see C hap ter 1 9 ) and
startin g o ther thread s o f exec u tio n (see C hap ter 1 6 ).
p ub lic vo id
paint(
Graphics g )
T his d ra w in g m etho d is called after the i n i t m e tho d co m p letes exec utio n a nd the s t a r t m etho d ha s started . It is also called
every tim e the ap p let need s to b e rep ainted . F o r exam p le, if the u ser co vers the ap p let w ith ano ther o p en w ind o w o n the screen
and later unco vers the ap p let, the p a i n t m etho d is called . T yp ica l actio n s p erfo rm ed here invo lve d ra w in g w ith the
G r a p h i c s o b ject g that is p assed to the p a i n t m e tho d b y the ap p let co ntainer.
p ub lic vo id
stop()
T his m etho d is called w he n th e ap p let sho uld s to p execu tin g — no rm ally, w h en the user o f the b ro w ser lea ves the H T M L p age
o n w hic h the ap p let resid es. T he m etho d p erfo rm s a n y ta sk s that are req uired to susp end th e ap p let’s exec utio n. T yp ical
actio ns p erfo rm ed here are to sto p executio n o f an im a tio n s and thread s.
p ub lic vo id
destroy()
T his m etho d is called w he n th e ap p let is b eing re m o ved fro m m e m o ry — no rm ally, w h e n the u ser o f the b ro w ser exits th e
b ro w sing se ssio n (i.e., clo ses all b ro w ser w ind o w s). T he m e tho d p erfo rm s an y task s that a re req uired to d estro y reso urce s
allo cated to the ap p let.
F ig . 6 .1 1
J A p p l e t m e th o d s th a t th e a p p le t c o n ta in e r c a lls d u rin g a n a p p le t’s e x e c u tio n .
 2003 Prentice Hall, Inc. All rights reserved.
38
6.15 Method Overloading
• Method overloading
– Several methods of the same name
– Different parameter set for each method
• Number of parameters
• Parameter types
 2003 Prentice Hall, Inc. All rights reserved.
39
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Outline
// Fig. 6.12: MethodOverload.java
// Using overloaded methods
import java.awt.Container;
MethodOverload.
java
import javax.swing.*;
public class MethodOverload extends JApplet {
// create GUI and call each square method
public void init()
{
JTextArea outputArea = new JTextArea();
Container container = getContentPane();
container.add( outputArea );
Lines 22-29
Method square
receives an int as an
argument
outputArea.setText( "The square of integer 7 is " + square( 7 ) +
"\nThe square of double 7.5 is " + square( 7.5 ) );
} // end method init
Method square receives an
// square method with int argument
int as an argument
public int square( int intValue )
{
System.out.println( "Called square with int argument: " +
intValue );
return intValue * intValue;
} // end method square with int argument
 2003 Prentice Hall, Inc.
All rights reserved.
40
31
32
33
34
35
36
37
38
39
40
41
// square method with double argument
public double square( double doubleValue )
{
System.out.println( "Called square with double argument: " +
doubleValue );
Outline
MethodOverload.
java
return doubleValue * doubleValue;
} // end method square with double argument
} // end class MethodOverload
Lines 32-39
Overloaded method
square receives a
Overloaded method square
double as an
receives a double as an argument
argument
Called square with int argument: 7
Called square with double argument: 7.5
 2003 Prentice Hall, Inc.
All rights reserved.
41
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Outline
// Fig. 6.13: MethodOverload.java
// Overloaded methods with identical signatures.
import javax.swing.JApplet;
MethodOverload.
java
public class MethodOverload extends JApplet {
// declaration of method square with int argument
Lines 8 and 15
public int square( int x )
{
Compiler cannot distinguish betweenCompiler cannot
return x * x;
methods with identical names and distinguish between
}
parameter sets
// second declaration of method square
// with int argument causes syntax error
public double square( int y )
{
return y * y;
}
methods with identical
names and parameter
sets
} // end class MethodOverload
MethodOverload.java:15: square(int) is already defined in MethodOverload
public double square( int y )
^
1 error
Fig. 6.17 Compiler
error messages
generated from
overloaded methods
with identical
parameter lists and
different return types.
 2003 Prentice Hall, Inc.
All rights reserved.
42
6.12 Recursion
• Recursive method
– Calls itself (directly or indirectly) through another method
– Method knows how to solve only a base case
– Method divides problem
• Base case
• Simpler problem
– Method now divides simpler problem until solvable
– Recursive call
– Recursive step
 2003 Prentice Hall, Inc. All rights reserved.
43
Final value = 120
5!
5!
5! = 5 * 24 = 120 is returned
5 * 4!
5 * 4!
4! = 4 * 6 = 24 is returned
4 * 3!
4 * 3!
3! = 3 * 2 = 6 is returned
3 * 2!
3 * 2!
2! = 2 * 1 = 2 is returned
2 * 1!
2 * 1!
1 returned
1
1
(a) Sequence of recursive calls.
(b) Values returned from each recursive call.
Fig. 6.14 Recursive evaluation of 5!.
 2003 Prentice Hall, Inc. All rights reserved.
44
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Outline
// Fig. 6.15: FactorialTest.java
// Recursive factorial method.
import java.awt.*;
FactorialTest.j
ava
import javax.swing.*;
public class FactorialTest extends JApplet {
JTextArea outputArea;
// create GUI and calculate factorials of 0-10
public void init()
{
outputArea = new JTextArea();
Line 21
Invoke method
factorial
Invoke method factorial
Container container = getContentPane();
container.add( outputArea );
// calculate the factorials of 0 through 10
for ( long counter = 0; counter <= 10; counter++ )
outputArea.append( counter + "! = " +
factorial( counter ) + "\n" );
} // end method init
 2003 Prentice Hall, Inc.
All rights reserved.
45
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// recursive declaration of method factorial
public long factorial( long number )
{
// base case
if ( number <= 1 )
return 1;
// recursive step
else
return number * factorial( number - 1 );
} // end method factorial
} // end class FactorialTest
Outline
Test for base case
(method factorial
can solve base case)
FactorialTest.j
ava
Lines 29-30
Else return simpler Test
problem
that case
for base
method factorial
might solve
(method
factorial
in next recursive
call
can solve base case)
Line 34
Else return simpler
problem that method
factorial might
solve in next recursive
call
 2003 Prentice Hall, Inc.
All rights reserved.
46
6.13 Example Using Recursion: The
Fibonacci Series
• Fibonacci series
– Each number in the series is sum of two previous numbers
• e.g., 0, 1, 1, 2, 3, 5, 8, 13, 21…
fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(n) = fibonacci(n - 1) + fibonacci( n – 1 )
• fibonacci(0) and fibonacci(1) are base cases
– Golden ratio (golden mean)
 2003 Prentice Hall, Inc. All rights reserved.
47
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Fig. 6.16: FibonacciTest.java
// Recursive fibonacci method.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Outline
FibonacciTest.j
ava
public class FibonacciTest extends JApplet implements ActionListener {
JLabel numberLabel, resultLabel;
JTextField numberField, resultField;
// set up applet’s GUI
public void init()
{
// obtain content pane and set its layout to FlowLayout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// create numberLabel and attach it to content pane
numberLabel = new JLabel( "Enter an integer and press Enter" );
container.add( numberLabel );
// create numberField and attach it to content pane
numberField = new JTextField( 10 );
container.add( numberField );
// register this applet as numberField’s ActionListener
numberField.addActionListener( this );
 2003 Prentice Hall, Inc.
All rights reserved.
48
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// create resultLabel and attach it to content pane
resultLabel = new JLabel( "Fibonacci value is" );
container.add( resultLabel );
// create numberField, make it uneditable
// and attach it to content pane
resultField = new JTextField( 15 );
resultField.setEditable( false );
container.add( resultField );
} // end method init
// obtain user input and call method fibonacci
public void actionPerformed( ActionEvent event )
{
long number, fibonacciValue;
// obtain user’s input and convert to long
number = Long.parseLong( numberField.getText() );
showStatus( "Calculating ..." );
Outline
FibonacciTest.j
ava
Line 43
Method
actionPerformed
is invoked when user
presses Enter
Method actionPerformed
is
Line 45
invoked when user
Enter
Wepresses
use long,
because Fibonacci
We use long, because
numbers become large
Fibonacci numbers
quickly
become large quickly
Lines 48-53
Pass user input to
method fibonacci
// calculate fibonacci value for number user input
fibonacciValue = fibonacci( number );
Pass user input to method fibonacci
// indicate processing complete and display result
showStatus( "Done." );
resultField.setText( Long.toString( fibonacciValue ) );
} // end method actionPerformed
 2003 Prentice Hall, Inc.
All rights reserved.
49
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// recursive declaration of method fibonacci
public long fibonacci( long n )
{
// base case
if ( n == 0 || n == 1 )
return n;
Outline
Test for base case
(method fibonacci
can solve base case)
// recursive step
else
return fibonacci( n - 1 ) + fibonacci( n - 2 );
} // end method fibonacci
} // end class FibonacciTest
FibonacciTest.j
ava
Else return simpler problem
that
Lines 65-66
method fibonacciTest
might
for solve
base case
in next recursive
call fibonacci
(method
can solve base case)
Lines 69-70
Else return simpler
problem that method
fibonacci might
solve in next recursive
call
 2003 Prentice Hall, Inc.
All rights reserved.
50
Outline
FibonacciTest.j
ava
 2003 Prentice Hall, Inc.
All rights reserved.
51
Outline
FibonacciTest.j
ava
 2003 Prentice Hall, Inc.
All rights reserved.
52
fibonacci( 3 )
return
return
fibonacci( 1 )
return 1
fibonacci( 2 )
+
+
fibonacci( 1 )
fibonacci( 0 )
return 0
Fig. 6.17 Set of recursive calls for fibonacci (3).
 2003 Prentice Hall, Inc. All rights reserved.
return 1
53
6.14 Recursion vs. Iteration
• Iteration
–
–
–
–
Uses repetition structures (for, while or do…while)
Repetition through explicitly use of repetition structure
Terminates when loop-continuation condition fails
Controls repetition by using a counter
• Recursion
–
–
–
–
Uses selection structures (if, if…else or switch)
Repetition through repeated method calls
Terminates when base case is satisfied
Controls repetition by dividing problem into simpler one
 2003 Prentice Hall, Inc. All rights reserved.
54
6.14 Recursion vs. Iteration (cont.)
• Recursion
–
–
–
–
More overhead than iteration
More memory intensive than iteration
Can also be solved iteratively
Often can be implemented with only a few lines of code
 2003 Prentice Hall, Inc. All rights reserved.
55
C h a p te r
6
7
20
F ig . 6.1 8
R e c u rsio n e xa m p le s a nd e xe rc is e s
F acto rial m etho d (Fig. 6 .1 5), F ib on acci m ethod (F ig . 6 .1 6), R aising an in teg er to an
integ er p o w er (E x ercise 6 .3 6), T o w ers o f H ano i (E xercise 6 .37 ), V isu alizing recu rsion
(E x ercise 6 .39 ), G reatest co m m o n d iviso r (E x ercise 6 .40 ), W h at d oes this m etho d
d o?(E x ercise 6 .43 ), Find th e erro r in the recu rsiv e m eth od (E xercise 6 .4 5 )
W h at d oes this p rog ram d o? (E x ercise 7 .16 ), W h at do es th is p ro g ram d o ?
(E x ercise 7 .19 ), D eterm in e w h eth er a string is a p alind ro m e (E x ercis e 7 .32 ), L inear
search (E xercise 7 .33), B in ary search (E xercise 7 .3 4), E igh t Q ueens (E x ercise 7 .35 )
P rin t an array (E x ercise 7 .3 6), P rin t an array b ack w ard (E xercise 7 .37 ), M inim u m v alu e
in an array (E x ercise 7 .38 ), Q uickso rt (E x ercise 7 .3 9), M aze traversal (E x ercise 7 .40 )
B inary-tree in sert (Fig . 20 .17 ), P reo rd er trav ersal o f a b in ary tree (F ig . 20 .17 ), Ino rd er
trav ersal o f a b in ary tree (F ig . 20 .17 ), Po sto rder trav ersal o f a bin ary tree (F ig . 20 .17 ),
P rin t a lin ked list b ack w ard (E x ercise 20 .20 ), S earch a lin ked list (E x ercise 20 .2 1 )
S u m m a ry o f rec u rs io n e xa m p le s a n d exe rc is e s in th is te xt.
 2003 Prentice Hall, Inc. All rights reserved.
56
6.15 (Optional Case Study) Thinking About
Objects: Identifying Class Operations
• Class operations
– Also known as behaviors
– Service the class provides to “clients” (users) of that class
• e.g., radio’s operations
– Setting its station or volume
 2003 Prentice Hall, Inc. All rights reserved.
57
6.15 Thinking About Objects (cont.)
• Deriving class operations
– Use problem statement
• Identify verbs and verb phrases
• Verbs can help determine class operations
 2003 Prentice Hall, Inc. All rights reserved.
58
C la ss
Elevator
V e rb p h ra se s
m oves to other floor, arrives at a floor, resets elevator
button, rings elevator bell, signals its arrival, opens its
door, closes its door
ElevatorShaft
turns off light, turns on light, resets floor button
Person
w alks on floor, presses floor button, presses elevator
button, rides elevator, enters elevator, exits elevator
Floor
[none in the problem statem ent]
FloorButton
requests elevator
E l e v a t o r B u t t o n closes elevator door, signals elevator to m ove to opposite
floor
FloorDoor
signals person to enter elevator (by opening)
ElevatorDoor
signals person to exit elevator (by opening), opens floor
door, closes floor door
Bell
[none in the problem statem ent]
Light
[none in the problem statem ent]
F ig . 6 .1 9
V e rb p h ra se s fo r e a c h cla ss in sim u la to r.
 2003 Prentice Hall, Inc. All rights reserved.
59
6.15 Thinking About Objects (cont.)
• Deriving class operations
– Verbs can help determine class operations
• e.g., verb phrase “resets elevator button”
– Elevator informs ElevatorButton to reset
– ElevatorButton needs method resetButton
• e.g., verb phrase “signal its arrival”
– Elevator informs ElevatorDoor to open
– ElevatorDoor needs method openDoor
 2003 Prentice Hall, Inc. All rights reserved.
60
6.17 Thinking About Objects (cont.)
• Deriving class operations
– Not all verbs determine class operations
• e.g., verb phrase “the elevator arrives at a floor”
– Elevator decides when to arrive
• (after traveling 5 seconds)
– i.e., no object causes Elevator to arrive
– Elevator does not need to provide “arrival” service for
other objects
– arriveElevator is not a valid method (operation)
• We do not include method arriveElevator
 2003 Prentice Hall, Inc. All rights reserved.
61
6.17 Thinking About Objects (cont.)
• Store methods (operations) in UML class diagram
– Place class methods in bottom compartment of that class
 2003 Prentice Hall, Inc. All rights reserved.
62
Person
ElevatorShaft
ID : Integer
moving : Boolean = true
open : Boolean = false
openDoor( )
closeDoor( )
doorOpened( )
Elevator
moving : Boolean = false
summoned : Boolean = false
currentFloor : Integer = 1
destinationFloor : Integer = 2
capacity : Integer = 1
travelTime : Integer = 5
ElevatorDoor
Floor
floorNumber : Integer
capacity : Integer = 1
Light
lightOn : Boolean = false
turnOnLight( )
turnOffLight( )
ElevatorButton
ride( )
requestElevator( )
enterElevator( )
exitElevator( )
departElevator( )
FloorButton
pressed : Boolean = false
resetButton( )
pressButton( )
FloorDoor
pressed : Boolean = false
open : Boolean = false
resetButton( )
pressButton( )
openDoor( )
closeDoor( )
Fig 6.20 Classes with attributes and operations.
 2003 Prentice Hall, Inc. All rights reserved.
Bell
ringBell( )

similar documents