Download week-11-12-13-lecs-ch07_methods

Document related concepts
no text concepts found
Transcript
Chapter 5: METHODS
USER-DEFINED METHODS
user-defined
2
We learned that a Java application program is a
collection of classes, and that a class is a
collection of methods and data members.
 use only the method main; all the programming
instructions are packed into one method.
 For large programs, it is not practical to put the
entire programming instructions into one
method, You must learn to break the problem
into manageable pieces.

Java Programming: From Problem Analysis to Program Design, 4e
Chapter Objectives
3

Learn about user-defined methods
 Learn
how to construct and use user-defined void
methods in a program
 Actual and formal parameters
 Explore how to construct and use a value-returning
Explore using variables as parameters
 Explore using arrays as parameters.

Java Programming: From Problem Analysis to Program Design, 4e
Chapter Objectives (continued)
4
Learn about standard (predefined) methods
and discover how to use them in a program
 Learn about the scope of an identifier
 Become aware of method overloading

Java Programming: From Problem Analysis to Program Design, 4e
Why use method
5
Using methods has several advantages:
 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.
Java Programming: From Problem Analysis to Program Design, 4e
Syntax: Method
6
Java Programming: From Problem Analysis to Program Design, 4e
Syntax: Method
7
• There are 3 different criteria defining types of
methods:
• Modifiers: this criteria is also composed of 3 sub-criteria:
» Visibility: public or private (or protected in csc 113)
» Shared between all instances or not: class member (static) or
instance method.
» Override able or not (final): to be discussed in CSC 113.
• Return type: method with or without (void) return value.
• Parameters: with or without parameters.
•Every method have two important elements :
Method head: used to declare and define the method.
Method call: used to invoke and employ this method.
User-Defined Methods
8
1-Method Head :

To declare a method,the user must specify the following:
modifiers: public, private, protected,
static, abstract, final
returnType: type of the value that the method
calculates and returns (using return statement)
methodName: Java identifier; name of method

formal parameter list:The syntax of the



formal parameter list is:
Java Programming: From Problem Analysis to Program Design, 4e
User-Defined Methods
9
2-Method call
-The syntax to call a value-returning method is:
-
Actual parameter list are also called arguments
The syntax of the actual parameter list (arguments) is:
Java Programming: From Problem Analysis to Program Design, 4e
User-Defined Methods
10
Void Methods:
 Defined by users.
 Call to method is always stand-alone
statement
 Can use return statement to exit method
early (optional)
Java Programming: From Problem Analysis to Program Design, 4e
Void Methods without Parameters:
Syntax
Method Definition
The definition of void method without parameters has the following syntax:
modifier(s) void methodName( )
{
statements
}
Method Call
A method call has the following syntax:
methodName( ) ;
To call a method, you use its name.
Void method: Example (1)
Public static void theMethod( )
{
System.out.println(“3”+”+”+”4”+”=“+ (3+4));
}
Void method: Example (2)
public static void drawRectangle ( )
{
System.out.println(“Enter the dimensions of your rectangle ”);
int x=read.nextInt();
int y=read.nextInt();
for( int i = 0 ; i < x ; i++ )
{
for( int j = 0 ; j < y ; j++ )
System.out.print(“*”);
System.out.println();
}
}
Void Methods with Parameters: Syntax
14
Java Programming: From Problem Analysis to Program Design, 4e
15
Void Methods with Parameters:
Syntax (continued)
To call a method you use its name, with the actual parameters (if
any) in parentheses.
Java Programming: From Problem Analysis to Program Design, 4e
Formal parameters
16
Modifiers
Method
heading
Method
name
Formal
parameters
public static void larger (double x, double y)
{
Formal parameters list
if ( x >= y )
System.out.print(“The max is ”+x);
else
System.out.print(“the max is ”+ y);
Method
body
}
Java Programming: From Problem Analysis to Program Design, 4e
Actual parameters
Method call
Actual parameters
larger ( 2.5 , 5.4 );
Method call
Actual parameters
larger ( num1 , num2 );
Method call
Actual parameters
larger ( num1 , 33,2 );
17
Java Programming: From Problem Analysis to Program Design, 4e
Void method with parameters:
Example
public static void drawRectangle (int x, int y )
{
for( int i = 0 ; i < x ; i++ )
{
for( int j = 0 ; j < y ; j++ )
System.out.print(“*”);
System.out.println();
}
}
Void method with parameters:
Example (print area of a rectangle)
public static void areaofRectangle (int l, int w )
{
System.out.println( “the Area of the rectangle is” + (l*w));
}
Flow of Execution
20
Execution always begins with the first statement
in the method main
 User-defined methods execute only when called
 Call to method transfers control from caller to
