Transcript Chapter 1

Chapter 7: User-Defined
Methods
Java Programming:
From Problem Analysis to Program Design,
Third Edition
Chapter Objectives
 Understand how methods are used in Java
programming.
 Learn about standard (predefined) methods
and discover how to use them in a program.
 Learn about user-defined methods.
 Examine value-returning methods, including
actual and formal parameters.
2
Chapter Objectives
 Explore how to construct and use a valuereturning, user-defined method in a program.
 Learn how to construct and use user-defined
void methods in a program.
 Explore variables as parameters.
 Learn about the scope of an identifier.
 Become aware of method overloading.
3
Methods
Given that f(x) = 2x + 5 then:
 f(1) = 7
 f(4) = 13
In Java, concept of methods is similar to function
in algebra.
Every method has a name, arguments and does
some computations.
4
Methods
We've already seen some methods:
Math.pow(x ,y) = xy
 Method name: power.
 Method type or return value: double.
 Method arguments or parameters: 2  x, y.
 Data type of parameters: both double.
 In this chapter we're going to introduce more java
methods (predefined) and give you the information
you need to write your own methods (user defined).
5
Predefined Methods
 Methods already written and provided by Java
like pow from class Math.
 Organized as a collection of classes (class
libraries).
 To use, import package.
 Method type: The data type of the value
returned by the method.
6
Predefined Methods
Math.sqrt(x) = √ x for x >= 0.0
 Method name: square root.
 Method type or return value: double
 Method arguments or parameters: 1  x
 Data type of parameter: double
 Ex: Math.sqrt(2.25) = 1.5;
7
Predefined Classes
8
Predefined Classes
9
Predefined Classes
10
class Character (Package: java.lang)
11
class Character (Package: java.lang)
12
Using Predefined Methods
To use any public and static method in a class:
 import the class from the package.
 Call the method using the following syntax:
className.methodName(parameters)
 Ex: Math.min(2,4);
// 2
Character.isDigit(‘*’); //false
 Remember, java automatically imports classes from
the package java.lang.
13
Using Predefined Methods
 JDK 5.0 introduces the following import statement:
import static packageName.ClassName.*;
 This is called static import statement.
 With it you have the choice when using public static
method of a class:
 Ex: import static java.lang.Math.*;
 Math.pow(2,4);
 Or simply pow(2,4);
14
Using Predefined Methods
Line
Line
Line
import static java.lang.Math.*;
Line
import static java.lang.Character.*; Line
Example 7_1
1:
4:
5:
7:
9:
Uppercase a is A
4.2 to the power of 3.0 = 74.09
5 to the power of 4 = 625.00
u = 31.20
Absolute value of -15 = 15
public class Example7_1{
public static void main(String[] args) {
int
x;
double u,v;
System.out.println("Line 1: Uppercase a is " +toUpperCase('a') );
u = 4.2;
v = 3.0;
System.out.printf("Line 4: %.1f to the power of %.1f = %.2f%n", u,v, pow(u,v) );
System.out.printf("Line 5: 5 to the power of 4 = %.2f%n",pow(5,4) );
u = u + Math.pow(3,3) ;
System.out.printf("Line 7: u = %.2f%n",u);
x = -15;
System.out.printf("Line 9: Absolute value of %d = %d%n", x ,abs(x) );
}
}
15
User-Defined Methods
 Java does not provide every method that you will
ever need.
 So you must learn how to write your own methods!
 User-defined methods in java are classified into two
categories:
 Value-returning methods: method that have a return type.
 Void methods: methods that do not have a return type.
16
Value-Returning Method
 Whether user or predefined it is used in either:
 An assignment statement.
 Or an output statement.
 Or a parameter in a method call.
 Ex:
double x;
x = Math.pow(2,4); //assignment stmt
System.out.println(Math.pow(2,4)); //output stmt
x= Math.pow(2,Math.pow(2,2)); //method call parm.
17
Value-Returning Method
 Every method has a heading and a body.
 Ex: Method abs (absolute) in class Math.
public static int abs(int number)
{
if (number < 0 )
number = -number;
return number;
}
Heading
Body
 number is called formal parameter.
18
Value-Returning Method
Suppose:
 heading of method pow in class Math:
public static double pow(double base, double exponent)
 declaration:
double x, u = 2.5, v = 3.0;
 Method call:
x= Math.pow(u,v); // value of u & v are passed to method pow
//value of u is copied into base
//value of v is copied into exponent




u & v are called actual parameter.
base & exponent are called formal parameter.
Formal parameter: variable decaled in method heading.
Actual parameter : variable or expression listed in method call.
19
User-Defined Methods
Syntax of Value-Returning Method
modifier(s) returnType methodName(formalParameters)
{
statements
}
In this syntax:
1.modifiers: indicates the visibility of the method, that is,
where in a program the method can be called.
 Some modifiers are: public, private, protected,
