java programming: from problem analysis to program design, 4e

Post on 23-Feb-2016

39 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

Java Programming: From Problem Analysis to Program Design, 4e. Chapter 7 User-Defined Methods. Chapter Objectives. Learn about user-defined methods Learn how to construct and use user-defined void methods in a program Actual and formal parameters - PowerPoint PPT Presentation

TRANSCRIPT

Java Programming: From Problem Analysis to Program Design, 4e

Chapter 7User-Defined Methods

2Java Programming: From Problem Analysis to Program Design, 4e

Chapter Objectives

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

3Java Programming: From Problem Analysis to Program Design, 4e

Chapter Objectives (continued)

• 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

4Java Programming: From Problem Analysis to Program Design, 4e

Syntax: Method

5

Syntax: Method

• There 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.

6Java Programming: From Problem Analysis to Program Design, 4e

User-Defined Methods1-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:

7Java Programming: From Problem Analysis to Program Design, 4e

User-Defined Methods2-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:

8Java Programming: From Problem Analysis to Program Design, 4e

User-Defined Methods

Void Methods:• Defined by users.• Call to method is always stand-alone

statement• Can use return statement to exit method

early (optional)

Void Methods without Parameters: SyntaxMethod 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(); }}

12Java Programming: From Problem Analysis to Program Design, 4e

Flow of Execution – Example(void)

Public static void theMethod( ){ System.out.println(“in method “);}

Public static void main( String args[]){ System.out.println(“Before call”); theMethod(); System.out.println(“Aftere call”);}

Before callIn methodAfter call

Execution begins with the 1st

statement in main

Call to method transfers control from caller to called method

Control goes back to caller when method exits

13Java Programming: From Problem Analysis to Program Design, 4e

Void Methods with Parameters: Syntax

14Java Programming: From Problem Analysis to Program Design, 4e

Void Methods with Parameters: Syntax (continued)

To call a method you use its name, with the actual parameters (if any)in parentheses.

15Java Programming: From Problem Analysis to Program Design, 4e

Formal parameters

public static void larger (double x, double y){

if ( x >= y ) System.out.print(“The max is ”+x);else System.out.print(“the max is ”+ y);

}

Formal parameters

Formal parameters list

Method nameModifiers

Methodheading

Method body

Java Programming: From Problem Analysis to Program Design, 4e 16

Actual parameters

larger ( 2.5 , 5.4 );

larger ( num1 , num2 );

larger ( num1 , 33,2 );

Actual parametersMethod call

Actual parameters

Actual parameters

Method call

Method call

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

19Java Programming: From Problem Analysis to Program Design, 4e

Flow of Execution• 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

20Java Programming: From Problem Analysis to Program Design, 4e

Flow of Execution – Example(parameters)

Public static void method( String str){ System.out.println(str);}

Public static void main( String args[]){ System.out.println(“Before call”); method(“csc111”); System.out.println(“Aftere call”);}

Before callcsc111

After call

Execution begins with the 1st

statement in main

Call to method transfers control from caller to called methodand passing parameter from main to method

Control goes back to caller when method exits

21Java Programming: From Problem Analysis to Program Design, 4e

Value returning MethodsValue-returning methods

– Used in expressions– Calculate and return a value– Can save value for later calculation or print value

22Java Programming: From Problem Analysis to Program Design, 4e

Value returning Methods: Syntax

Value returning Methods: Syntax

Java Programming: From Problem Analysis to Program Design, 4e 23

24Java Programming: From Problem Analysis to Program Design, 4e

Value returning Methods: Actual and formal parameters

25Java Programming: From Problem Analysis to Program Design, 4e

Value returning Methods: Actual and formal parameters

26Java Programming: From Problem Analysis to Program Design, 4e

Return Statment• 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 statement2- The value they return must be the same as the method data type

27Java Programming: From Problem Analysis to Program Design, 4e

Flow of Execution – Example(void) add return

Public static int theMethod( ){ int x= 1000; return x;}

Public static void main( String args[]){ System.out.println(“Before call”); System.out.println( theMethod()); System.out.println(“Aftere call”);}

Before call1000

After call

Execution begins with the 1st

statement in main