called method
 In method call statement, specify only actual
parameters, not data type or method type
 Control goes back to caller when method exits

Java Programming: From Problem Analysis to Program Design, 4e
21
Flow
of Execution – Example
Execution begins
with the 1st
(void)
statement in main
Public static void main( String args[])
{
System.out.println(“Before call”);
theMethod();
System.out.println(“Aftere call”);
}
Call to method
transfers control from
caller to called method
Public static void theMethod( )
{
System.out.println(“in method “);
}
Before call
In method
After call
Control goes back to
caller when method
exits
Java Programming: From Problem Analysis to Program Design, 4e
22
Flow
of Execution – Example
Execution begins
with the 1st
(parameters)
statement in main
Public static void main( String args[])
{
System.out.println(“Before call”);
method(“csc111”);
System.out.println(“Aftere call”);
}
Call to method
transfers control from
caller to called method
and passing parameter
from main to method
Public static void method( String str)
{
System.out.println(str);
}
Before call
csc111
After call
Control goes back to
caller when method
exits
Java Programming: From Problem Analysis to Program Design, 4e
Value returning Methods
23
Value-returning methods
 Used
in expressions
 Calculate and return a value
 Can save value for later calculation or print value
Java Programming: From Problem Analysis to Program Design, 4e
Value returning Methods: Syntax
24
Java Programming: From Problem Analysis to Program Design, 4e
Value returning Methods: Syntax
25
Java Programming: From Problem Analysis to Program Design, 4e
Value returning Methods: Actual
and formal parameters
Java Programming: From Problem Analysis to Program Design, 4e
26
Value returning Methods: Actual
and formal parameters
Java Programming: From Problem Analysis to Program Design, 4e
27
Return Statment
28
• Syntax: return statement
•return statement will return the flow of the
program from the method to the main method.
•It is also used to return the value resulting from
the method to the main method to be used their.
-The return statement has the following syntax:
return expr/value/variable;
Important note:
1-value returning methods must have a return statement
2- The value they return must be the same as the method
Java Programming: From Problem Analysis to Program Design, 4e
data type
29
Executionof
begins
Flow
Execution
–
Example
(no
with the 1st
statement in main
parameters)
Public static void main( String args[])
{
System.out.println(“Before call”);
System.out.println( theMethod());
System.out.println(“Aftere call”);
}
Call to method
transfers control from
caller to called method
Public static int theMethod( )
{
int x= 1000;
return x;
}
Before call
1000
After call
Control goes back to
caller when method
exits
Java Programming: From Problem Analysis to Program Design, 4e
30
Executionof
begins
Flow
Execution
–
Example
with the 1st
statement parameters)
in main
(with
Public static void main( String args[])
{
System.out.println(“Before call”);
System.out.println( method(6));
System.out.println(“Aftere call”);
}
Call to method
transfers control from
caller to called method
Public static int method(int num )
{
return ++num;
}
Before call
7
After call
Control goes back to
caller when method
exits (return in this e.g)
Java Programming: From Problem Analysis to Program Design, 4e
31
Return Statement – Equivalent
Examples
public static double
larger(double x,
double y)
{
public static double
larger(double x,
double y)
public static double
larger(double x,
double y)
{
{
if (x >= y)
return x;
else
return y;
double max;
if (x >= y)
max = x;
else
max = y;
}
return max;
}
Java Programming: From Problem Analysis to Program Design, 4e
if (x >= y)
return x;
return y;
}
Examples (1)
The int variable num contains the number that we want to
compute the factorial
public static int factorial (int num )
{
int fact=1;
for (int i=2;i<=num;i++)
fact=fact*i;
return fact;
}
Java Programming: From Problem Analysis to Program Design, 4e
32
Examples (2): Palindrome Number
33
Palindrome: integer or string that reads the
same forwards and backwards
 The method isPalindrome takes a string
as a parameter and returns true if the
string is a palindrome, false otherwise

Java Programming: From Problem Analysis to Program Design, 4e
Examples (2) - Cont
34
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;
}
Java Programming: From Problem Analysis to Program Design, 4e
Example (3):Largest Number
35
Input: set of 10 numbers
 Output: largest of 10 numbers
 Solution

 Get