static, abstract, and final.
 You can select one among public, private or
protected.
 Similarly, you can select between static or abstract.
 Meanwhile, we will use public and/or static only.
20
User-Defined Methods
Syntax of Value-Returning Method
modifier(s) returnType methodName(formalParameters)
{
statements
}
2.returnType: Type of the value that the method
calculates and returns (using return statement).
3.methodName: Java identifier; name of method.
4.statements enclosed between { } form the body
of the method.
21
Syntax
 Syntax of formal parameter list:
dataType identifier, dataType identifier,...
 Syntax to call a value-returning method:
methodName(actual parameter list)
 Syntax of the actual parameter list:
expression or variable, expression or variable, ...
22
Notes
 Method's formal parameter can be empty.
modifiers returnType methodName()
 If no formal parameter  no actual parameter in
method call.
 Method call: methodName();
 In method call: number and data types of actual
parameters MUST match formal parameters.
 Ex: Math.pow(4);
// syntax error!!
23
Syntax
return statement
 Syntax of the return statement:
return expr;
 expr data type should match return type of
the method.
 expr can be:
 variable: return x;
 value: return 5;
 expression: return (x+5);
24
User defined Method - larger
• Method larger compares two numbers and returns the
larger of the two.
public static double larger(double x, double y)
{
double max;
if (x >= y)
max = x;
else
max = y;
return max;
}
25
Equivalent larger Method
Definitions
public static double larger(double x, double y)
{
if (x >= y)
return x;
else
return y;
}
26
Equivalent larger Method
Definitions
public static double larger(double x, double y)
{
if (x >= y)
return x;
return y;
}
 Execution of return statement terminates the
function. Thus, all subsequent statements are skipped.
27
User Defined Method - compareThree
 compareThree uses method larger to
determine the largest of three numbers.
public static double compareThree(double x, double y, double z)
{
return larger(x, larger(y, z));
}
28
User defined Method – final program
import java.util.*;
public class LargerNumber
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
double num1, num2;
System.out.println("Line 2: Larger of 5.6 and 10.8 is "
+ larger(5.6,10.8) );
System.out.print("Line 3: Enter two numbers: ");
num1 = console.nextDouble();
num2 = console.nextDouble();
System.out.println();
System.out.println("Line 7: Larger of "
+ num1 + " and " + num2 + " is " larger(num1,num2) );
System.out.println("Line 8: Largest of 23.5, 34.6, "
+ "and 12 is " + compareThree(23.5,34.6,12) );
} // end main method
29
Line 2: Larger of 5.6 and 10.8 is 10.8
Line 3: Enter two numbers: 5 7
User defined Method – final program
Line 7: Larger of 5.0 and 7.0 is 7.0
Line 10: Largest of 23.5, 34.6, and 12 is 34.6
public static double larger(double x, double y)
{
if(x >= y)
return x;
else
return y;
}
// end larger method
public static double compareThree(double x, double y, double z)
{
}
}
return larger(x, larger(y, z));
// end compareThree method
// end LargerNumber class
30
Programming Example:
Palindrome Number
 Palindrome: An integer or string that reads the
same forwards and backwards.
 Input: Integer or string.
 Output: Boolean message indicating whether
integer string is a palindrome.
31
Solution: isPalindrome Method
public static boolean isPalindrome(String str)
{
int len = str.length();
int i, j;
j = len - 1;
for (i = 0; i <= (len - 1) / 2; i++)
{
if (str.charAt(i) != str.charAt(j))
return false;
j--;
}
return true;
}
32
Sample Runs: Palindrome Number
33
Sample Runs: Palindrome Number
34
Flow of Execution
 Execution always begins with the first statement in
the method main.
 You can put methods within a class in any order.
 A value returning method MUST return a value.
 User-defined methods execute only when called.
 Call to method transfers control from caller to called
method.
 In the method call statement, specify only actual
parameters, not data type or method type.
 Control goes back to caller when method exits.
35
Programming Example: Largest
Number
 Input: Set of 10 numbers
 Output: Largest of 10 numbers
 Solution:
 Get numbers one at a time.
 Method largest number: Returns the larger of 2 numbers.
 For loop: Calls method largest number on each number
received and compares to current largest number.
36
Solution: Largest Number
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
double num;
double max;
int count;
System.out.println("Enter 10 numbers.");
num = console.nextDouble();
max = num;
for (count = 1; count < 10; count++)
{
num = console.nextDouble();
max = larger(max, num);
}
System.out.println("The largest number is "
+ max);
}
37
Sample Run: Largest Number
Sample Run:
Enter 10 numbers:
10.5 56.34 73.3 42 22 67 88.55 26 62 11
The largest number is 88.55
38
Void Methods
 Methods that do not have a return type.
 Similar in structure to value-returning
