Download presentation
Presentation is loading. Please wait.
1
Reference: COS240 Syllabus
COS240 O-O Languages AUBG, COS dept Lecture 11 Title: Java Methods Reference: COS240 Syllabus
2
Lecture Contents: Creating/Defining method Calling a Method
Passing Parameters by Values Overloading Methods The Scope of Local Variables Method Abstraction TheMath Class
3
Why methods? Any Java program must have at least one class.
Each class begins with a class declaration that defines data items and methods for the class. The class contains a method named main(…). The main(…) method is invoked by JVM.
4
Benefits of Methods Write a method once and reuse it anywhere.
Information hiding. Hide the implementation from the user. Reduce complexity.
5
Categories of Methods Predefined methods User defined methods
6
Predefined Methods Methods already written and provided by JRE
Organized as a collection of classes (class libraries) To use: import <package>; Method type: value data type returned by method Illustration: Math class, String class Java Programming: From Problem Analysis to Program Design, 4e 6
7
Predefined methods
8
Predefined Classes (continued)
Java Programming: From Problem Analysis to Program Design, 4e 8
9
Predefined Classes (continued)
Java Programming: From Problem Analysis to Program Design, 4e 9
10
Predefined Classes (continued)
Java Programming: From Problem Analysis to Program Design, 4e 10
11
Some Commonly Used String Methods
Java Programming: From Problem Analysis to Program Design, 4e 11
12
Some Commonly Used String Methods (continued)
Java Programming: From Problem Analysis to Program Design, 4e 12
13
Some Commonly Used String Methods (continued)
Java Programming: From Problem Analysis to Program Design, 4e 13
14
Some Commonly Used String Methods (continued)
Java Programming: From Problem Analysis to Program Design, 4e 14
15
Some Commonly Used String Methods (continued)
Java Programming: From Problem Analysis to Program Design, 4e 15
16
Categories of Methods Predefined methods User defined methods
17
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 17
18
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++) System.out.println("Sum from 20 to 30 is " + sum); for (int i = 35; i <= 45; i++) System.out.println("Sum from 35 to 45 is " + sum);
19
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));
20
Creating/Defining Methods
A method is a collection of statements that are grouped together to perform an operation.
21
Method Signature Method signature is the combination of the method name and the parameter list.
22
Formal Parameters The variables defined in the method header are known as formal parameters.
23
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.
24
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.
25
Note In certain PL methods are referred to as:
procedures functions A method with a non void return value type is called a function. A method with a void return value type is called a procedure.
26
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”);
27
Calling Methods, cont.
28
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. 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.
29
Reuse Methods from Other Classes
NOTE: One of the benefits of methods is for reuse. The max method can be invoked from any class besides TestMax. If you create a new class Test, you can invoke the max method using ClassName.methodName (e.g., TestMax.max).
30
Call Stacks
31
void Method Example This type of method does not return a value. The method performs some actions.
32
Passing Parameters Suppose you invoke the method using
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”, 65); What is the output? nPrintln(“Computer Science”, 45);
33
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.
34
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) {
35
Overloading Methods Overloaded methods must have different parameter lists. You cannot overload methods based on different modifiers or different return types.
36
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 36
37
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.
38
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) {
39
Arrays and Methods Passing Arrays to methods
Through parameter passing mechanism Returning an Array from a Method Through return stmt
40
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; }
41
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
42
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.
43
Scope of Local Variables, cont.
You can declare a local variable with the same name multiple times in different non-nesting blocks in a method, but you cannot declare a local variable twice in nested blocks.
44
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.
45
Scope of Local Variables, cont.
46
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 y += i;
47
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; }
48
Method Abstraction You can think of the method body as a black box that contains the detailed implementation for the method.
49
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.
50
PrintCalender Case Study
Let us use the PrintCalendar example to demonstrate the stepwise refinement approach.
51
Design Diagram
52
Design Diagram
53
Design Diagram
54
Design Diagram
55
Design Diagram
56
Design Diagram
57
Implementation: Top-Down
Top-down approach is to implement one method in the structure chart at a time from the top to the bottom. Stubs can be used for the methods waiting to be implemented. A stub is a simple but incomplete version of a method. The use of stubs enables you to test invoking the method from a caller. Implement the main method first and then use a stub for the printMonth method. For example, let printMonth display the year and the month in the stub. Thus, your program may begin like this: A Skeleton for printCalendar
58
Implementation: Bottom-Up
Bottom-up approach is to implement one method in the structure chart at a time from the bottom to the top. For each method implemented, write a test program to test it. Both top-down and bottom-up methods are fine. Both approaches implement the methods incrementally and help to isolate programming errors and makes debugging easy. Sometimes, they can be used together.
59
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)
60
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
61
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 61
62
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 62
63
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.
64
Thank You for Your attention!
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.