COS240Lec11_JavaMethods

Download Report

Transcript COS240Lec11_JavaMethods

COS240 O-O Languages
AUBG, COS dept
Lecture 11
Title:
Java Methods
Reference: COS240 Syllabus
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
1
Lecture Contents:










Creating/Defining method
Calling a Method
Passing Parameters by Values
Overloading Methods
The Scope of Local Variables
Method Abstraction
TheMath Class
Case Study: Generating Random Characters
Stepwise Refinements
4.12 Packages
P159
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
2
Digression on previous Lecture
.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
Why methods?
 Every
Java program must have at least one
class.
 Each class begins with a class declaration that
defines data and methods for the class.
 The class contains a method named main(…).
The main(…) method is invoked by the
interpreter or JVM.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
4
Benefits of Methods
• Write a method once and reuse it anywhere.
• Information hiding. Hide the implementation
from the user.
• Reduce complexity.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
5
Predefined Methods
 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
 Illustration: Math class, String class
Java Programming: From Problem Analysis to Program Design, 4e
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
6
6
Predefined methods
Java Programming: From Problem Analysis to Program Design, 4e
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
7
7
Predefined Classes (continued)
Java Programming: From Problem Analysis to Program Design, 4e
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
8
8
Predefined Classes (continued)
Java Programming: From Problem Analysis to Program Design, 4e
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
9
9
Predefined Classes (continued)
Java Programming: From Problem Analysis to Program Design, 4e
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
10
10
Some Commonly Used String
Methods
Java Programming: From Problem Analysis to Program Design, 4e
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
11
11
Some Commonly Used String Methods (continued)
Java Programming: From Problem Analysis to Program Design, 4e
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
12
12
Some Commonly Used String Methods (continued)
Java Programming: From Problem Analysis to Program Design, 4e
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
13
13
Some Commonly Used String
Methods (continued)
Java Programming: From Problem Analysis to Program Design, 4e
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
14
14
Some Commonly Used String Methods (continued)
Java Programming: From Problem Analysis to Program Design, 4e
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
15
15
User-Defined Methods
 User-defined
methods in Java are classified in
two categories:
 Value-returning methods
– Methods have a return data type
– Methods return a value of specific data type using return
statement
– Used in expressions, Calculate and return a value
– Can save value for later calculation or print value
 Void methods
