Presentation is loading. Please wait.

Presentation is loading. Please wait.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 COS240 O-O Languages AUBG,

Similar presentations


Presentation on theme: "Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 COS240 O-O Languages AUBG,"— Presentation transcript:

1 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 COS240 O-O Languages AUBG, COS dept Lecture 11 Title: Java Methods Reference: COS240 Syllabus

2 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 2 Lecture Contents: F Creating/Defining method F Calling a Method F Passing Parameters by Values F Overloading Methods F The Scope of Local Variables F Method Abstraction F TheMath Class F Case Study: Generating Random Characters F Stepwise Refinements F 4.12 PackagesP159

3 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 3 Digression on previous Lecture F.F.

4 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 4 Why methods? F Every Java program must have at least one class. F 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.

5 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 5 Benefits of Methods Write a method once and reuse it anywhere. Information hiding. Hide the implementation from the user. Reduce complexity.

6 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 6 6Java Programming: From Problem Analysis to Program Design, 4e Predefined Methods F Methods already written and provided by Java F Organized as a collection of classes (class libraries) F To use: import package F Method type: data type of value returned by method F Illustration: Math class, String class

7 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 7 7Java Programming: From Problem Analysis to Program Design, 4e Predefined methods

8 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 8 8Java Programming: From Problem Analysis to Program Design, 4e Predefined Classes (continued)

9 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 9 9Java Programming: From Problem Analysis to Program Design, 4e Predefined Classes (continued)

10 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 10 Java Programming: From Problem Analysis to Program Design, 4e Predefined Classes (continued)

11 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 11 Java Programming: From Problem Analysis to Program Design, 4e Some Commonly Used String Methods

12 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 12 Java Programming: From Problem Analysis to Program Design, 4e Some Commonly Used String Methods (continued)

13 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 13 Java Programming: From Problem Analysis to Program Design, 4e Some Commonly Used String Methods (continued)

14 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 14 Java Programming: From Problem Analysis to Program Design, 4e Some Commonly Used String Methods (continued)

15 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 15 Java Programming: From Problem Analysis to Program Design, 4e Some Commonly Used String Methods (continued)

16 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 16 Java Programming: From Problem Analysis to Program Design, 4e User-Defined Methods F User-defined methods in Java are classified in two categories: F 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 F Void methods –Methods that do not have a return data type –Methods do not use return statement to return a value

17 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 17 Opening Problem 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); Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

18 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 18 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)); }

19 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 19 Creating/Defining Methods A method is a collection of statements that are grouped together to perform an operation.

20 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 20 Method Signature Method signature is the combination of the method name and the parameter list.

21 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 21 Formal Parameters The variables defined in the method header are known as formal parameters.

22 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 22 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.

23 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 23 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.

24 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 24 Note F 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.

25 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 25 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”);

26 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 26 Calling Methods, cont.

27 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 27 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.

28 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 28 Call Stacks

29 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 29 void Method Example This type of method does not return a value. The method performs some actions.

30 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 30 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?

31 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 31 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.

32 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 32 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; }

33 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 33 Overloading Methods Overloaded methods must have different parameter lists. You cannot overload methods based on different modifiers or different return types.

34 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 34 Java Programming, Fifth Edition34 Learning About Ambiguity (continued) F Overload methods –Correctly provide different argument lists for methods with same name F Illegal methods –Methods with identical names that have identical argument lists but different return types – int aMethod(int x) – void aMethod(int x)

35 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 35 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.

36 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 36 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; }

37 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 37 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.

38 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 38 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.

39 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 39 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.

40 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 40 Scope of Local Variables, cont.

41 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 41 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; }

42 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 42 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; }

43 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 43 Method Abstraction You can think of the method body as a black box that contains the detailed implementation for the method.

44 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 44 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.

45 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 45 Arrays and Methods F Passing Arrays to methods –Through parameter passing mechanism F Returning an Array from a Method –Through return stmt

46 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 46 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; }

47 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 47 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

48 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 48 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)

49 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 49 Exercises F 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 F Write a Java program to test the method

50 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 50 Java Programming: From Problem Analysis to Program Design, 4e 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; }

51 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 51 Java Programming: From Problem Analysis to Program Design, 4e 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; }

52 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 52 Exercises  Write a value-returning method isVowel(), that returns true if a given character is vowel, and otherwise returns false. F Write a Java program to test the method F Write a Java program to output the number of vowels in a string.

53 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 013213080753 Thank You for Your attention!


Download ppt "Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 COS240 O-O Languages AUBG,"

Similar presentations


Ads by Google