numbers one at a time
 Method largest number: returns the larger of two numbers
 For loop: calls method largest number on each number
received and compares to current largest number
Java Programming: From Problem Analysis to Program Design, 4e
Examples (3) - Cont
36
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);
}
Java Programming: From Problem Analysis to Program Design, 4e
Examples (3) - cont
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
Java Programming: From Problem Analysis to Program Design, 4e
38
Primitive VS. Reference Variables
Week 12
Java Programming: From Problem Analysis to Program Design, 4e
Primitive VS. Reference Variables
• Primitive variables hold values of primitive data
types.
1
Example: int x = 5;
x
x is primitive variable
• Instance variables hold references of objects: the
location (memory address) of objects in memory.
Example: int [] arr = {1,2,3,4,5};
arr is reference variable, it carries the address of
the location of the array
1100
arr 1100
39
1
2
3
4
5
40
Primitive Data Type Variables as
Parameters
A formal parameter receives a copy of its
corresponding actual 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
Java Programming: From Problem Analysis to Program Design, 4e
Reference Variables as Parameters
41

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 parameter refer to same object
Java Programming: From Problem Analysis to Program Design, 4e
42
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 address, would save memory
space and time, relative to copying large
amount of data

Java Programming: From Problem Analysis to Program Design, 4e
43

Declaring Arrays as Formal
Parameters to Methods
A general syntax to declare an array as a formal
parameter
public static void arraysAsFormalParameter(int[] listA,
double[] listB, int num)
{
//...
}
int[] intList = new int[10];
double[] doubleNumList = new double[15];
int number;
arraysAsFormalParameter(intList, doubleNumList, number);
Java Programming: From Problem Analysis to Program Design, 4e
Arrays as Parameter to Methods
44
Java Programming: From Problem Analysis to Program Design, 4e
Methods for Array Processing
45
Java Programming: From Problem Analysis to Program Design, 4e
Methods for Array Processing (continued)
46
Methods for Array Processing
(continued)
47
Java Programming: From Problem Analysis to Program Design, 4e
48
Methods for Array Processing
(elements of array as par.)
Java Programming: From Problem Analysis to Program Design, 4e
49
Methods for Array Processing
(search)
public static int seqSearch(int[] list,
int listLength, int searchItem)
{
int loc;
boolean found = false;
loc = 0;
while (loc < listLength && !found)
if (list[loc] == searchItem)
found = true;
else
loc++;
if (found)
return loc;
else
return -1;
}
Java Programming: From Problem Analysis to Program Design, 4e
49
Relational Operators and Arrays
(example)
50
boolean areEqualArrays(int[] firstArray,
int[] secondArray)
{
if (firstArray.length != secondArray.length)
return false;
for (int index = 0; index < firstArray.length;
index++)
if (firstArray[index] != secondArray[index])
return false;
return true;
}
if (areEqualArrays(listA, listB))
...
Java Programming: From Problem Analysis to Program Design, 4e
Arrays and Variable Length Parameter
List
51