– Methods that do not have a return data type
– Methods do not use return statement to return a value
Java Programming: From Problem Analysis to Program Design, 4e
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
16
16
Opening Problem
Find the sum of integers from 1 to 10, from 20 to 30, and
from 35 to 45, respectively.
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);
sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
System.out.println("Sum from 20 to 30 is " + sum);
sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
System.out.println("Sum
from 35 to 45 is " + sum);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
17
Solution
public static int sum(int i1, int i2) {
int sum = 0;
for (int i = i1; i <= i2; i++)
sum += i;
return sum;
}
public static void main(String[] args) {
System.out.println("Sum from 1 to 10 is " + sum(1, 10));
System.out.println("Sum from 20 to 30 is " + sum(20, 30));
System.out.println("Sum from 35 to 45 is " + sum(35, 45));
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
18
Creating/Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
19
Method Signature
Method signature is the combination of the method name and the
parameter list.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
20
Formal Parameters
The variables defined in the method header are known as
formal parameters.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
21
Actual Parameters/Arguments/
When a method is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
22
Return Value Type
A method may return a value. The returnValueType is the data type
of the value the method returns. If the method does not return a
value, the returnValueType is the keyword void. For example, the
returnValueType in the main method is void.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
23
Note
In
certain PL methods are referred to as:
– procedures
– functions
with a non void return
value type is called a function.
A method with a void return value
type is called a procedure.
A method
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
24
Calling Methods
•In creating a method, you give a definition of what
the method is expected to do.
•To use a method, you have to call it, or invoke it, or
activate it in two ways:
•As a value, (i.e. operand of an expression)
Larger = max(20, 50);
System.out.println(“Result is=“, max(20,50));
•As a statement
System.out.println(“JAVA”);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
25
Calling Methods, cont.
pass the value of i
pass the value of j
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
26
CAUTION
A return statement is required for a value-returning method. The
method shown below in (a) is logically correct, but it has a
compilation error because the Java compiler thinks it possible that
this method does not return any value.
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else if (n < 0)
return –1;
}
(a)
Should be
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else
return –1;
}
(b)
To fix this problem, delete if (n < 0) in (a), so that the compiler will
see a return statement to be reached regardless of how the if
statement is evaluated.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
27
Call Stacks
Space required for
the max method
num2: 2
num1: 5
Space required for
the max method
result: 5
num2: 2
num1: 5
Space required for
the main method
k:
2
j:
5
i:
Space required for
the main method
k:
2
j:
5
i:
Space required for
the main method
k:
2
j:
5
i:
Space required for
the main method
5
k:
2
j:
5
i:
(a) The main
method is invoked.
(b) The max
method is invoked.
(c) The max method
is being executed.
(d) The max method is
finished and the return
value is sent to k.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Stack is empty
(e) The main
method is finished.
28
void Method Example
This type of method does not return a value. The method
performs some actions.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
29
Passing Parameters
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
Suppose you invoke the method using
nPrintln(“Welcome to Java”, 5);
What is the output?
Suppose you invoke the method using
nPrintln(“Computer Science”, 15);
What is the output?
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
30
Passing parameters by Values
When calling a method, the argument value
is passed /copied/ to the formal parameter.
The argument is not affected,
regardless of the changes made to the
parameter inside the method.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
31
Overloading Methods
Overloading the max Method
public static double max(int num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
32
Overloading Methods
Overloaded methods must have different
parameter lists.
You cannot overload methods based on
different modifiers or different return
types.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
33
Learning About Ambiguity
(continued)
 Overload
methods
– Correctly provide different argument lists for
methods with same name
 Illegal
methods
– Methods with identical names that have
identical argument lists but different return
types
– int aMethod(int x)
– void aMethod(int x)
Java Programming,
Fifth Edition
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
34
34
Ambiguous Invocation
Sometimes there may be two or more
possible matches for an invocation of a
method, but the compiler cannot determine
the most specific match. This is referred to
as ambiguous invocation. Ambiguous
invocation is a compilation error.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
35
Ambiguous Invocation
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1, 2));
}
public static double max(int num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
36
Scope of Local Variables
A local variable: a variable defined inside a
method.
Scope: the part of the program where the
variable can be referenced.
The scope of a local variable starts from its
declaration and continues to the end of the
block that contains the variable. A local
variable must be declared before it can be
used.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
37
Scope of Local Variables, cont.
You can declare a local variable with the
same name multiple times in different nonnesting blocks in a method, but you cannot
declare a local variable twice in nested
blocks.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
38
Scope of Local Variables, cont.
A variable declared in the initial action part of a for loop
header has its scope in the entire loop. But a variable
declared inside a for loop body has its scope limited in the
loop body from its declaration and to the end of the block
that contains the variable.
The scope of i
The scope of j
public static void method1() {
.
.
for (int i = 1; i < 10; i++) {
.
.
int j;
.
.
.
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
39
Scope of Local Variables, cont.
It is fine to declare i in two
non-nesting blocks
public static void method1() {
int x = 1;
int y = 1;
It is wrong to declare i in
two nesting blocks
public static void method2() {
int i = 1;
int sum = 0;
for (int i = 1; i < 10; i++) {
x += i;
}
for (int i = 1; i < 10; i++) {
y += i;
}
for (int i = 1; i < 10; i++) {
sum += i;
}
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
40
Scope of Local Variables, cont.
// Fine with no errors
public static void correctMethod() {
int x = 1;
int y = 1;
// i is declared
for (int i = 1; i < 10; i++) {
x += i;
}
// i is declared again
for (int i = 1; i < 10; i++) {
y += i;
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
41
Scope of Local Variables, cont.
// With no errors
public static void incorrectMethod() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
int x = 0;
x += i;
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
42
Method Abstraction
You can think of the method body as a black box
that contains the detailed implementation for the
method.
Optional arguments
for Input
Optional return
value
Method Header
Black Box
Method body
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
43
Stepwise Refinement (Optional)
The concept of method abstraction can be applied
to the process of developing programs. When
writing a large program, you can use the “divide
and conquer” strategy, also known as stepwise
refinement, to decompose it into subproblems. The
subproblems can be further decomposed into
smaller, more manageable problems.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
44
Arrays and Methods
Passing Arrays
to methods
– Through parameter passing mechanism
Returning
an Array from a Method
– Through return stmt
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
45
Arrays and Methods
public static int[] arrayProcess(int[] par) {
int j;
int[] b = new int[par.length];
for (j=1; j<par.length; j++) b[j] = par[j] *10;
return b;
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
46
Arrays and Methods
public static void main(String[] args) {
int[] ar = new int[10];
for (i=0; i < ar.length; i++) ar[i] = i;
int[] br;
br = arrayProcess(ar);
for (i=0; i < br.length; i++)
System.out.print(br[i] + " ");
}// end of main
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
47
Exercise on methods
Write a program to demonstrate how to create and invoke max method
Write a program to demonstrate how to create and invoke min method
Write a Java program as a single class and methods:
• method main()
• method to return the greatest common divisor of two positive integer
values
•Method to return the factorial of its integer argument
•Method to return the sum of positive integer numbers in range from
0…n, n is a parameter.
•Method to return the sum of integer numbers in range from n1…n2, and
n1, n2 are parameters, such that n1<n2
Write a program to demonstrate the effect of passing by value. (method
swap)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
48
Exercises
 Palindrome:
string that reads the same
forwards and backwards
 Write a value-returning method
isPalindrome(), that returns true if a
given string is palindrome, i.e. it reads the
same way forwards and backwards.
 The method isPalindrome() takes a
string as a parameter and returns true if
the string is a palindrome, false otherwise
 Write a Java program to test the method
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
49
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;
}
Java Programming: From Problem Analysis to Program Design, 4e
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
50
50
Rewrite isPalindrome() Method
using while loop stmt
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
51
51
Exercises
 Write
a value-returning method
isVowel(), that returns true if a given
character is vowel, and otherwise returns
false.
 Write a Java program to test the method
 Write a Java program to output the number
of vowels in a string.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
52
Thank You
for
Your attention!
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
53