0% found this document useful (0 votes)
30 views

Lec 11

Uploaded by

Johny Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Lec 11

Uploaded by

Johny Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Lecture-11

By
Dr. Bharati Mishra
Methods
Motivation
• Suppose we want to write a program to find the
sum of integers
• from 1 to 10
• from 20 to 30
• from 35 to 45
Naïve Solution
• Obvious solution

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);
Refactor
• What about some refactoring?

int sum = 0;
for (int i = 1x ; i <= 10;
y i++)
sum += i;
x to 10
System.out.println("Sum from 1 y is " + sum);

sum = 0;
x
for (int i = 20; y
i <= 30; i++)
sum += i;
x to 30
System.out.println("Sum from 20 y is " + sum);

sum = 0;
x
for (int i = 35; y
i <= 45; i++)
sum += i;
y is " + sum);
x to 45
System.out.println("Sum from 35
Solution
• A better approach is to use a method
name
modifier output input

public static int sum(int x, int y)


{
int sum = 0;
Method for (int i = x; i <= y; i++)
body
sum += i;
return sum;
}
Invoking a Method

• First, a method should be defined


• Then we can use the method
• i.e. calling or invoking a method

public static void main(String[] args) {


int total1 = sum(1, 10);
int total2= sum(20, 30);
int total3 = sum(35, 45);
int total4 = sum(35,1000);
}
Invoking a Method

• When calling a method within the same class, we


directly call the method

public class TestClass{


public static void main(String[] args) {
int total1 = sum(1, 10);
} calling
//---------------------------------------------- directly
public static int sum(int x, int y)
{
int sum = 0;
for (int i = x; i <= y; i++)
sum += i;
return sum;
}
}
Invoking a Method

• When calling a method from another class, use


class name if a static method
public class AnotherClass{
public static int sum(int x, int y)
{
int sum = 0;
for (int i = x; i <= y; i++)
sum += i;
return sum;
}
}

public class TestClass{


public static void main(String[] args) {
int total1 = AnotherClass .sum(1, 10);
} Class
} name
Invoking a Method

• When calling a method from another class, use


class name if a static method
public class AnotherClass{
public int sum(int x, int y)
{
int sum = 0;
for (int i = x; i <= y; i++)
sum += i;
return sum;
}
}
public class TestClass{
public static void main(String[] args) {
AnotherClass a = new AnotherClass();
int total1 = a.sum(1, 10);
} Instance
} name
So…

• Method is
• A collection of statements grouped together to
perform an operation
• To use a method
• We invoke the method
• E.g. int result = sum(1,10);
Method Signature

• Method signature
• Combination of the method name and the parameter
list
Method header

signature

public static int sum(int x, int y)


{
int sum = 0;
for (int i = x; i <= y; i++)
sum += i;
return sum;
}
Parameters

Formal parameter
• Parameters
public static int sum(int x, int y)
{
int sum = 0;
for (int i = x; i <= y; i++)
sum += i;
return sum;
}
public static void main(String[] args)
{
int total1 = sum(1, 10);
} Actual parameter
Parameters

• Formal parameters:
• Variables defined in the method header
• Actual parameters:
• When a method is invoked, you pass a value to
the parameter. This value is referred to as
actual parameter or argument.
Output

• If the method does not return a value, the “return


type” is the keyword void.
• It means “nothing” will be returned
• A method may return a value:
• Use return keyword to return the value…
• E.g. return sum;
• “return” keyword is required if return type is anything
other than void
Tip

• A return statement is not required for a void


method.
• return still can be used for terminating the method
• This is not often done
Programming Style

• Use “return” only once in a method!


• Easier to debug and trace
public int max(int x, int y)
{
public int max(int x, int y) int result= 0;
{
if (x > y) if(x > y)
return x; result = x;
else else
return y; result = y;
}
return result;
Two exit points
}
One exit point:
This is better
Program
• This program demonstrates calling a method max
to return the largest value among a set of values.

TestMax
Program
• Passing arguments

public static void main(String[] args) public static int max(int x, int y)
{ {
int i = 5; int result= 0;
int j = 2;
int k = max(i, j); if(x > y)
} result = x;
else
result = y;

return result;
}
Program Trace

i is now 5

public static void main(String[] args) public static int max(int x, int y)
{ {
int i = 5; int result= 0;
int j = 2;
int k = max(i, j); if(x > y)
} result = x;
else
result = y;

return result;
}
Program Trace

j is now 2

public static void main(String[] args) Public static int max(int x, int y)
{ {
int i = 5; int result= 0;
int j = 2;
int k = max(i, j); if(x > y)
} result = x;
else
result = y;

return result;
}
Program Trace

invoke method max(i,j)

public static void main(String[] args) public static int max(int x, int y)
{ {
int i = 5; int result= 0;
int j = 2;
int k = max(i, j); if(x > y)
} result = x;
else
result = y;

return result;
}
Program Trace

pass the value of i to x


pass the value of j to y

public static void main(String[] args) Public static int max(int x, int y)
{ {
int i = 5; int result= 0;
int j = 2;
int k = max(i, j); if(x > y)
} result = x;
else
result = y;

return result;
}
Program Trace

Declare variable result

public static void main(String[] args) Public static int max(int x, int y)
{ {
int i = 5; int result= 0;
int j = 2;
int k = max(i, j); if(x > y)
} result = x;
else
result = y;

return result;
}
Program Trace

(x > y) is true because (5 > 2)

public static void main(String[] args) Public static int max(int x, int y)
{ {
int i = 5; int result= 0;
int j = 2;
int k = max(i, j); if(x > y)
} result = x;
else
result = y;

return result;
}
Program Trace

result is now 5

public static void main(String[] args) Public static int max(int x, int y)
{ {
int i = 5; int result= 0;
int j = 2;
int k = max(i, j); if(x > y)
} result = x;
else
result = y;

return result;
}
Program Trace

return result which is 5

public static void main(String[] args) Public static int max(int x, int y)
{ {
int i = 5; int result= 0;
int j = 2;
int k = max(i, j); if(x > y)
} result = x;
else
result = y;

return result;
}
Program Trace

return max(i, j) and assign the


return value to k

public static void main(String[] args) Public static int max(int x, int y)
{ {
int i = 5; int result= 0;
int j = 2;
int k = max(i, j); if(x > y)
} result = x;
else
result = y;

return result;
}
Program Trace

finished

public static void main(String[] args) Public static int max(int x, int y)
{ {
int i = 5; int result= 0;
int j = 2;
int k = max(i, j); if(x > y)
} result = x;
else
result = y;

return result;
}
Modularizing Code

• Methods reduce redundant coding and enable


code reuse.
• Methods modularize code and improve the quality
of the program.

PrimeNumberMethod
Program

• Write a method that converts a decimal integer to


a hexadecimal. Write another method to convert
decimal to hexadecimal.

Decimal2HexConversion
Program Explained

• Converting a decimal number x (e.g. 74) into a


hexadecimal number (e.g. 4A)
1. Divide x by 16
2. Save remainder and quotient
3. Repeat step 1 and 2 until quotient is 0
4. Form the hexadecimal number from remainders (the
most recent remainder will be the leftmost digit)
Memory & Methods
Stack
• A data structure
• Last in, first out (LIFO)
• Two basic operation
• Pop
• Push
Push Pop

Z
Y
x
Memory
• How memory is arranged
1. Registers
• Inside the processor, very limited, you have no direct access
2. RAM
• Stack memory
• Inside RAM, very fast, lifetime of objects should be known, all
primitive variables placed here
• Heap memory
• Inside RAM, reference values placed here
3. Constant values
• Will be directly replaced in code
Revisiting Program

• Each time a method is called, the system stores


parameters and variables in stack memory.

Public static int max(int x, int y) public static void main(String[] args)
{ {
int result= 0; int i = 5;
int j = 2;
if(x > y) int k = max(i, j);
result = x; }
else
result = y;

return result;
}
Memory
• How memory is managed?

Space
Space required for
required for max
max method:
method: Result: 5
x:5 x:5
y:2 y:2

Space Space Space Space Stack


required for required for required for required for is empty
main method: main method: main method: main method:
k: k: k: k: 5
i:5 i:5 i:5 i:5
j:2 j:2 j:2 j:2
Pass by Reference

• What about reference types?


• E.g. Random r = new Random();

Actual Object


Space
required for
main
method:
r
(reference)
Heap Memory
Stack Memory
Pass by Reference

• What about reference types?


• E.g. Random r = new Random();

Space
required for
test
method: Actual Object
x

Space
required for
main
method:
r
(reference)
Heap Memory
Stack Memory
Passing Arguments

• If primitive types are passed


• Value is passed
• Changes inside method will not affect the variable
outside the method
• If a reference type is passed
• Reference is passed (address of memory location
containing actual object)
• Changes inside the method will affect the variable
Method Overload
Method Overload

• Different versions of the same method accepting


different arguments

TestMethodOverloading
Tip

• Method overload is only based on input


arguments
• Method overload can not be based on different
output values
• Method overload cannot be based on different
modifiers
Method Overload

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


double result = 0;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

public static double max(double num1, int num2) {


double result = 0;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
Variable Scope
Variable Scope

• Scope:
• Part of the program where the variable can be
referenced.
• A local variable:
• A variable defined inside a method.
• The scope of a local variable starts from its
declaration and continues to the end of the block
that contains the variable.
Variable Scope

• A variable declared in the initial action part of a


for loop has its scope in the entire loop.
• 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.
Variable Scope

• You can declare a local variable with the same


name multiple times in different non-nesting
blocks in a method
• You cannot declare a local variable twice in
nested blocks.
Variable Scope

• A variable declared in a method


Method Abstraction
Abstraction

• You can think of the method body as a black box


that contains the detailed implementation for
the method.
Method Benefits

• Write a method once and reuse it anywhere.


• Hide the implementation from the user.
• Change it without affecting the user
• Reduce complexity.
Method Benefits

• Example
• Math class provides many methods
• Trigonometric Methods
• Exponent Methods
• Rounding Methods
• min, max, abs, and random Methods
Stepwise Refinement

• When writing a large program, you can use the


“divide and conquer” strategy, also known as
stepwise refinement, to decompose it into
sub-problems.
• The sub-problems can be further decomposed
into smaller, more manageable problems.
Task 1-1
Task 1
Task 1-2
Main Task Task 2

Task 3
Stepwise Refinement

• An example to demonstrate the stepwise


refinement approach:

PrintCalendar
Stepwise Refinement
Stepwise Refinement
Stepwise Refinement
Stepwise Refinement
Stepwise Refinement
Stepwise Refinement
Top Down Design

• Top-down approach is to implement one method


in the structure chart at a time from the “top to
the bottom”.
• Implement the main method first and then use a
stub for each one of the methods.
• 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.

A Skeleton for printCalendar


Bottom Up Design

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

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

• An example to demonstrate the stepwise


refinement approach:

PrintCalendar
Program

• As introduced before, each character has a


unique Unicode between 0 and FFFF in
hexadecimal (65535 in decimal). To generate a
random character is to generate a random
integer between 0 and 65535. The Unicode for
lowercase letters are consecutive integers
starting from the Unicode for 'a', then for 'b', 'c',
..., and 'z'. A random character between any two
characters ch1 and ch2 with ch1 < ch2 can be
generated as follows:

Random r = new Random();


char x = ch1 + r.nextInt(ch2 – ch1 + 1)
Program

• Random character generator

RandomCharacter TestRandomCharacter

You might also like