The syntax to declare a variable length formal
parameter (list) is:
dataType ... identifier
Java Programming: From Problem Analysis to Program Design, 4e
Arrays and Variable Length Parameter List (continued)
52
Java Programming: From Problem Analysis to Program Design, 4e
53
Arrays and Variable Length
Parameter List (continued)
Java Programming: From Problem Analysis to Program Design, 4e
Arrays and Variable Length
Parameter List (continued)
54
• A method can have both a variable length formal
parameter and other formal parameters; consider the
following method heading:
public static void myMethod(String name,
double num, int ... intList)
• The formal parameter name is of type String, the
formal parameter num is of type double, and the
formal parameter intList is of variable length
• The actual parameter corresponding to intList can
be an int array or any number of int variables and/or
int values
Java Programming: From Problem Analysis to Program Design, 4e
55
Arrays and Variable Length
Parameter List (continued)
A method can have at most one variable length
formal parameter
 If a method has both a variable length formal
parameter and other types of formal
parameters, then the variable length formal
parameter must be the last formal parameter of
the formal parameter list

Java Programming: From Problem Analysis to Program Design, 4e
Reference Variables as Parameters: type
String (special case)
Java Programming: From Problem Analysis to Program Design, 4e
56
Reference Variables as Parameters: type
String (continued)
Java Programming: From Problem Analysis to Program Design, 4e
57
Reference Variables as Parameters: type
String (continued)
Java Programming: From Problem Analysis to Program Design, 4e
58
Reference Variables as Parameters: type
String (continued)
Java Programming: From Problem Analysis to Program Design, 4e
59
Reference Variables as Parameters: type
String (continued)
String str = "Hello";
Java Programming: From Problem Analysis to Program Design, 4e
//Line 5
60
Reference Variables as Parameters: type
String (continued)
stringParameter(str);
Java Programming: From Problem Analysis to Program Design, 4e
//Line 7
61
Reference Variables as Parameters: type
String (continued)
pStr = "Sunny Day";
//Line 14
Java Programming: From Problem Analysis to Program Design, 4e
62
Reference Variables as Parameters: type
String (continued)
Variables before the statement in Line 8 executes
Java Programming: From Problem Analysis to Program Design, 4e
63
Predefined Classes
64
Methods already written and provided by Java
 Organized as a collection of classes (class
libraries)
 To use: import package
 Method type: data type of value returned by
method

Java Programming: From Problem Analysis to Program Design, 4e
Predefined Classes (continued)
65
Java Programming: From Problem Analysis to Program Design, 4e
Predefined Classes (continued)
66
Java Programming: From Problem Analysis to Program Design, 4e
67
Java Programming: From Problem Analysis to Program Design, 4e
Predefined Classes (continued)
68
Java Programming: From Problem Analysis to Program Design, 4e
69
random()
return a value of type double greater than or
equal to 0.0 and less than 1.0.
Java Programming: From Problem Analysis to Program Design, 4e
Example
70
double x = Math.pow(3,2);
double area = Math.PI*radius*radius;
If you use the static import statement, you
can omit the name of class
import static java.lang.Math.*;
double x = pow(3,2);
-
Java Programming: From Problem Analysis to Program Design, 4e
71

Generating random variable in
range
General form
randomNum = (int) (Math.random()*range ‫)عدد االلمنت‬+minimum ;
Rollin dice
int dice2 = (int) (Math.random() * 6) + 1;

Java Programming: From Problem Analysis to Program Design, 4e
class Character
(Package: java.lang)
72
Java Programming: From Problem Analysis to Program Design, 4e
class Character
(Package: java.lang) (continued)
73
Java Programming: From Problem Analysis to Program Design, 4e
class Character
(Package: java.lang) (continued)
74
Java Programming: From Problem Analysis to Program Design, 4e
75
Scope and overloading
Week 13
Java Programming: From Problem Analysis to Program Design, 4e
Scope of an Identifier within a Class
76
Local identifier: identifier declared within a method
or block, which is visible only within that method or
block
 Java does not allow the nesting of methods; you
cannot include the definition of one method in the
body of another method
 Within a method or a block, an identifier must be
