0% found this document useful (0 votes)
32 views34 pages

CSE211 Lecture 6

The document explains how to define and call methods in Java. It defines a max method that takes in two integer parameters and returns the larger of the two. It then calls the max method from the main method and prints the result.

Uploaded by

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

CSE211 Lecture 6

The document explains how to define and call methods in Java. It defines a max method that takes in two integer parameters and returns the larger of the two. It then calls the max method from the main method and prints the result.

Uploaded by

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

Method

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

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

3
Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

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

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

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

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

6
Actual Parameters
When a method is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

7
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.
Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

8
animation

Calling Methods

pass the value of i


pass the value of j

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

9
animation

Trace Method Invocation


i is now 5

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

10
animation

Trace Method Invocation


j is now 2

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

11
animation

Trace Method Invocation


invoke max(i, j)

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

12
animation

Trace Method Invocation


invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

13
animation

Trace Method Invocation


declare variable result

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

14
animation

Trace Method Invocation


(num1 > num2) is true since num1
is 5 and num2 is 2

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

15
animation

Trace Method Invocation


result is now 5

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

16
animation

Trace Method Invocation


return result, which is 5

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

17
animation

Trace Method Invocation


return max(i, j) and assign the
return value to k

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

18
animation

Trace Method Invocation


Execute the print statement

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

19
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.
public static int sign(int a) public static int sign(int a)
{ {
if(a>0) if(a>0)
return 1; return 1;
else if(a==0) else if(a==0)
return 0; return 0;
else if(a<0) else
return -1; return -1;
} }
Fig: a Fig: b

To fix this problem, delete else if (a < 0) in (a), so that the compiler will see a return statement to be
reached regardless of how the if statement is evaluated.

20
Reuse Methods from Other Classes
NOTE: One of the benefits of methods is for reuse. The sign
method can be invoked from any class besides MethodReturn.
If you create a new class Test, you can invoke the max
method using ClassName.methodName (e.g., MethodReturn.
sign).

21
Usefulness of Method
Methods can be used to reduce redundant coding
and enable code reuse. Methods can also be used to
modularize code and improve the quality of the
program.

22
Passing Arrays to Methods
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}

Invoke the method

int[] list = {3, 1, 2, 6, 4, 2};


printArray(list);

Invoke the method


printArray(new int[]{3, 1, 2, 6, 4, 2});

Anonymous array

23
Anonymous Array
The statement
int printArray[] = new int[] {3, 1, 2, 6, 4, 2}; //with a var
name
printArray(new int[]{3, 1, 2, 6, 4, 2});
creates an array using the following syntax:
new dataType[]{literal0, literal1, ..., literalk};
There is no explicit reference variable for the array.
Such array is called an anonymous array.

24
Anonymous Array
 Array without name
 Created and initialized in the same line
 It can be single or multidimensional
 It can be used as arguments in method

25
Method Overloading
If a class has multiple methods having same name but different
in parameters, it is known as Method Overloading.

If we have to perform only one operation, having same name of


the methods increases the readability of the program.

Suppose you have to perform addition of the given numbers but


there can be any number of arguments, if you write the method
such as a(int,int) for two parameters, and b(int,int,int) for three
parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because
its name differs.

So, we perform method overloading to figure out the program


quickly.
26
Method Overloading

public static int a(int x, int y) { public static int sum(int x, int y) {
return x + y; return x + y;
} }

public static double b(double x, double y) { public static double sum(double x, double y)
return x + y; return x + y;
} }

public static void main(String[] args) { public static void main(String[] args) {
int myNum1 = a(8, 5); int myNum1 = sum(8, 5);
double myNum2 = b(4.3, 6.26); double myNum2 = sum(4.3, 6.26);
System.out.println("int: " + myNum1); System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2); System.out.println("double: " + myNum2);
} }

Instead of defining two methods that should do the same thing, it is better to
overload one.
In the example below, we overload the sum method to work for both int and double
27
Method Overloading
Different ways to overload the method
There are two ways to overload the method in java

• By changing number of arguments


• By changing the data type of arguments.

1) Method Overloading: changing no. of arguments


class TestOverloading1{
static int add(int a,int b){
return a+b;}
static int add(int a,int b,int c){
return a+b+c;}
public static void main(String[] args){
System.out.println(add(11,11));
System.out.println(add(11,11,11));
}} 28
Method Overloading
Different ways to overload the method
There are two ways to overload the method in java

• By changing number of arguments


• By changing the data type of arguments.

1) Method Overloading: data type of arguments


class TestOverloading2{
static int add(int a, int b){
return a+b;}
static double add(double a, double b){
return a+b;}
public static void main(String[] args){
System.out.println(add(11,11));
System.out.println(add(12.3,12.6));
}} 29
Call by value in java
 If we call a method passing a value, it is known as call by
value. The changes being done in the called method, is not
affected in the calling method.
public class CallByValue {
public static void change(int ndata){
System.out.println("Inside before change "+ndata);
ndata = 500;
System.out.println("Inside after change "+ndata);
}
public static void main(String[] args) {
int data = 100;
System.out.println("before change "+data);
change(data);
System.out.println("after change "+data);
}
} In case of call by value original
value is not changed.
30
Call by Reference in java

• When you pass an array to other method, actually the


reference to that array is copied.

• Any changes in the content of array through that


reference will affect the original array.

• But changing the reference to point to a new array will


not change the existing reference in original method.

31
public class ArrayRef {

public static void changeContent(int[] arr) {

// If we change the content of arr.


arr[0] = 10; // Will change the content of array in main()
}
public static void changeRef(int[] arr) {
// If we change the reference
arr = new int[2]; // Will not change the array in main()
arr[0] = 15; }
public static void main(String[] args) {
int [] arr = new int[2];
arr[0] = 4;
arr[1] = 5;
System.out.println(arr[0]); // Will print 4 before change..
changeContent(arr);
System.out.println(arr[0]); // Will print 10 after change..

changeRef(arr);
System.out.println(arr[0]); // Will still print 10..
// Change the reference doesn't
reflect change here..
}} 32
Call by Reference in java through Object
If we pass object in place of any primitive value, original
value will be changed. In this example we are passing
object as a value.

33
Call by Reference in java through Object
class Car{
String name = "";
int cost = 0;
}
public class CallByRef {
public static void main(String[] args) {
Car ob = new Car();
ob.name = "BMW";
ob.cost = 20000000;
System.out.println(ob.name);
System.out.println(ob.cost);

Car ob1;
ob1 = ob;
ob.name = "Tata";
ob.cost = 10000000;

System.out.println(ob1.name);
System.out.println(ob1.cost);
System.out.println(ob.name);
System.out.println(ob.cost);
}} 34

You might also like