INTRODUCTION

advertisement
CMPS 161
CHAPTER 7
INTRODUCTION






In Java, there are predefined methods that are already written and provided
and user-defined methods, methods that you create.
While working on one method, you can focus on just that part of the program
and construct it, debug it, and perfect it.
Different people can work on different methods simultaneously.
If a method is needed in more than one place in a program, or in different
programs, you can write it once and use it many times.
Using methods greatly enhances the program’s readability because it reduces
the complexity of the method main.
Methods are often called modules.
PREDEFINED METHODS



In Java, predefined methods are organized as a collection of classes, called
class libraries.
The class Math contained in the package java.lang contains mathematical
methods.
The method type is the data type of the value returned by the method. Some
predefined methods in the class Math are:
1
CMPS 161

CHAPTER 7
The class Character, also in the package java.lang contains the following
methods:
2
CMPS 161




CHAPTER 7
In general, to use predefined methods of a class in a program, you must
import the class from the package containing the class.
By default Java automatically imports classes from the package java.lang.
Therefore, if you use a method from the class Math or Character you do not
need to explicitly import these classes in your program.
Example:
//How to use predefined methods
import java.text.DecimalFormat;
import
java.lang.*;
public class PredefinedMethods
{
public static void main(String[] args)
{
int
x;
double u, v;
DecimalFormat twoDigits = new DecimalFormat("0.00");
System.out.println("Line 1: Uppercase a is "
+ Character.toUpperCase('a'));
u = 4.2;
v = 3.0;
System.out.println("Line 4: " + u
+ " to the power of "
+ v + " = "
+ twoDigits.format(Math.pow(u,v)));
System.out.println("Line 5: 5 to the power of 4 = "
+ twoDigits.format(Math.pow(5,4)));
u = u + Math.pow(3,3);
System.out.println("Line 7: u = "
+ twoDigits.format(u));
x = -15;
System.out.println("Line 9: Absolute value of " +
+ x + " = " + Math.abs(x));
//Line 1
//Line 2
//Line 3
//Line 4
//Line 5
//Line 6
//Line 7
//Line 8
//Line 9
}
}
3
CHAPTER 7
CMPS 161
Output:
Line
Line
Line
Line
Line
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
USER-DEFINED METHODS