methods.
 Call to method is always stand-alone
statement.
 Can use return statement to exit method
early.
39
Void Methods without Parameters
Method definition:
The general form (syntax) of a void method without
parameters is as follows:
modifier(s) void methodName()
{
statements
}
Method call (within the class):
The method call has the following syntax:
methodName();
40
Void Methods with Parameters
Method definition:
The definition of a void method with parameters
has the following syntax:
modifier(s) void methodName(formalParameterList)
{
statements
}
Formal parameter list:
The formal parameter list has the following syntax:
dataType variable, dataType variable, ...
41
Void Methods with Parameters
Method call:
The method call has the following syntax:
methodName(actual parameter list);
Actual parameter list:
The actual parameter list has the following syntax:
expression or variable, expression or
variable, ...
42
Void Methods with Parameters
public class Shapes {
}
public static void main (String args[]) {
square(3);
System.out.println();
rect(2,4);
public static void rect(int x, int y) {
for ( int i = 1 ; i <= x * y ; i++ )
{
System.out.print("*");
if (i % y == 0)
System.out.println();
}
}
***
***
***
****
****
public static void square(int x)
{
for (int i =1; i <= x * x; i++) {
System.out.print("*");
if (i % x == 0) System.out.println();
}
}
}
43
Guidelines for Using Methods
 Pick meaningful names. celsiusToFahrenheitConverter is a much better
name than ctfc.
 A method should have a primary purpose - it should do one thing well.
If you're trying to do two or more things, think about breaking them up
into their own methods.
 Use as many parameters as you need but, as a guide, more than six is
hard to read and often unnecessary.
 Choose meaningful parameter names. celsiusValue means a lot more
than n or x.
 Every parameter must have a type.
 If you have specified a value-return type for the method, you must use a
return statement.
44
Recall…
 Recall that java has 2 categories of variables:
 Primitive type variables: directly store data into
their memory space.
 Reference variables: cannot directly store data
in its memory space. Instead, they stores the
memory location, that is, the address of the
memory space where the actual data is stored.
45
Recall…
int x;
x=45;
String str;
str = “java programming”;
46
Recall…

In reality, str = “Java Progrmming” is equivalent to
String str = new String("Java Programming");

In java new is an operator that causes the system to:
1. Allocate memory space of a specific type,
2. Store data in that space,
3. Return the address of that space.
47
Recall…
String  calss type
str  object of that class
An object is an instance of a class and the operator
new is used to instantiate an object.
In java, any variable declared using a class is a
reference variable.
48
Primitive Data Type Variables as
Parameters
 When a method is called:
 The value of the actual parameter is copied into the
corresponding formal parameter.
 If a formal parameter is a variable of a primitive data
type:
 Value of actual parameter is directly stored.
 Cannot pass information outside the method.
 Provides only a one-way link between actual parameters
and formal parameters.
49
Primitive
Line 2: Before
Data
calling
Type
the method
Variables
funcPrimFormalParam,
as Parameters
number = 6
Line 5: In the methodfuncPrimFormalParam, beforechanging, num = 6
Line 7: In the method funcPrimFormalParam, after changing, num = 15
Line 4: After calling the method funcPrimFormalParam, number = 6
Example7_7
50
Reference Variables as Parameters
If a formal parameter is a reference variable:
 Copies value of corresponding actual parameter.
 Value of actual parameter is address of the object
where actual data is stored.
 Both formal and actual parameters refer to same
object.
51
Uses of Reference Variables as
Parameters
 Can return more than one value from a
method.
 Can change the value of the actual object.
 When passing an address, saves memory
space and time, relative to copying large
amount of data.
52
Reference Variables as Parameters:
type String
53
Line
Line
Line
Line
Line
2:
5:
6:
8:
4:
str before calling the method stringParameter: Hello
In the method stringParameter
pStr before changing its value: Hello
pStr after changing its value: Sunny Day
str after calling the method stringParameter: Hello
54
Reference Variables as Parameters:
type String
 The preceding example shows that you should
be careful when passing String variables as
parameters.
 If you want to pass strings as parameters to
methods and want to change the actual
parameters, you can use the class
StringBuffer.
55
Scope of an Identifier within a Class
 Recall, identifier is the name of something in java
such as variables or methods.
 Are we allowed to access (use) any identifier
anywhere in the program? The answer is NO.
 Certain rules exist that we must follow to access an
identifier.
 The scope of identifier refers to what other parts of
the program can see an identifier, i.e., where it is
accessible.
56
Scope of an Identifier within a Class
 Local identifier: An identifier that is declared within a