Call to method transfers control from caller to called method

Control goes back to caller when method exits

28Java Programming: From Problem Analysis to Program Design, 4e

Flow of Execution – Example(parameters) add return

Public static int method(int num ){ return ++num;}

Public static void main( String args[]){ System.out.println(“Before call”); System.out.println( method(6)); System.out.println(“Aftere call”);}

Before call7

After call

Execution begins with the 1st

statement in main

Call to method transfers control from caller to called method

Control goes back to caller when method exits (return in this e.g)

Return Statement – Equivalent Examples

public static double larger(double x, double y){ double max;

if (x >= y) max = x; else max = y;

return max;}

Java Programming: From Problem Analysis to Program Design, 4e 29

public static double larger(double x, double y)

{ if (x >= y) return x; else return y;}

public static double larger(double x, double y)

{ if (x >= y) return x; return y;}

30Java Programming: From Problem Analysis to Program Design, 4e

The int variable num contains the number that we want to compute the factorial

Examples (1)

public static int factorial (int num )

{

int fact=1;

for (int i=2;i<=num;i++)

fact=fact*i;

return fact;

}

31Java Programming: From Problem Analysis to Program Design, 4e

Palindrome Number• 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

Examples (2)

32Java Programming: From Problem Analysis to Program Design, 4e

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

Examples (2) - Cont

33Java Programming: From Problem Analysis to Program Design, 4e

Example (3) Largest Number

• 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

34Java Programming: From Problem Analysis to Program Design, 4e

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

Examples (3) - Cont

35Java Programming: From Problem Analysis to Program Design, 4e

Sample Run: Largest Number• Sample RunEnter 10 numbers:10.5 56.34 73.3 42 22 67 88.55 26 62 11The largest number is 88.55

Examples (3) - cont

36

Primitive VS. Reference Variables• Primitive variables hold values of primitive data

types. Example: int x = 5; 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

x 1

1100 1 2 3 4 5arr1100

37Java Programming: From Problem Analysis to Program Design, 4e

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

38Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters

• 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

39Java Programming: From Problem Analysis to Program Design, 4e

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 40

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 41

Arrays as Parameter to Methods

Java Programming: From Problem Analysis to Program Design, 4e 42

Methods for Array Processing

Java Programming: From Problem Analysis to Program Design, 4e 43

Methods for Array Processing (continued)

Java Programming: From Problem Analysis to Program Design, 4e 44

Methods for Array Processing (continued)

Java Programming: From Problem Analysis to Program Design, 4e 45

Methods for Array Processing (elements of array as par.)

Java Programming: From Problem Analysis to Program Design, 4e 46

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

Methods for Array Processing (search)

Java Programming: From Problem Analysis to Program Design, 4e 47

Relational Operators and Arrays (example)

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 48

Arrays and Variable Length Parameter List

• The syntax to declare a variable length formal parameter (list) is:dataType ... identifier

Java Programming: From Problem Analysis to Program Design, 4e 49

Arrays and Variable Length Parameter List (continued)

Java Programming: From Problem Analysis to Program Design, 4e 50

Arrays and Variable Length Parameter List (continued)

Java Programming: From Problem Analysis to Program Design, 4e 51

Arrays and Variable Length Parameter List (continued)

• 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 52

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

53Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters: type String (special case)

54Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters: type String (continued)

55Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters: type String (continued)

56Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters: type String (continued)

57Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters: type String (continued)

String str = "Hello"; //Line 5

58Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters: type String (continued)

stringParameter(str); //Line 7

59Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters: type String (continued)

pStr = "Sunny Day"; //Line 14

60Java Programming: From Problem Analysis to Program Design, 4e

Reference Variables as Parameters: type String (continued)

Variables before the statement in Line 8 executes

61Java Programming: From Problem Analysis to Program Design, 4e

Predefined Classes

• 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

62Java Programming: From Problem Analysis to Program Design, 4e

Predefined Classes (continued)

63Java Programming: From Problem Analysis to Program Design, 4e

Predefined Classes (continued)

random() return a value of type double greater than or equal to 0.0 and less than 1.0.

64Java Programming: From Problem Analysis to Program Design, 4e