There are two types of user-defined methods: value-returning methods and
void methods.
Value-returning methods, used in expressions, calculate and return a value.
The methods are usually used to save the value for further calculation,
use the value in a calculation or to print the value.
To use these methods you must know:
1. The heading of the method (the name of the method,
2. The number of parameters (if any),
3. The data type of each parameter,
4. The type of the value returned by the method called the type of the
method. The first four properties are the heading of the method.
5. The code required to accomplish the task is the body of the method.
In other words, you must know the definition of the method.
For predefined methods you only need to know the heading, however, for
ones you create, you must know the entire definition.
The variable declared in the heading, within the parentheses, of the method is
called the formal parameter of the method.
The actual parameter is the variable or expression listed in a call to the
method.
Example:
public static double pow (double base, double exponent)
double u = 2.5;
double v = 2.5;
double x, y, w;
x = Math.pow(u, v);
y = Math.pow(2.0, 3.2);
w = Math.pow(u, 7);
The syntax of a value-returning method is:
modifier(s) returnType methodName(formal parameter list)
{
statements
}

The modifier(s) indicates the visibility of the method; where in a program the
method can be used (called).
4
CMPS 161









CHAPTER 7
Some of the modifiers are public, private, protected, static, abstract, and
final.
If you include more than one modifier, they must be separated with spaces.
You can select one modifier among public, protected, and private.
The modifier public specifies that the method can be called outside the class,
and the modifier private specifies that the method cannot be used outside the
class.
Similarly, you can choose one of the modifiers static or abstract.
The returnType is the type of value that the method calculates and returns.
This type is also called the type of the value-returning method.
The methodName is a Java identifier, giving a name to the method, and
statements enclosed between curly braces form the body of the method.
The syntax of the formal parameter list is:
dataType identifier, dataType identifier, …

The syntax to a value-returning method call is:
methodName(actual parameter list)

If the parameter list is empty the parentheses remain empty. The syntax of
the actual parameter list is:
Expression or variable, expression or variable, …




In a method call, the number of actual parameters, together with their data
types, must match the formal parameters in the order given.
Once a value-returning method computes the value, the method returns this
value via the return statement. The syntax is: return expr;
Where expr (a variable, constant, or expression) is evaluated and returned.
The data type of the value that expr computes must match the method type.
public static double larger (double x, double y)
{
if(x >= y)
return x;
else
return y;
}
1. In method larger, x and y are formal parameters.
2. The return statement may appear anywhere and once executed, all
subsequent statements are skipped.
5
CHAPTER 7
CMPS 161
//Program: Largest number
import java.io.*;
import java.util.*;
public class LargestNumber
{
static BufferedReader keyboard = new
BufferedReader(new InputStreamReader(System.in));
public static void
{
double num; //
double max; //
int count; //
main(String[] args) throws IOException
variable to hold the current number
variable to hold the larger number
loop control variable
StringTokenizer tokenizer;
System.out.println("Enter 10 numbers in the same line.");
tokenizer =
new StringTokenizer(keyboard.readLine());
max = Double.parseDouble(tokenizer.nextToken());
//Step 1
//Step 1
for(count = 1; count < 10; count++)
//Step 2
{
num = Double.parseDouble(tokenizer.nextToken()); //Step 2a
max = larger(max, num);
//Step 2b
}
System.out.println("The largest number is " + max);//Step 3
}
public static double larger(double x, double y)
{
if(x >= y)
return x;
else
return y;
}
}
OUTPUT:
Enter 10 numbers in the same line.
1 2 3 4 5 6 7 8 9 10
The largest number is 10.0
6
CMPS 161
CHAPTER 7
FLOW OF EXECUTION





When a program executes, the execution always begins with the first
statement in the method main.
User-defined methods execute only when they are called.
A call to a method transfers control from the caller to the called method.
In a method call statement, you specify only the actual parameters, not their
data type or the method type.
When a method exits, the control goes back to the caller.
VOID METHODS

Void methods do not have a data type. The syntax is as follows:
modifier(s) void methodName()
{
statements
}


A call to a void method is a stand-alone statement.
The method call for void methods, within the class has the following syntax:
methodName();

The void methods without parameters are often used for displaying
information about the program or for printing statements. Ex:
public class Banner2
{
public static void main (String[] args)
{
printStars();
System.out.println("********** Annual ***********");
printStars();
System.out.println("******* Spring Sale **********");
printStars();
}
public static void printStars()
{
int stars, lines;
for(lines = 1; lines <= 2; lines++)
{
for(stars = 1; stars <= 30; stars++)
System.out.print("*");
System.out.println();
}
}
//Line
//Line
//Line
//Line
//Line
1
2
3
4
5
//Line 1
//Line 2
//Line 3
//Line 4
}
7
CMPS 161

CHAPTER 7
The syntax for a void method with parameters is as follows:
modifier(s) void methodName(formal parameter list)
{
statements
}
Where the formal parameter list has the syntax:
dataType variable, dataType variable, …
The method call would have the syntax:
methodName(actual parameter list);
Where the actual parameter list would have the syntax:
expression or variable, expression or variable, …
//Example: Program: Print a triangle of stars
import java.io.*;
public class TriangleOfStars
{
static BufferedReader keyboard =
new BufferedReader(new InputStreamReader(System.in));
public static void main (String[] args) throws IOException
{
int numberOfLines;
int counter;
int numberOfBlanks;
System.out.print("Enter the number of star lines (1 to 20)"
+ " to be printed--> ");
//Line 1
System.out.flush()
//Line 2
numberOfLines =
Integer.parseInt(keyboard.readLine()); //Line 3
while(numberOfLines < 0 || numberOfLines > 20)
//Line 4
{
System.out.println("Number of star lines should be "
+ "between 1 and 20");
//Line 5
System.out.print("Enter the number of star lines (1 "
+ "to 20) to be printed--> ");
//Line 6
System.out.flush();
//Line 7
numberOfLines =
Integer.parseInt(keyboard.readLine());
//Line 8
}
numberOfBlanks = 30;
//Line 9
for(counter = 1; counter <= numberOfLines; counter++)//Line 10
{
8
CHAPTER 7
CMPS 161
printStars(numberOfBlanks, counter);
numberOfBlanks--;
//Line 11
//Line 12
}
}
public static void printStars(int blanks, int starsInLine)
{
int count;
for(count = 1; count <= blanks; count++)
//Line
System.out.print(" ");
//Line
for(count = 1; count <= starsInLine; count++)
//Line
System.out.print(" *");
//Line
System.out.println();
//Line
}
13
14
15
16
17
}
Output:
Enter the number of star lines (1 to 20) to be printed--> 9
*
**
***
****
*****
******
*******
********
*********
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, then after
copying the value of the actual parameter, there is no connection between the
formal parameter and the actual parameter;
A formal parameter of the primitive type cannot pass any result back to
the calling method.
When the method executes, any changes made to the formal parameters do
not in any way affect the actual parameters. The actual parameter has no
knowledge of what is happening to the formal parameter.
Thus, formal parameters of the primitive data types cannot pass
information outside the method.
Formal parameters of the primitive data types provide only a one-way link
between actual parameters and formal parameters.
9
CMPS 161
CHAPTER 7
// Example 7-7
// Programming illustrating how a formal parameter of primitive data
type works.
public class PrimitiveTypeParameters
{
public static void main(String[] args)
{
int number = 6;
//Line 1
System.out.println("Line 2: Before calling the "
+ " method funcPrimFormalParam, "
+ "number = " + number);
//Line 2
funcPrimFormalParam(number);
//Line 3
System.out.println("Line 4: After calling the "
+ "method funcPrimFormalParam, "
+ "number = " + number);
//Line 4
public static void funcPrimFormalParam(int num)
{
System.out.println("Line 5: In the method "
+ "funcPrimFormalParam, before "
+ "changing, num = " + num);
num = 15;
//Line 5
//Line 6
}
System.out.println("Line 7: In the method "
+ "funcPrimFormalParam, after "
+ "changing, num = " + num);
//Line 7
}
}
Output:
Line
Line
Line
Line
2:
5:
7:
4:
Before calling the method funcPrimFormalParam, number = 6
In the method funcPrimFormalParam, before changing, num = 6
In the method funcPrimFormalParam, after changing, num = 15
After calling the method funcPrimFormalParam, number = 6
REFERENCE VARIABLES AS PARAMETERS



A reference variable contains the address (memory location) of the actual
data; both the formal and the value parameters refer to the same object.
Therefore, reference variables can pass one or more values from a
method and can change the value of the actual parameter.
Reference variables, as parameters are useful in three situations:
1. When you want to return more than one value from a method
2. When the value of the actual object needs to be changed
3. When passing the address would save memory space and time,
relative to copying a large amount of data
10
CHAPTER 7
CMPS 161
//Program: This program reads a course score and prints the
//associated course grade.
import java.io.*;
public class Example7_8
{
static BufferedReader keyboard =
new BufferedReader(new InputStreamReader(System.in));
public static void main (String[] args) throws IOException
{
DoubleClass courseScore = new DoubleClass(); // page 866
System.out.println("Line 1: Based on the course score, "
+ "this program computes the "
+ "course grade.");
//Line 1
getScore(courseScore);
printGrade(courseScore.getNum());
//Line 2
//Line 3
}
public static void getScore(DoubleClass score) throws IOException
{
double s;
//Line 4
System.out.print("Line 5: Enter course score: ");
//Line 5
System.out.flush();
//Line 6
s = Double.parseDouble(keyboard.readLine());
//Line 7
score.setNum(s);
//Line 8
System.out.println("\nLine 7: Course score is " + s); //Line 9
}
public static void printGrade(double testScore)
{
System.out.print("Line 10: Your grade for "
+ "the course is ");
if(testScore >= 90)
System.out.println("A");
else if(testScore >= 80)
System.out.println("B");
else if(testScore >= 70)
System.out.println("C");
else if(testScore >= 60)
System.out.println("D");
else
System.out.println("F");
//Line 10
//Line 11
}
}
Output:
Line 1: Based on the course score, this program computes the course
grade.
Line 5: Enter course score: 89
Line 7: Course score is 89.0
Line 10: Your grade for the course is B
11
CHAPTER 7
CMPS 161

This is how the program works:
Line 2 calls the method getScore with the actual parameter courseScore
(a reference variable of the DoubleClass type declared in main).
Formal parameter score, of the method getScore, is a reference variable of
the type DoubleClass, which receives the value of courseScore. Both
courseScore and score point to the same object.
Any changes that score makes to the object immediately change the value
of the object to which courseScore points.
Control is then transferred to the method getScore.
Line 4 declares the variable s of the type double.
Line 5 prints the second line of the output which prompts the user for a score.
Line 7 reads and stores the value entered by the user in s.
Line 8 copies the value of s into the object to which score points.
Now score & courseScore point to the value entered by the user (89.0).
Line 9 outputs the value of s. Also, control goes back to method main.
Line 3 executes next which is a method call to printGrade with the actual
parameter courseScore.getNum(). Method getNum of the class
DoubleClass returns the value of the object pointed to by courseScore.
Test score is then passed as a primitive data type.
Parameters and Memory Allocation



When a method is called, memory for its formal parameters and local
variables is allocated in the method data area.
The value of the actual parameter is copied into the memory cell of its
corresponding formal parameter.
If the parameter is an object (of a class type), both the actual parameter and
formal parameter refer to the same memory space.
Reference Variables of the String Type as Parameters: A Precaution


In the case of reference variables of the type String, we can use the
assignment operator to allocate memory space to store a string and assign
the string to a String variable.
Example:
String str;
str = “Hello”;

str = new String(“Hello”);
12
CMPS 161

CHAPTER 7
If you pass a String variable (a reference variable of the String type) as a
parameter to a method, and within the method you use the assignment
operator to change the string, the string assigned to the actual parameter
does not change; a new string is assigned to the formal parameter.
//Program: String Objects as Parameters
public class StringObjectsAsParemeters
{
public static void main (String[] args)
{
String str = "Hello";
System.out.println("Line 2: str before calling "
+ "the method stringParameter: "
+ str);
stringParameter(str);
System.out.println("Line 4: str after calling "
+ "the method stringParameter: "
+ str);
}
public static void stringParameter(String pStr)
{
System.out.println("Line 5: In the method "
+ "stringParameter");
System.out.println("Line 6: pStr before changing "
+ "its value: " + pStr);
pStr = "Sunny Day";
System.out.println("Line 8: pStr after changing "
+ "its value: " + pStr);
}
}
Output:
Line 2:
Line 5:
Line 6:
Line 8:
Line 4:


//Line 1
//Line 2
//Line 3
//Line 4
//Line 5
//Line 6
//Line 7
//Line 8
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
If you want to pass strings as parameters to a method and want to change the
actual parameter, you can use the class StringBuffer, where strings
assigned to StringBuffer variables can be altered using various methods
provided to manipulate strings (e.g. append, delete).
Example:
13
CMPS 161
CHAPTER 7
//Program: StringBuffer Objects as Parameters
public class StringBufferObjectsAsParemeters
{
public static void main (String[] args)
{
StringBuffer str = new StringBuffer("Hello");
System.out.println("Line 2: str before calling "
+ "the method stringParameter: "
+ str);
stringParameter(str);
System.out.println("Line 4: str after calling "
+ "the method stringParameter: "
+ str);
}
//Line 1
//Line 2
//Line 3
//Line 4
public static void stringParameter(StringBuffer pStr)
{
System.out.println("Line 5: In the method "
+ "stringParameter");
//Line
System.out.println("Line 6: pStr before changing "
+ "its value: " + pStr);
//Line
pStr.append(" There");
//Line
System.out.println("Line 8: pStr after changing "
+ "its value: " + pStr);
//Line
}
Output:
Line 2: str before calling the method stringParameter: Hello
Line 5: In the method stringParameter
Line 6: pStr before changing its value: Hello
Line 8: pStr after changing its value: Hello There
Line 4: str after calling the method stringParameter: Hello There
//Example 7-11
public class Example7_11
{
public static void main(String[] args)
{
int num1;
//Line
IntClass num2 = new IntClass();
//Line
char ch;
//Line
StringBuffer str;
//Line
num1 = 10;
//Line
num2.setNum(15);
//Line
ch = 'A';
//Line
str = new StringBuffer("Sunny");
//Line
System.out.println("Line 9: Inside main: "
+ "num1 = " + num1
+ ", num2 = " + num2.getNum()
+ ", ch = " + ch
+ ", and str = "
+ str);
//Line
funOne(num1, num2, ch, str);
//Line
System.out.println("Line 11: After funcOne: "
+ "num1 = " + num1
+ ", num2 = " + num2.getNum()
5
6
7
8
1
2
3
4
5
6
7
8
9
10
14
CHAPTER 7
CMPS 161
+ ", ch = " + ch
+ ", and str = "
+ str);
//Line
}
public static void funOne(int a, IntClass b,
char v, StringBuffer pStr)
{
int num;
//Line
int len;
//Line
num = b.getNum();
//Line
a++;
//Line
b.addToNum(12);
//Line
v = 'B';
//Line
len = pStr.length();
//Line
pStr.delete(0, len);
//Line
pStr.append("Warm");
//Line
System.out.println("Line 21: Inside funOne: \n"
+ "
a = " + a
+ ", b = " + b.getNum()
+ ", v = " + v
+ ", pStr = " + pStr
+ ", len = " + len
+ ", and num = " + num);
//Line
}
11
12
13
14
15
16
17
18
19
20
21
}
Output
Line: 9 Inside main: num1 = 10, num2 = 15, ch = A, and str = Sunny
Line 21: Inside funOne:
"
a = 11, b = 27, v = B, pStr = Warm, len = 5, and num = 15
Line 11: After funcOne: num1 = 10, num2 = 27, ch = A, and str = Warm
The following is a program walk through!
num1
?
num2
0
ch
?
str
?
Variables and objects just before the statement in Line 5 executes
15
CHAPTER 7
CMPS 161
num1
10
num2
15
ch
A
str
Sunny
Variables and objects after the statement in Line 8 executes
10
a
b
A
num1
v
10
pStr
num2
15
ch
str
?
num
?
len
A
Sunny
Variables and objects just before the statement in Line 14 executes
16
CHAPTER 7
CMPS 161
10
num1
10
a
b
A
num2
v
15
ch
pStr
A
str
Sunny
15
num
?
len
Variables and objects after the statement num = b.getNum(); in Line 14 executes
11
a
b
A
num1
v
10
pStr
num2
15
ch
str
A
15
num
?
len
Sunny
Variables and objects after the statement a++; in Line 15 executes
17
CHAPTER 7
CMPS 161
11
a
b
A
num1
v
10
pStr
num2
27
ch
A
str
15
num
?
len
Sunny
Variables and objects after the statement b.addtoNum(12); in Line 16 executes
11
a
b
B
num1
v
10
pStr
num2
27
ch
str
A
15
num
?
len
Sunny
Variables and objects after the statement v = ‘B’; in Line 17 executes
18
CHAPTER 7
CMPS 161
11
a
b
B
num1
v
10
pStr
num2
27
ch
A
str
15
num
5
len
Sunny
Variables and objects after the statement pStr.length(); in Line 17 executes
11
a
b
B
num1
v
10
pStr
num2
27
ch
A
15
num
5
len
str
Variables and objects after the statement pStr.delete(0, len); in Line 19 executes
19
CHAPTER 7
CMPS 161
11
a
b
B
num1
v
10
pStr
num2
27
ch
A
str
15
num
5
len
Warm
Variables and objects after the statement pStr.append(“Warm”); in Line 20
executes
num1
10
num2
27
ch
str
A
Warm
Variables and objects of main when the control goes back to main
20
CHAPTER 7
CMPS 161
SCOPE OF AN IDENTIFIER WITHIN A CLASS




The scope of an identifier refers to what other parts of the program can “see”
an identifier; where it is accessible (visible).
A local identifier is an identifier declared within a method or block that can
be accessed only by code within that same method or block.
Java does not allow the nesting of methods. That is, you cannot include the
definition of one method in the body of another method.
Within a class, an identifier is accessible throughout the class, with the
exception that a static method cannot access non-static identifiers. The
identifier declared within a block is accessible:
1. Only within the block from the point at which it is declared until the end of
the block.
2. By those blocks that are nested within that block if the nested block does
not have an identifier with the same name as that of the outside block (the
block that encloses the nested block).



Within a method, an identifier 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.
Within a class, any method can call any other method, with the exception
that a static method cannot call a non-static method.
A variable can be declared in the initialization statement of the for statement;
the scope of the variable is limited only to the body of the loop.
for (int count = 1; count < 10; count++)
System.out.println(count);//scope of count is limited only to the body of for loop.
import java.io.*;
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)
{
//...
}
21
CHAPTER 7
CMPS 161
public static int w;
public static void two(int one, int z)
{
char ch;
int a;
//block three
{
int x = 12;
//...
}//end block three
//...
}
}

