More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5...

Post on 12-Jan-2016

218 views 1 download

Tags:

transcript

More with Methods More with Methods (parameters, reference vs. (parameters, reference vs. value, array processing)value, array processing)

Corresponds with Chapters 5 Corresponds with Chapters 5 and 6and 6

Pass by ValuePass by ValueParameter passing can be of two types:1. Pass by Value

• A COPY of the actual parameter’s contents is sent to the method and inserted into the formal parameter.

• Changing the contents of the formal parameter does not affect the actual parameter.

2. Pass by Reference• The formal parameter IS THE SAME AS the actual

parameter.• Changing the contents of the formal parameter also changes

the actual parameter.

Java is strictly a pass-by-value language. The contents of variable passed to a method will not change based on actions done within the method.

HOWEVER, some variables are themselves REFERENCES. The objects that they reference can be changed if a called method accesses these objects through the passed in parameters. (More about this later).

NOTE: data of formal parameters is being changed…but this does not affect actual parameters.

Call to swap method, passing two variables

Listing 5.3 p 136

Anatomy of Method Declaration and Anatomy of Method Declaration and CallCall

return typeidentifier

formal parameters

method body

No return statement needed for void method

specifyidentifier

Pass actual parameters (arguments)

No use of return value because return type is void

method declaration

method call

modifiers

Processing Sequence of a Method Processing Sequence of a Method CallCall

method call

method declaration

2) Pass by value: n1 is a copy of num1, n2 is a copy of num2.

3) Method body executes.

4) After method terminates, control returns to right after the calling statement.

1) invoke the method

Review of Variables and Review of Variables and Memory UsageMemory Usage

Two categories of variablesTwo categories of variables ValueValue – contains actual data (integer, float, double, – contains actual data (integer, float, double,

boolean, or other primitive data type)boolean, or other primitive data type) ReferenceReference – contains a reference (pointer) to an – contains a reference (pointer) to an

object or array that is located on the heap.object or array that is located on the heap. Two different locations of memory (more to Two different locations of memory (more to

come later)come later) FrameFrame StackStack – contains local variables and – contains local variables and

parameters of methodsparameters of methods HeapHeap – contains – contains objectsobjects and and arraysarrays The The newnew keyword always creates an object or array keyword always creates an object or array

and places it in the heap.and places it in the heap.

Frame Stack

argsnum1 1

num2

main’sframe 2

In main(), before calling swap()

Frame Stack

argsnum1 1

num2

main’sframe 2

swap’sframe

n1 1

n2 2

temp

In swap(), before assigning n1 to temp

Frame Stack

argsnum1 1

num2

main’sframe 2

swap’sframe

n1 1

n2 2

temp 1

In swap(), before assigning n2 to n1

Frame Stack

argsnum1 1

num2

main’sframe 2

swap’sframe

n1 2

n2 2

temp 1

In swap(), before assigning temp to n2

Frame Stack

argsnum1 1

num2

main’sframe 2

swap’sframe

n1 2

n2 1

temp 1

In swap(), after assigning temp to n2

Note: the formal parameter values changed, but not the actual parameters

Frame Stack

argsnum1 1

num2

main’sframe 2

Back in main(), after swap() returns

Passing Reference Variables Passing Reference Variables as Parametersas Parameters

As the previous example shows, Java is strictly a pass-by-value language.

The contents of variable passed to a method will not change based on actions done within the method.

HOWEVER, some variables are themselves REFERENCES. The objects that they reference can be changed if a called method accesses these objects through the passed in parameters.

Any variable that is not a primitive data type (int, boolean, float, double, etc.) is a REFERENCE variable. That is, the variable is a pointer, pointing to the object. This could be:

1) An array2) An instance of a class

The next example shows the effects of passing an array as a parameter to a method.

Example 6.3 p180 – TestPassArray Class

Heap

args

Frame Stack

main’sframe

a

1) Declaring the reference variable

0 1

1 2

2) Creating the array on the heap

3) Assigning the array’s memory location to the reference variable

Heap

args

a

Frame Stack

main’sframe

0 1

1 2

swap’sframe

n1 1

n2 2

temp

In this case, individual array elements are passed.

The array elements are primitive data types, so copies of the data are passed.

