Transcript Lecture 5

1
Chapter 6 - Methods
 2003 Prentice Hall, Inc. All rights reserved.
2
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.
Method
abs( x )
ceil( x )
cos( x )
exp( x )
floor( x )
log( x )
max( x, y )
min( x, y )
pow( x, y )
sin( x )
sqrt( x )
tan( x )
Fig. 6.2 Math-class methods.
Description
Example
absolute value of x (this method also has float, int and long versions) abs( 23.7 ) is 23.7
abs( 0.0 ) is 0.0
abs( -23.7 ) is 23.7
rounds x to the smallest integer not less than x
ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0
trigonometric cosine of x (x is in radians)
cos( 0.0 ) is 1.0
exponential method ex
exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
rounds x to the largest integer not greater than x
floor( 9.2 ) is 9.0
floor( -9.8 ) is -10.0
natural logarithm of x (base e)
log( Math.E ) is 1.0
log( Math.E * Math.E ) is 2.0
larger value of x and y (this method also has float, int and long
max( 2.3, 12.7 ) is 12.7
versions)
max( -2.3, -12.7 ) is -2.3
smaller value of x and y (this method also has float, int and long
min( 2.3, 12.7 ) is 2.3
versions)
min( -2.3, -12.7 ) is -12.7
x raised to the power y (xy)
pow( 2.0, 7.0 ) is 128.0
pow( 9.0, 0.5 ) is 3.0
trigonometric sine of x (x is in radians)
sin( 0.0 ) is 0.0
square root of x
sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
trigonometric tangent of x (x is in radians)
tan( 0.0 ) is 0.0
 2003 Prentice Hall, Inc. All rights reserved.
3
4
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.
5
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.
6
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.
7
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
8
// 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.
9
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.
10
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.
11
Type
double
float
long
int
char
short
byte
boolean
Valid promotions
None
double
float or double
long, float or double
int, long, float or double
int, long, float or double
short, int, long, float or double
None (boolean values are not considered to be
numbers in Java)
Fig. 6.5 Allowed promotions for primitive types.
 2003 Prentice Hall, Inc. All rights reserved.
12
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.
GUIs in Java 1.0 and 1.1. In Java 2, the Swing GUI components of the javax.swing packag
13
instead.
java.awt.event
The Java Abstract Window Toolkit Event Package contains classes and interfaces that enable
GUI components in both the java.awt and javax.swing packages.
java.io
The Java Input/Output Package contains classes that enable programs to input and output da
Files and Streams).
java.lang
The Java Language Package contains classes and interfaces (discussed throughout this text)
many Java programs. This package is imported by the compiler into all programs.
java.net
The Java Networking Package contains classes that enable programs to communicate via net
Chapter 18, Networking).
java.text
The Java Text Package contains classes and interfaces that enable a Java program to manipu
characters and strings. The package provides many of Java’s internationalization capabilities
program to be customized to a specific locale (e.g., an applet may display strings in different
the user’s country).
java.util
The Java Utilities Package contains utility classes and interfaces, such as date and time mani
number processing capabilities with class Random, storing and processing large amounts of d
strings into smaller pieces called tokens with class StringTokenizer (see Chapter 20; Data
Chapter 21, Java Utilities Package and Bit Manipulation; and Chapter 22, Collections).
javax.swing
The Java Swing GUI Components Package contains classes and interfaces for Java’s Swing G
provide support for portable GUIs.
javax.swing.event
The Java Swing Event Package contains classes and interfaces that enable event handling for
package javax.swing.
Fig. 6.6
Java API packages (a subset).
 2003 Prentice Hall, Inc. All rights reserved.
14
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
15
// 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
16
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.
17
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.
18
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.
19
 2003 Prentice Hall, Inc. All rights reserved.
20
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.
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
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.
22
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.
23
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.
24
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.
25
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.
26
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.
27
Outline
Craps.java
 2003 Prentice Hall, Inc.
All rights reserved.
28
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.
29
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.
30
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.
31
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.
32
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.
Method
When the method is called and its purpose
public void
init()
This method is called once by the applet container when an applet is loaded for
execution. It performs initialization of an applet. Typical actions performed here are
initializing fields, creating GUI components, loading sounds to play, loading images
to display (see Chapter 19, Multimedia) and creating threads (see Chapter 16,
Multithreading).
public void
start()
This method is called after the init method completes execution. In addition, if the
browser user visits another Web site and later returns to the HTML page on which
the applet resides, method start is called again. The method performs any tasks
that must be completed when the applet is loaded for the first time and that must be
performed every time the HTML page on which the applet resides is revisited.
Typical actions performed here include starting an animation (see Chapter 19) and
starting other threads of execution (see Chapter 16).
public void
paint(
Graphics g )
This drawing method is called after the init method completes execution and the
start method has started. It is also called every time the applet needs to be
repainted. For example, if the user covers the applet with another open window on
the screen and later uncovers the applet, the paint method is called. Typical
actions performed here involve drawing with the Graphics object g that is passed
to the paint method by the applet container.
 2003 Prentice Hall, Inc. All rights reserved.
33
Method
When the method is called and its purpose
public void
stop()
This method is called when the applet should stop executing—normally,
when the user of the browser leaves the HTML page on which the applet
resides. The method performs any tasks that are required to suspend the
applet’s execution. Typical actions performed here are to stop execution of
animations and threads.
public void
destroy(
)
This method is called when the applet is being removed from memory—
normally, when the user of the browser exits the browsing session (i.e., closes
all browser windows). The method performs any tasks that are required to
destroy resources allocated to the applet.
Fig. 6.11 JApplet methods that the applet container calls during an applet’s execution.
 2003 Prentice Hall, Inc. All rights reserved.
34
35
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.
36
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.
37
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.
38
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.
39
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.
40
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.
41
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.
42
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.
43
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 – 2 )
• fibonacci(0) and fibonacci(1) are base cases
– Golden ratio (golden mean)
 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
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.
45
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.
46
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.
47
Outline
FibonacciTest.j
ava
 2003 Prentice Hall, Inc.
All rights reserved.
48
Outline
FibonacciTest.j
ava
 2003 Prentice Hall, Inc.
All rights reserved.
49
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
50
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.
51
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.