Predefined Classes (continued)

Exampledouble 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 65

Generating random variable in range

• General form range = (max - min) + 1; [min,max] OR range = (max - min) ; [min,max[ randomNum = (int) (Math.random()* range)+minimum ;

• Rollin dice int dice2 = (int) (Math.random() * 6) + 1;

Java Programming: From Problem Analysis to Program Design, 4e 66

67Java Programming: From Problem Analysis to Program Design, 4e

class Character (Package: java.lang)

68Java Programming: From Problem Analysis to Program Design, 4e

class Character (Package: java.lang) (continued)

69Java Programming: From Problem Analysis to Program Design, 4e

class Character (Package: java.lang) (continued)

70Java Programming: From Problem Analysis to Program Design, 4e

Scope of an Identifier within a Class

• 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

Scope of an Identifier within a Class (continued)

• A method’s definition can contain several blocks – The body of a loop or an if statement also

form a block• 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 71

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 72

73Java Programming: From Problem Analysis to Program Design, 4e

Scope of an Identifier within a Class (continued)

public static void illegalIdentifierDeclaration(){ int x; //block { double x; //illegal declaration, //x is already declared ... }}

74Java Programming: From Problem Analysis to Program Design, 4e

Scope Rules• 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

75Java Programming: From Problem Analysis to Program Design, 4e

public static int w; public static void two(int one, int z) { char ch; int a; //block three { int x = 12; //... } //end block three //... }}

Scope Rules (continued) Example 7-11

Scope Rules (continued)

• Suppose X is an identifier declared within a class and outside of every method’s definition (block) – If 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

Java Programming: From Problem Analysis to Program Design, 4e 76

77Java Programming: From Problem Analysis to Program Design, 4e

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) { //... }

Scope Rules (continued) Example 7-11

78Java Programming: From Problem Analysis to Program Design, 4e

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; { int x = 12;

} //... }}

Scope Rules (continued) Example 7-11

static final double rate static int z;static double t;mainint num;double x, z;char ch;

Method oneone(int x, char y)public static int w;

Method twotwo(int one, int z)char ch; int a;

int x = 12;

79Java Programming: From Problem Analysis to Program Design, 4e

Scope Rules: Demonstrated (continued)

80Java Programming: From Problem Analysis to Program Design, 4e

Scope Rules: Demonstrated

Scope Rules – Scanner Examplepublic class ScopeRules { static Scanner read=new Scanner (System.in); public static void main(String[] args){ int number = read.nextInt(); //… } }

Java Programming: From Problem Analysis to Program Design, 4e 81

public class ScopeRules { public static void main(String[] args){ Scanner read=new Scanner (System.in); int number = read.nextInt(); //… } }

Can be accessed from any method

(static & non-static) including main,

‘Local ‘ accessed from main only

public class ScopeRules { Scanner read=new Scanner (System.in); public static void main(String[] args){ int number = read.nextInt(); //… } }

Can be accessed from non-static

method only

82Java Programming: From Problem Analysis to Program Design, 4e

Method Overloading: An Introduction

• 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

83Java Programming: From Problem Analysis to Program Design, 4e

Method Overloading

public void methodOne(int x)public void methodTwo(int x, double y)public void methodThree(double y, int x)public 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

84Java Programming: From Problem Analysis to Program Design, 4e

Method Overloading (continued)

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

85Java Programming: From Problem Analysis to Program Design, 4e

Method Overloading (continued)

• 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

86Java Programming: From Problem Analysis to Program Design, 4e

Method Overloading (continued)

• The following method headings correctly overload the method methodXYZ:

public void methodXYZ()public void methodXYZ(int x, double y)public void methodXYZ(double one, int y)public void methodXYZ(int x, double y, char ch)

87Java Programming: From Problem Analysis to Program Design, 4e

Method Overloading (continued) 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

88Java Programming: From Problem Analysis to Program Design, 4e

Chapter Summary

• Predefined methods• User-defined methods

– Value-returning methods– Void methods– Formal parameters– Actual parameters

• Flow of Execution

89Java Programming: From Problem Analysis to Program Design, 4e

Chapter Summary (continued)

• 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

top related