Heap

args

a

Frame Stack

main’sframe

0 1

1 2

swap’sframe

n1 1

n2 2

temp 1

In this case, individual array elements are passed.

The array elements are primitive data types, so copies of the data are passed.

Heap

args

a

Frame Stack

main’sframe

0 1

1 2

swap’sframe

n1 2

n2 2

temp 1

In this case, individual array elements are passed.

The array elements are primitive data types, so copies of the data are passed.

Heap

args

a

Frame Stack

main’sframe

0 1

1 2

swap’sframe

n1 2

n2 1

temp 1

In this case, individual array elements are passed.

The array elements are primitive data types, so copies of the data are passed.

Original data does not change!!

In this case, the array variable itself is passed.

The array variable is a reference type of variable, so a copy of the reference is passed.

Heap

args

a

Frame Stack

main’sframe

0 1

1 2

SwapFirstTwoInArray’sframe

array

temp

Heap

args

a

Frame Stack

main’sframe

0 1

1 2

SwapFirstTwoInArray’sframe

array

temp 1

Note: data in the array itself is changed

Heap

args

a

Frame Stack

main’sframe

0 1

2 2

SwapFirstTwoInArray’sframe

array

temp 1

Heap

args

a

Frame Stack

main’sframe

0 1

2 1

SwapFirstTwoInArray’sframe

array

temp 1

Original data did change!!!

Note: data in the array itself is changed

Searching for a Value in an Searching for a Value in an ArrayArray

It is very common to need to find a It is very common to need to find a particular value in an arrayparticular value in an array

The following example shows a The following example shows a simple approach for doing this…it is simple approach for doing this…it is called a called a Linear SearchLinear Search..

Linear Search of an Array

This class includes a method that receives two parameters:

1) An integer of the value you want to search for.

2) An integer array that you want to search in.

The method will search the array, looking for the desired value. If it finds the value, the method returns the index of the element containing the value. If the value is not found, the method returns -1.

Method AbstractionMethod Abstraction

Separating method use from its implementationSeparating method use from its implementation

The The signaturesignature is the only thing the caller of a method is the only thing the caller of a method needs to know. needs to know.

The details of the implementation should not affect the The details of the implementation should not affect the caller.caller.

Remember: Signature = modifier + return type + name + formal parameter list

To Illustrate Method To Illustrate Method Abstraction…Abstraction…

Consider the Java Online Consider the Java Online Documentation:Documentation: http://java.sun.com/j2se/1.5.0/docs/api/i

ndex.html

Consider the description of the Math.round() method…all you see is the signature. This is an abstraction. You don’t need to know how it implements the code; these details are hidden from the user of the method.

The documentation will provide information about what is returned, the formal parameters expected, and any modifiers. This is all the caller of a method needs.

Top-Down Design and Stepwise Top-Down Design and Stepwise RefinementRefinement

Structure Chart:Structure Chart: top-down top-down breakdown of tasks (methods) with breakdown of tasks (methods) with data couples (parameters and return data couples (parameters and return values)values)

Some Elements of a Structure chart:Some Elements of a Structure chart: Boxes (for methods)Boxes (for methods) Connecting arrows (for invocations)Connecting arrows (for invocations)

See Liang pp 159-165See Liang pp 159-165

3333

Stepwise RefinementStepwise Refinement (Optional) (Optional)The concept of method abstraction can be The concept of method abstraction can be applied to the process of developing applied to the process of developing programs. When writing a large program, programs. When writing a large program, you can use the “divide and conquer” you can use the “divide and conquer” strategy, also known as strategy, also known as stepwise refinementstepwise refinement, , to decompose it into subproblems. The to decompose it into subproblems. The subproblems can be further decomposed subproblems can be further decomposed into smaller, more manageable problems.into smaller, more manageable problems.

3434

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

3535

Design DiagramDesign Diagram

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

3636

Design DiagramDesign Diagram

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

3737

Design DiagramDesign Diagram

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

3838

Design DiagramDesign Diagram

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

3939

Design DiagramDesign Diagram

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Design DiagramDesign Diagram

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

4141

Implementation: Top-Implementation: Top-DownDown

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:

4444

Implementation: Bottom-Implementation: Bottom-UpUp

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.