method or block and that is visible only within that method
or block.
 Within a class
 Any method can call any other method
 Exception: static method cannot call a non-static method
 Java does not allow the nesting of methods. That is, you
cannot include the definition of one method in the body of
another method.
57
Scope of an Identifier within a Class
 Within a method or a block, an identifier must be
declared before it can be used. Note that a block is a set
of statements enclosed within braces { }.
 A method’s definition can contain several blocks. The
body of a loop or an if statement also forms a block.
 Within a class, outside of every method definition
(and block), an identifier can be declared anywhere.
58
Scope of an Identifier within a Class
 Within a method, an identifier that is used to name a
variable in the outer block of the method cannot be
used to name any other variable in an inner block of
the method.
 For example, in the following method definition, the
second declaration of the variable x is illegal:
public static void illegalIdentifierDeclaration()
{
int x;
//block
{
double x;
//illegal declaration,
//x is already declared
...
}
}
59
Scope Rules
 Scope rules of an identifier that is declared within a class
and accessed within a method (block) of the class.
 An identifier, say X, that is declared within a method (block) is
accessible:
 Only within the block from the point at which it is declared until the
end of the block.
 By those blocks that are nested within that block.
 Suppose X is an identifier that is declared within a class and
outside of every method’s definition (block).
 If X is declared without the reserved word static (such as a named
constant or a method name), then it cannot be accessed in a static
method.
 If X is declared with the reserved word static (such as a named
constant or a method name), then it can be accessed within a method
(block) provided the method (block) does not have any other identifier
named X.
60
Scope Rules
Example 7-12
public class ScopeRules
{
static final double rate = 10.50;
static int z;
static double t;
public static void main(String[] args)
{
int num;
double x, z;
char ch;
//...
}
public static void one(int x, char y)
{
//...
}
61
Scope Rules
public static int w;
public static void two(int one, int z)
{
char ch;
int a;
//block three
{
int x = 12;
//...
} //end block three
//...
}
}
62
Scope Rules: Demonstrated
63
More Examples
int x = 6;
int y = 2;
if (x > 5)
{
int x = 5;
y = y + x;
}
• What will the values of x & y be after this code
segment?
64
Method Overloading: An
Introduction
 It is often useful to have multiple versions of
the same method that differ in their
parameters.
 This idea of several methods with the same
name is called
METHOD OVERLOADING.
65
Method Overloading: An Introduction
 The max(x,y) from class Math method is one example.
 It has many versions which take different arguments:
static int max(int x, int y) or
static double max(double x, double y), etc.
 The Java compiler works out which version of a method
with a given name is meant from the parameters passed in
the call.
 The factors taken into account are:
– The number of actual parameters.
– The types of actual parameters.
– The order in which actual parameters are passed.
66
Method Overloading: An
Introduction
 Method overloading: More than one method can
have the same name.
 Two methods are said to have different formal
parameter lists:
 If both methods have a different number of
formal parameters.
 If the number of formal parameters is the same in
both methods, the data type of the formal
parameters in the order you list must differ in at
least one position.
67
Method Overloading
public
public
public
public
void methodOne(int x)
void methodTwo(int x, double y)
void methodThree(double y, int x)
int methodFour(char ch, int x,
double y)
public int methodFive(char ch, int x,
String name)
These methods all have different formal parameter lists.
68
Method Overloading
public void methodSix(int x, double y,
char ch)
public void methodSeven(int one, double u,
char firstCh)
 The methods methodSix and methodSeven both
have three formal parameters, and the data type of the
corresponding parameters is the same.
 These methods all have the same formal parameter
lists.
69
Method Overloading
 Method overloading: Creating several methods within
a class with the same name.
 The signature of a method consists of the method
name and its formal parameter list. Two methods
have different signatures if they have either different
names or different formal parameter lists. (Note that
the signature of a method does not include the return
type of the method.)
70
Method Overloading
 The following method headings correctly overload
the method methodXYZ:
public
public
public
public
void
void
void
void
methodXYZ()
methodXYZ(int x, double y)
methodXYZ(double one, int y)
methodXYZ(int x, double y,
char ch)
71
Method Overloading
public void methodABC(int x, double y)
public int methodABC(int x, double y)
 Both these method headings have the same name and
same formal parameter list.
 These method headings to overload the method
methodABC are incorrect.
 In this case, the compiler will generate a syntax error.
(Notice that the return types of these method headings are
different.)
72
Chapter Summary
 Pre-defined methods
 User-defined methods:




Value-returning methods
Void methods
Formal parameters
Actual parameters
 Flow of execution
73
Chapter Summary
 Primitive data type variables as parameters:
 One-way link between actual parameters and
formal parameters (limitations caused).
 Reference variables as parameters:
 Can pass one or more variables from a method.
 Can change value of actual parameter.
 Scope of an identifier within a class
 Method overloading
74