Java Programming:
From the Ground Up
Chapter 6
Methods
Methods
• A method is a named sequence of instructions that are
grouped together to perform a task.
• Methods enable the programmer to organize various tasks
into neat manageable independent bundles of code. Every
Java application that we have written contains one method;
its name is main and its instructions appear between the
opening and closing braces of main.
• Every Java application must have a main method, and the
execution of every Java application begins with the main
method.
• Other methods that we have used are print(...), println(...),
and [Link]().
Java's Pre-defined Methods
Imagine a mathematical “black box” that works in such a way
that whenever you supply a number to the box, the box gives
or returns the positive square root of that number.
A square root box
A similar mechanism that accepts two numbers, the length and
width of a rectangle, and returns the area of the rectangle.
An area box
Such a “box” is a metaphor for a method. A
method is very much like a mathematical
function – a black box that computes an
output given some inputs.
Java's Pre-defined Methods
• The values that you supply or pass to the method are called
arguments. The value computed by the method is the
returned value.
• Java comes bundled with an extraordinary number of
methods. You can use these methods to perform various
calculations but you need not be concerned with their
implementations.
The Square Root Method
Example:
In general, the distance to the horizon (in miles) can be
estimated as follows:
Determine the distance (in feet) from sea level to your eyes.
Compute the square root of that distance.
Multiply the result by 1.23.
Problem statement:
Write a program that prompts a user for the distance measured
from the ground to his/her eyes and calculates the distance to
the horizon.
The Square Root Method
1. import [Link].*;
2. public class DistanceToHorizon
3. {
4. public static void main(String[] args)
5. {
6. Scanner input;
7. double distanceToEyes; // measured from the ground
8. double distanceToHorizon;
9. int answer = 1; // used to repeat the calculation
10. input = new Scanner([Link]);
11. do
12. {
13. [Link]("Distance from the ground to your eyes in feet: ");
14. distanceToEyes =[Link]();
15. distanceToHorizon = 1.23 * [Link](distanceToEyes);
16. [Link]("The distance to the horizon is "+
distanceToHorizon+" mi.");
17. [Link]("Again? 1 for YES; any other number to Exit: ");
18. answer = [Link]();
19. }while (answer == 1);
20. }
21. }
Output
Distance from the ground to your eyes in feet: 16.0
The distance to the horizon is 4.92 mi.
Again? 1 for YES; any other number to Exit: 1
Distance from the ground to your eyes in feet: 5.25
The distance to the horizon is 2.8182840523978414 mi
Again? 1 for YES; any other number to Exit: 0
Discussion
The program utilizes the method :
double [Link](double x)
to calculate the square root of distanceToEyes.
• The method [Link](…) hides the details of its
implementation.
• How the square root of a number is calculated is hidden from
the programmer.
• The argument passed to the method is distanceToEyes,
and the returned value is the square root of distanceToEyes.
• If distanceToEyes has the value 16.0, then
[Link](distanceToEyes) returns the value 4.0 and that value
is used in the expression
distanceToHorizon = 1.23 * [Link](distanceToEyes);
The Square Root Method
The effect of this statement
double root= [Link](25.0);
is that variable root is assigned the value 5.0, the square root of
25.0.
•This method, which calculates square root, is a member of Java's
Math class.
•The Math class is a Java-supplied collection (or library) of
methods that performs mathematical tasks or functions.
[Link](…) is one of several methods in the Math class.
•The name of the method is sqrt, and the argument that is supplied
to the method is the number 25.0.
[Link](double x)
Notice the period that separates the class name Math
from the method, sqrt.
The Square Root Method
In the statement
double root = [Link](25.0)
the [Link](…) method is called (or invoked) with the argument 25.0 and
returns the value 5.0 (the square root of 25.0) which is subsequently
assigned to the variable root.
This action is similar to that of the statement:
double sum = 5.0 + 8.0;
The expression 5.0 + 8.0 evaluates to (or returns)13.0, which is assigned to
sum.
The argument that is passed to a method may be a constant, an expression, or a
variable.
And, a method call may be used within an expression.
[Link]([Link](456)); // prints the square root of 245
( double)
double w = [Link]([Link]()); // here input is a Scanner object
double x = [Link]();
double y = [Link]();
double z = 3.14*[Link](x + y); // method is used within an expression
Methods
A method is described by its header, which has the
following form:
return-type name(parameter-list)
• The return-type specifies the data type of the value returned
by the method.
• The parameter-list enumerates the number (implicitly) and
type (explicitly) of the arguments that must be passed or
given to the method.
• The names in the parameter-list are called formal
parameters, or simply parameters.
Methods
The header for [Link](…)
Methods of the Math class
A Method that Computes Powers
double [Link](double x, double y)
returns xy.
The parameter list of the header specifies that the method
require two arguments of type double.
For example,
[Link](5.0,2.0) returns 5.02.0, i.e., 25.0.
The power method, [Link](…)
Random Numbers
The
double [Link]()
method returns a random number that is greater than or equal
to 0.0 and strictly less than 1.0. [Link]() requires no
parameter or argument.
There is no discernible pattern to the output.
Generate 10 random numbers
public class TenRandomNumbers
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
[Link]([Link]());
}
}
Output
0.6516831128923004
0.3159760705754926
0.945877632966408
0.04538322890407964
0.8815999823052094
0.07672479266883347
0.04423548066038108
0.4441137107417066
0.15348060768674676
0.1833850393131755
Using [Link]() to Generate Integers
To simulate the roll of a single die, a program requires a random integer from 1 to 6
inclusive. Use [Link]() to
generate integers in the range 1 through 6 by “magnifying” its 0 through 1 range.
Suppose
r = [Link]();
Then
0.0 < r < 1.0.
0.0 < 6*r < 6.0 (multiplying the inequality by 6), and
1.0 < 6*r +1 < 7.0. (adding 1 to each value in the inequality)
Thus 6*[Link]() + 1 is a number greater than or equal to 1 but strictly less
than 7.
.
Using [Link]() to Generate Integers
For example, if :
r = 0.8929343993861253, then
6*r = 5.3576063963167518, and
6*r+1 = 6.3576063963167518.
To obtain an integer value, cast 6*r+1 to an integer, effectively dropping the
fractional part. Thus,
(int)(6*[Link]() + 1)
returns a random integer between 1 to 6, inclusive. (int)(52*[Link]()
+1) returns a random integer between 1 and 52, inclusive
Using [Link]() to Generate Integers
Problem statement
Write a program that rolls a pair of dice 100 times and counts
the number of times seven appears..
Using [Link]() to Generate Integers
1. import [Link].*;
2. public class Dice
3. {
4. public static void main(String [] args)
5. {
6. int die1,die2;
7. int sum, seven = 0;
8. for (int i = 1; I <= 100; i++)
9. {
10. die1 = (int)(6*[Link]()+1) ; // random integer 1..6
11. die2 = (int)(6*[Link]()+ 1);
12. sum = die1 + die2;
13. if (sum == 7)
14. seven = seven + 1;
15. }
16. [Link]("The number of sevens is " + seven);
17. }
18. }
Writing Your Own Methods
Like Java's methods, a method that you create:
• Has a name
• May accept arguments
• May return a value
• May be used as part of an expression.
Methods that Return a Value
• The number of calories used while running depends on the
runner's weight as well as the distance that he/she has run.
A common rule of thumb used to estimate the number of
calories burned is:
calories = .653 × weight × distance
where weight is the runner's weight in pounds and
distance is in miles.
Methods that Return a Value
Write a program that calculates the number of calories burned as a function
of weight and distance. Include a method:
double caloriesBurned(double weight, double distance)
that accepts two arguments of type double, and returns a value of type
double.
The method double caloriesBurned(double weight, double distance)
Methods that Return a Value
1. import [Link].*;
2. public class RunnersCalculator
3. {
4.
5. public static double caloriesBurned(double weight, double
distance)
6. {
7. // returns the number of calories burned using the formula
8. // calories = .653 × weight × distance
9. double calories = .653* weight *distance;
10. return calories;
11. }
Methods that Return a Value
12. public static void main(String[] args)
13. {
14. Scanner input;
15. double myWeight, myDistance, totalCalories;
16.
17. input = new Scanner([Link]);
18. [Link]("Enter weight in pounds: ");
19. myWeight = [Link]();
20.
21. [Link]("Enter distance in miles: ");
22. myDistance = [Link]();
23.
24. totalCalories = caloriesBurned(myWeight, myDistance);
25. [Link]("Calories burned: "+ totalCalories);
26. }
27. }
Output
Enter weight in pounds: 165.0
Enter distance in miles: 6.0
Calories burned: 646.47
Discussion
Like all Java applications, RunnersCalculator begins execution
with main(...) (lines 11 – 22) Within main(...) there is a call to
the method caloriesBurned(...) on line 24:
24. totalCalories = caloriesBurned(myWeight, myDistance);
caloriesBurned(…) has two arguments:
• myWeight and
• myDistance;
the returned value is assigned to the variable totalCalories.
• The instructions of the method caloriesBurned(...) are
specified on lines 9 and 10:
double calories = .653* weight *distance;
return calories;
• Line 5 is the header of the method:
public static double caloriesBurned(double weight, double distance)
• For now, ignore the keywords public and static. The
remainder of the header specifies:
• The data type of the return value: double
• The name of the method: caloriesBurned
• The parameters: weight and distance
Methods that Return a Value
• The parameters specify the type and number of the
arguments that must be passed to the method. When this
method is invoked with two arguments, the value of the first
argument is assigned or passed to weight and the value of
the second argument is passed to parameter distance. If the
method call is
caloriesBurned(155.5, 3.5)
the parameter weight gets the value 155.5, and distance the
value 3.5.
Methods that Return a Value
Parts of a method header
The block consisting of lines 6 through 11 contains the instructions of
the method caloriesBurned(...).
Line 9 is an expression that calculates the number of calories burned.
Line 10 is a return statement. The return statement has the form:
return expression
.
The return statement
The return statement has two purposes:
• It specifies the value that the method returns to the caller.
• It terminates the method and returns program control to the
caller
A trace of RunnersCalculator
Line 15: double myWeight, myDistance, totalCalories
Line 19: myWeight = [Link]();.
Line 22: myDistance = [Link]();
Line 24:
totalCalories =
caloriesBurned(myWeight,myDistance);
Call caloriesBurned(…). Pass values of the arguments
myWeight and myDistance to parameters weight and
distance, respectively.
Program control passes to caloriesBurned(...)
A trace of RunnersCalculator
Line 5: public static double caloriesBurned(double weight,
double distance)
The parameters weight and distance are initialized with the values of
arguments myWeight and myDistance.
Line 9: double calories = .653* weight *distance;
Declare the variable calories. Calculate the number of calories burned,
and initialize calories to that value.
Line 10: return calories;
Return the value of calories to the caller and exit.
Program control returns to the assignment on line 20
Line 24 (resumed): Assign the
returned value to totalCalories.
Line 25: Print the results.
Void Methods
A method can perform a task without returning a value. Such a method is
called a void method:
void drawSquare( int size)
might be the header of a method that draws a square on the
screen and does not return a value. Because a void method
does not return a value, it makes no sense to incorporate a void
method into an expression. The expression:
5* [Link](25)
is certainly meaningful and has the value 25.0, but:
5*drawSquare(25)
makes no sense since drawSquare(25) does not return a value.
Void Methods
• A call to a void method is a “stand-alone” statement
consisting of the method name along with any arguments
that must be passed to the method such as:
[Link](“Print me!”);
or
drawSquare(10);
Void Methods
Problem statement:
Write a program that includes a void method:
void coinChanger(int amount)
that accepts a single integer argument between 1 and 100 that
represents an amount of money between $.01 and $1.00. The
method makes change for that amount using the minimum
number of coins. Coins are in denominations of half dollars,
quarters, dimes, nickels, and pennies.
Solution
1. import [Link].*;
2. public class MoneyChanger
3. {
4. public static void coinChanger (int amount)
5. {
6. // calculates the minimum number of half dollars, quarters, dimes,
// nickels and pennies in amount
7. int halfDollars, quarters, dimes, nickels, pennies;
8. [Link]();
9. [Link](amount+" cents can be converted to:");
10. halfDollars = amount/50; //determine number of half dollars
11. amount = amount%50; // how much remains?
12. quarters = amount/25; // determine number of quarters
13. amount = amount%25; // how much remains?
14. dimes = amount/10; // determine the number of dimes
15. amount= amount%10; // how much remains?
16. nickels = amount/5; // determine the number of nickels
Solution
18. [Link]("Half Dollars: "+ halfDollars);
19. [Link]("Quarters: "+ quarters);
20. [Link]("Dimes: "+ dimes);
21. [Link]("Nickels: "+ nickels);
22. [Link]("Pennies: "+ pennies);
23. return; // return statement is optional here
24. }
25.
public static void main(String[] args)
26. {
27. Scanner input;
28. input = new Scanner([Link]);
29. [Link]("Enter a value between 1 and 100: ");
30. int money = [Link]();
31. coinChanger(money); //call to method coinChanger
32. }
33. }
Output
Enter a value between 1 and 100: 83
83 cents can be converted to:
Half Dollars: 1
Quarters: 1
Dimes: 0
Nickels: 1
Pennies: 3
Void Methods
• Because coinChanger(…) does not return a value, the call to
coinChanger(...) is not called within an expression. The method
call is the Java statement (line 32):
coinChanger (money);
• The return statement on line 24 does not include a return value or
an expression. The return statement merely causes the method
to exit; no value is returned to the calling method.
• The return statement on line 24 is unnecessary. After a void
method executes its last statement, the method automatically
returns; no final return statement is necessary.
Putting It All Together
• A Java method consists of a:
• header followed by a
• method block.
The parameters in the header specify the number and type of the arguments that must be
passed to the method. When a method is invoked, the values stored in the arguments are
copied to the parameters.
Putting It All Together
The method block is a sequence of statements enclosed by
curly braces:
{
statement-1;
statement-2;
statement-3;
…
statement-n;
}
A method that calculates the volume of a
box
Putting It All Together
• Method Name
The name of a method must be a valid Java identifier.
Standard Java convention specifies that the name of a
method begins with a lowercase letter and starts each
succeeding word in the method name with an uppercase
letter. For example, the names volumeOfBox and
caloriesBurned both follow this convention; the names
VolumeOfBox and volumeofbox do not.
Putting It All Together
• Parameter-List.
A method's parameter-list consists of pairs of the form:
type parameter-name
Putting It All Together
• Argument Passing.
When calling a method, the caller passes arguments to the
parameters. The calling statement must provide a type-
suitable value for each parameter. If a method has five
parameters, five arguments are required.
Putting It All Together
• Pass by Value.
All arguments are passed “by value.” This means that the
arguments are evaluated and values of the arguments are
copied to the parameters of a method. Subsequently,
modifying the parameters in the method has no effect on the
value of any variables passed as arguments.
Putting It All Together
• Method Block.
The statements of the method-block accomplish the task of
the method.
Putting It All Together
• The return Statement.
A method that returns a value must include a return
statement. The form of the return statement is
return expression
When a method executes the return statement,
• the method terminates,
• program control passes back to the caller, and
• any statements following the return statement are
ignored
Putting It All Together
• Local Variables.
Variables that are declared within a method are called the
local variables of that method. Local variables exist and are
known only within the method in which they are declared.
When a method exits, the local variables are destroyed.
Local variables do not exist beyond the life of a method call.
Local Variables
• When a method is invoked, memory for local variables is
allocated, and when a method exits, that memory is de-
allocated.
• A method's local variables do not retain values from call to
call. When a method exits, its local variables no longer exist.
• The concept of local variables is tied to the broader topic of
scope, which we discuss in the next section.
Scope
• The scope of a variable is that section of the program in which a variable can be
accessed or referenced.
• For example, consider the following void method that computes the sum and
product of the first n positive integers:
1. void sumAndProduct(int n)
2. {
3. int sum = 0;
4. int product = 1;
5. for (int i= 1; i<= n; i++)
6. {
7. sum += i;
8. product *= i;
9. }
10. [Link]( "Sum of the first " + n+ " positive integers is "+ sum);
11. [Link]("Product of the first " + n+ " positive integers is "+
product);
12. }
Scope
• The method sumAndProduct has several local variables: n, sum,
product, and i. The scope of each of these variables is as follows:
• The scope of parameter n is the entire method.
• The scope of sum begins with its declaration on line 3 and
extends to the end of the method.
• Similarly, the scope of product extends from its declaration on
line 4 to the method's end.
• The variable i does not exist beyond the block of the for-loop.
Thus, the scope of variable i is lines 5 through 9. Outside of the
for-loop, i is inaccessible and unknown.
Scope
• In general, the scope of a variable begins with its declaration
and extends to the end of the block in which it is declared.
Scope
• A block is a group of statements enclosed by curly braces
{ and }; if you declare a variable in the outermost block of a
method, its scope extends from the declaration to the end of
the method . On the other hand, the scope of a variable
declared within an inner or nested block begins at the
declaration and terminates at the end of that block.
Scope
if (purchase > 200)
{
double discount = .20* purchase;
double discountPrice = purchase-discount;
tax = .05*discountPrice;
total = discountPrice + tax;
}
else
{
tax = .05*purchase;
total = purchase + tax;
}
The scope of the variables discount and discountPrice
extends from their definitions to the end of the “if block.”
Thus, neither variable is known within the “else block.”
Scope
• The scope of a variable declared in the header of a for loop
is the entire for loop. In the segment
for (int i = 0; i<= 50; i++)
{
//statements
}
• The control variable i is unknown once the loop terminates.
Multiple return statements
• A method may have more than one return statement, but
only one executes before the method terminates.
• The first return statement that executes terminates the
method
Multiple return statements
Example
• A prime number p is a positive integer greater than 1 that
has no positive integer divisors other than 1 and p. For
example 101 is a prime number since no positive integers
other than 1 and 101 divide 101 evenly. The integers 2, 3, 5,
7, and 37 are all prime numbers. On the other hand, 100 is
not a prime number because 5 is a divisor of 100. With the
exception of 2, all prime numbers are odd.
Multiple return statements
Problem statement:
• Write a program that prompts a user for a positive integer
and determines whether or not the number is prime. Include
a method
boolean isPrime(int p)
that accepts an integer p as a parameter and returns true if p
is prime; otherwise false.
The isPrime method
Multiple return statements
1. import [Link].*;
2. public class PrimeChecker
3. {
4. public static boolean isPrime(int p) //returns true if p is a prime number
5. {
6. if (p <=1) // 0, 1, and all negatives are not prime
7. return false;
8. else if (p == 2) // if p is 2; return true (exit) because 2 is prime
9. return true;
10. else if ( p % 2 == 0) // if p is even and not 2 , return false (exit);
11. return false;
12. // so p is odd; check for odd divisors
13. // if a divisor is found, return false and exit
14. for (int i = 3; i < p; i+=2) // i = 3,5,7,9
15. if (p % i == 0) // if p % i == 0 then i divides p so p is not prime
16. return false;
17. // if the method reaches this point, p is prime,
18. return true;
19. }
Multiple return statements
20. public static void main(String[] args)
21. {
22. int number;
23. Scanner input;
24. input = new Scanner([Link]);
25. [Link]("What number would you like to test? ");
26. number = [Link]();
27. if (isPrime(number))
28. [Link](number + " is a prime number");
29. else
30. [Link](number+" is not prime");
31. }
32. }
Output
What number would you like to test? 6317
6317 is a prime number
What number would you like to test? 7163
7163 is not prime
Discussion
• The method isPrime(...) contains no less than five return
statements. When any one return statement executes, the
method exits and program control passes back to the caller.
For example:
• If parameter p has the value 22, the condition on line 10 is true
and the return statement on line 11 executes returning false and
terminating the method;
• If p has the value 35, the loop of line 14 executes and when i
attains the value of 5, the return on line 16 executes returning
false (because 35 % 5 == 0, i.e., 35 is divisible by 5);
• If p is 23, then none of the conditions of the else-if statement is
true nor does the condition on line 15 evaluate to true.
Consequently, the return statement on line 18 returns true, i.e.,
23 is prime.
Method Overloading
• Java allows two or more methods of the same class to share
the same name. This practice is called method overloading.
• Java's Math class has several overloaded methods including
[Link](...), which has two forms:
• int [Link](int x, int y)
• double [Link] (double x, double y)
Method Overloading
• The parameter lists of the two methods differ. The first
version of [Link](...) accepts two integer parameters and
the second version accepts two double parameters.
• In order for the Java compiler to distinguish between
methods of the same name, overloaded methods must differ
in the types and/or number of parameters.
• Because of this rule, Java (usually) has no difficulty deciding
which version of a method to execute
Four calls to the overloaded [Link](...)
method
method call return argument types version
[Link](10,5) 10 two int 1
[Link](10.0, 5.0) 10.0 two double 2
[Link](10.0, 5) 10.0 two double (5 is automatically cast to 5.0) 2
[Link](10, 5.0) 10.0 two double ( 10 is automatically cast to 2
10.0)
Problem statement:
Write a method:
double cost(double price, double discount)
that returns the sale price of an item. The cost(…) method
accepts two arguments: the price of an item and the
discount.
The discount can be an integer such as 10 (10%) or a
floating point number such as .10 (also 10%). The price an
can also be an integer or a double.
Solution
1. public static double cost(double price, double discount)
2. //version 1 – double, double
3. {
4. return price - discount*price;
5. }
6. public static double cost (int price, int discount)
7. //version 2 – int, int
8. {
9. double dollarsPrice = price/100.0;
//convert to dollars and cents
10. double decimalDiscount = discount/100.0;
// convert to decimal
11. return dollarsPrice - dollarsPrice*decimalDiscount;
12. }
Solution
13. public static double cost(double price, int discount)
14. //version 3 – double, int
15. {
16. return price - price*(discount/100.0);
17. }
18. public static double cost(int price, double discount)
19. //version 4 – int , double
20. {
21. return (price/100.00) - (price/100.0)*discount;
22. }
Method Overloading
Example
• Baseball uses many different statistics to measure the
performance of a hitter. The On Base Percentage is the
percentage of times that a batter reaches first base.
Historically, two formulas have been used to calculate this
statistic: one that was developed during the 1950's and a
more modern version created in 1984.
Method Overloading
• The method developed by in the 1950's computes the On Base
Percentage as:
(hits + walks + hbp) /(atBat + walks+ hbp)
• The 1984 version performs the calculation:
• (hits + walks + hbp) /(atBat + walks+ hbp + sacrifices)
Where:
• atBat is number of times a player gets a hit or makes an out
• hits is the number of times a player gets a hit
• walks is the number of times a player walks
• hbp is the number of times a player was hit by a pitch
• sacrifices is the number of times a player makes a sacrifice fly
Method Overloading
Problem statement
Write a program with two methods, each named
OnBasePercentage that calculate this statistic. The first method
uses the older formula and the second uses its more modern
counterpart.
Method Overloading
}
public static double OnBasePercentage(int atBat,int hits,int
walks,int hbp)
// old method from the 1950’s
{
return (double)(hits+walks+hbp)/(double)(atBat+walks+hbp);
}
public static double OnBasePercentage(int atBat,int hits,int walks,int
hbp,int sacrifices)
//new method from 1984
{
return (double)(hits+walks+hbp)/(double)(atBat+walks+hbp+sacrifices);
Discussion
• There are two versions of OnBaseBercentage, The first
method requires four integer arguments and the second
method five. Because the two parameter lists differ in the
number of parameters, the Java compiler can easily choose
a method based on the number of arguments the caller
passes.
• It is not legal to overload a method based on the type of the
return value. The Java compiler does not consider
int MyMethod(int x) and
double MyMethod(int x)
two distinct methods.
•
• Overloaded methods must differ in the types and/or number
of parameters.