Reference: COS240 Syllabus

Slides:



Advertisements
Similar presentations
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 5 Functions.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 5 Function Basics.
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
Introduction to Java Programming, 4E Y. Daniel Liang.
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
1 Chapter 5 Methods. 2 Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Chapter 7: User-Defined Methods
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
1 Topic 04 Methods Programming II/A CMC2522 / CIM2561 Bavy Li.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 7 User-Defined Methods.
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
INF120 Basics in JAVA Programming AUBG, COS dept, Spring 2014 Lecture 08 Title: Methods, Part 2 Reference: MalikFarrell, chap 1, Liang, Ch 5.
Chapter 6 Functions 1. Opening Problem 2 Find the sum of integers from 1 to 10, from 20 to 37, and from 35 to 49, respectively.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
1 Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Chapter 5: Methods 1. Objectives To declare methods, invoke methods, and pass arguments to a method (§ ). To use method overloading and know ambiguous.
Methods 1. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Introducing Methods.
1 Chapter 6 Methods. 2 Objectives F To declare methods, invoke methods, and pass arguments to a method. F To use method overloading and know ambiguous.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
Liang, Introduction to C++ Programming, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Advanced Function Features.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 4 Methods Chapter.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 6 Functions.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
1 Chapter 6 Methods. 2 Objectives F To declare methods, invoke methods, and pass arguments to a method. F To use method overloading and know ambiguous.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
Methods. Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 6 Methods Dr. Musab Zghoul.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 5 Functions Lecturer: Mrs Rohani Hassan.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 6 Methods.
INF120 Basics in JAVA Programming AUBG, COS dept Lecture 07 Title: Methods, part 1 Reference: MalikFarrell, chap 1, Liang Ch 5.
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Suppose we want to print out the word MISSISSIPPI in big letters.
Suppose we want to print out the word MISSISSIPPI in big letters.
Chapter 5 Methods.
Chapter 6: Methods CS1: Java Programming Colorado State University
Chapter 6 Functions.
Chapter 5 Functions DDC 2133 Programming II.
Chapter 5 Function Basics
Chapter 5 Functions.
Chapter 6 Methods 1.
Chapter 5 Methods.
Chapter 6 Methods: A Deeper Look
Chapter 6 Methods.
Chapter 5 – Part 2 Methods Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 6 Methods: A Deeper Look
Group Status Project Status.
CS2011 Introduction to Programming I Methods (II)
Chapter 6 Methods.
Chapter 5 Methods.
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
Week 4 Lecture-2 Chapter 6 (Methods).
Chapter 5 Methods Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Corresponds with Chapter 5
Introduction to Methods and Interfaces
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

Reference: COS240 Syllabus COS240 O-O Languages AUBG, COS dept Lecture 11 Title: Java Methods Reference: COS240 Syllabus

Lecture Contents: Creating/Defining method Calling a Method Passing Parameters by Values Overloading Methods The Scope of Local Variables Method Abstraction TheMath Class

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.

Benefits of Methods Write a method once and reuse it anywhere. Information hiding. Hide the implementation from the user. Reduce complexity.

Categories of Methods Predefined methods User defined methods

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

Predefined methods

Predefined Classes (continued) Java Programming: From Problem Analysis to Program Design, 4e 8

Predefined Classes (continued) Java Programming: From Problem Analysis to Program Design, 4e 9

Predefined Classes (continued) Java Programming: From Problem Analysis to Program Design, 4e 10

Some Commonly Used String Methods Java Programming: From Problem Analysis to Program Design, 4e 11

Some Commonly Used String Methods (continued) Java Programming: From Problem Analysis to Program Design, 4e 12

Some Commonly Used String Methods (continued) Java Programming: From Problem Analysis to Program Design, 4e 13

Some Commonly Used String Methods (continued) Java Programming: From Problem Analysis to Program Design, 4e 14

Some Commonly Used String Methods (continued) Java Programming: From Problem Analysis to Program Design, 4e 15

Categories of Methods Predefined methods User defined methods

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

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);

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));

Creating/Defining Methods A method is a collection of statements that are grouped together to perform an operation.

Method Signature Method signature is the combination of the method name and the parameter list.

Formal Parameters The variables defined in the method header are known as formal parameters.

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.

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.

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.

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”);

Calling Methods, cont.

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.

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).

Call Stacks

void Method Example This type of method does not return a value. The method performs some actions.

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);

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.

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) {

Overloading Methods Overloaded methods must have different parameter lists. You cannot overload methods based on different modifiers or different return types.

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

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.

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) {

Arrays and Methods Passing Arrays to methods Through parameter passing mechanism Returning an Array from a Method Through return stmt

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; }

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

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.

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.

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.

Scope of Local Variables, cont.

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;

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; }

Method Abstraction You can think of the method body as a black box that contains the detailed implementation for the method.

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.

PrintCalender Case Study Let us use the PrintCalendar example to demonstrate the stepwise refinement approach.

Design Diagram

Design Diagram

Design Diagram

Design Diagram

Design Diagram

Design Diagram

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

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.

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)

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

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

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

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.

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