declared before it can be used; a block is a set of
statements enclosed within braces

Java Programming: From Problem Analysis to Program Design, 4e
77
Scope of an Identifier within a
Class (continued)

A method’s definition can contain several
blocks
body of a loop or an if statement also form a
block
 The

Within a class, outside of every method
definition (and every block), an identifier
can be declared anywhere
Java Programming: From Problem Analysis to Program Design, 4e
78
Scope of an Identifier within a
Class (continued)
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
 For example, in the method definition on the
next slide, the second declaration of the
variable x is illegal

Java Programming: From Problem Analysis to Program Design, 4e
Scope of an Identifier within a
Class (continued)
79
public static void illegalIdentifierDeclaration()
{
int x;
//block
{
double x;
//illegal declaration,
//x is already declared
...
}
}
Java Programming: From Problem Analysis to Program Design, 4e
Scope Rules
80
Scope rules of an identifier declared within a
class and accessed within a method (block) of
the class
 An identifier, say X, 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
Java Programming: From Problem Analysis to Program Design, 4e
Scope Rules (continued) Example 7-11
81
public static int w;
public static void two(int one, int z)
{
char ch;
int a;
//block three
{
int x = 12;
//...
} //end block three
//...
}
}
Java Programming: From Problem Analysis to Program Design, 4e
Scope Rules (continued)
82

Suppose X is an identifier declared within a class
and outside of every method’s definition (block)
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
 If
Java Programming: From Problem Analysis to Program Design, 4e
Scope Rules (continued) Example 7-11
83
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)
{
//...
}
Java Programming: From Problem Analysis to Program Design, 4e
Scope Rules (continued) Example 7-11
84
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)
{
//...
}
public static int w;
public static void two(int one, int z)
{
char ch;
int a;
static final double rate
static int z;
static double t;
main
int num;
double x, z;char ch;
Method one
one(int x, char y)
public static int w;
Method two
two(int one, int z)
{
int x = 12;
}
//...
}
}
Java Programming: From Problem Analysis to Program Design, 4e
char ch; int a;
int x = 12;
Scope Rules: Demonstrated (continued)
85
Java Programming: From Problem Analysis to Program Design, 4e
Scope Rules: Demonstrated
86
Java Programming: From Problem Analysis to Program Design, 4e
Scope Rules – Scanner Example
87
public class ScopeRules {
Can be accessed
static Scanner read=new Scanner (System.in);
public static void main(String[] args){ from any method
(static & non-static)
int number = read.nextInt();
including main,
//…
}
}
public class ScopeRules {
public static void main(String[] args){
Scanner read=new Scanner (System.in);
int number = read.nextInt();
‘Local ‘ accessed
//…
}
from main only
}
public class ScopeRules {
Scanner read=new Scanner (System.in);
public static void main(String[] args){ Can be accessed
int number = read.nextInt();
from non-static
//…
}
method only
Java Programming: From Problem Analysis to Program Design, 4e
}
Method Overloading:
An Introduction
88
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, or
 If the number of formal parameters is the same, then
the data type of the formal parameters, in the order you
list, must differ in at least one position
Java Programming: From Problem Analysis to Program Design, 4e
Method Overloading
89
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
Java Programming: From Problem Analysis to Program Design, 4e
Method Overloading (continued)
90
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

Java Programming: From Problem Analysis to Program Design, 4e
Method Overloading (continued)
91
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
Java Programming: From Problem Analysis to Program Design, 4e
Method Overloading (continued)
92

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)
Java Programming: From Problem Analysis to Program Design, 4e
Method Overloading (continued)
93
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
Java Programming: From Problem Analysis to Program Design, 4e
Chapter Summary
94
Predefined methods
 User-defined methods

 Value-returning
methods
 Void
methods
 Formal parameters
 Actual parameters

Flow of Execution
Java Programming: From Problem Analysis to Program Design, 4e
Chapter Summary (continued)
95

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

Java Programming: From Problem Analysis to Program Design, 4e