The following table summarizes the scope (visibility) of the identifiers of the
previous program:
METHOD OVERLOADING: AN INTRODUCTION



Method overloading is creating several methods, within a class, with the
same name.
If several methods within a class have the same name:
o Every method must have a different number of formal parameters,
o Or if the number of formal parameters is the same, then the data type
of the formal parameter, in the order listed, must differ in at least one
position.
The types of parameters determine which method to execute.
22
CHAPTER 7
CMPS 161

Instead of giving different names to methods which perform similar
operations, we can use the same name for each method (overload the
method)
int largerInt (int x, int y)
char largerChar (char first, char second)
double largerDouble (double u, double v)
String largerString (String first, String second)

int larger (int x, int y)
char larger (char first, char second)
double larger (double u, double v)
String larger (String first, String second)
If the call is larger (5, 3) the first method executes because the actual
parameters match the formal parameters of the first method. If the call is
larger (‘A’, ‘9’) the second method executes, and so on.
Key Terms














Actual parameter: a variable or expression listed in a call to a method.
Class libraries: organized collection of classes.
Formal parameter: a variable declared in the method heading.
Local identifier: an identifier declared within a method or block that can
be accessed only by code within that same method or block.
Local variables: variables declared in the body of the method.
Method type: data type of the value returned by the method.
Modules: another name for methods.
Palindrome: integer or string that reads the same forwards and
backwards.
Parameters: arguments of a method.
Predefined methods: methods that are already written and provided by
Java.
Scope: refers to what other parts of the program can “see” an identifier.
User-defined methods: methods that the programmer creates.
Value-returning methods: methods that have a return type.
Void methods: methods that do not have a return type.
23
Download