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

Lesson 9 - Methods

This document outlines the concept of methods in programming, including their definition, invocation with and without return values, and method overloading. It provides examples of method usage, such as calculating sums and areas, and explains the scope of local variables. Additionally, it includes exercises for practice and demonstrates method overloading through various examples.

Uploaded by

raha.250826
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)
2 views

Lesson 9 - Methods

This document outlines the concept of methods in programming, including their definition, invocation with and without return values, and method overloading. It provides examples of method usage, such as calculating sums and areas, and explains the scope of local variables. Additionally, it includes exercises for practice and demonstrates method overloading through various examples.

Uploaded by

raha.250826
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/ 36

1

Lesson 9: Methods

Solaf A. Hussain
University of Sulaimani
College Of Science
Computer Department

May 2024
Objectives
2

 To define methods.
 To invoke methods with a return value.
 To invoke methods without a return
value.
 To pass arguments by value.
 To use method overloading.
 To determine the scope of variables.
Example
3

 Suppose that you need to find the sum of integers from 1 to 10, from 20
to 30, and from 35 to 45, respectively. The code may written as follows:
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);
Example (Cont.)
4

 The common code can be written once and reuse it without


rewriting it. The preceding code can be simplified as follows:
public static int sum(int start, int end) {
int s = 0;
for (int i = start; i <= end; i++)
s += i;
return s;
}

public static void main(String[] args) {


System.out.println("Sum from 1 to 10= " + sum(1, 10));
System.out.println("Sum from 20 to 30= " + sum(20, 30));
System.out.println("Sum from 35 to 45= " + sum(35, 45));
}
Introducing Methods (1)
5

 A method is a collection of statements that are grouped


together to perform an operation.
 Method is for creating reusable code.
 A part of your program when you are calling from
another method (ex. main method), the contents of the
method is executed.

 Syntax for defining a method:


modifier returnValueType methodName(list of parameters){
// Method body;
}
Introducing Methods (2)
6

Program
main method

Method

Class
Introducing Methods (3)
7

Method
Signature
return value method parameters
modifier type name

public static int sum(int start, int end) {


Method int s = 0;
body
for (int i = start; i <= end; i++)
s += i;
return s;
}

Return value
Introducing Methods (4)
8

 Method signature is the combination of the method name and the


parameter list.
 The variables defined in the method header are known as formal
parameters.
 When a method is invoked, parameters are replaced by variable
or data, which are referred to as actual parameter or argument.

 A method may return a value.


🞑 The returnValueTypeis the data type of the value the method
returns.
🞑 If the method does not return a value, the returnValueTypeis the
keyword void.
◼ For example, the returnValueType in the main method is void.
Calling Methods
9

public static void main(String[] args) {

int result = sum(1, 10);


System.out.println("Sum from 1 to 10= " + result);
}
Same data type

public static int sum(int start, int end) {


int s = 0;
for (int i = start; i <= end; i++)
s += i;
return s;
}
Calling Methods (Cont.)
10

 What happens when a method is called:


🞑 Control transfers to the method code.
🞑 Argument variables are assigned the values given in the
call.
🞑 Method code is executed.

🞑 Return value is assigned in place of the method name in


calling code.
🞑 Control transfers back to the calling code.
Example Trace: (1)
11

Executing java
application starts form
main method
Public class MethodDemo{
public static void main(String[] args) {
int result = sum(1, 10);
System.out.println("Sum from 1 to 10= "
+ result);
}

public static int sum(int start, int end) {


int s = 0;
for (int i = start; i <= end; i++)
s += i;
return s;
}
}
Example Trace: (2)
12

Method sum is invoked

Public class MethodDemo{


public static void main(String[] args) {
int result = sum(1, 10);
System.out.println("Sum from 1 to 10= "
+ result);
}

public static int sum(int start, int end) {


int s = 0;
for (int i = start; i <= end; i++)
s += i;
return s;
}
}
Example Trace: (3)
13

control is transferred to the


method

Public class MethodDemo{


public static void main(String[] args) {
int result = sum(1, 10);
System.out.println("Sum from 1 to 10= "
+ result);
}

public static int sum(int start, int end) {


int s = 0;
for (int i = start; i <= end; i++)
s += i;
return s;
}
}
Example Trace: (4)
14

Public class MethodDemo{


public static void main(String[] args) {
int result = sum(1, 10);
System.out.println("Sum from 1 to 10= "
+ result);
}

public static int sum(int start, int end) {


int s = 0;
for (int i = start; i <= end; i++)
s += i;
return s; start 1
} end 10
}
1 two variables start and
end declared
2 start = 1 and
3 end = 10
Example Trace: (5)
15

Public class MethodDemo{


public static void main(String[] args) {
int result = sum(1, 10);
System.out.println("Sum from 1 to 10= "
+ result);
}

public static int sum(int start, int end) {


int s = 0;
for (int i = start; i <= end; i++)
s += i;
return s; start 1
} end 10
}
variable s is declared
and initialized s 0
Example Trace: (6)
16

Public class MethodDemo{


public static void main(String[] args) {
int result = sum(1, 10);
System.out.println("Sum from 1 to 10= "
+ result);
}

public static int sum(int start, int end) {


int s = 0;
for (int i = start; i <= end; i++)
s += i;
return s;
} start 1
}
end 10
for statement is executed, starts
from 1 to 10; finds sum then put the s 55
result in variable s
Example Trace: (7)
17

Public class MethodDemo{


public static void main(String[] args) {
int result = sum(1, 10);
System.out.println("Sum from 1 to 10= "
+ result);
}

public static int sum(int start, int end) {


int s = 0;
for (int i = start; i <= end; i++)
s += i;
return s;
} start 1
}
end 10
1 The method completed
2 It returns to the main method 55
carrying variable s
s
Example Trace: (8) 1 variable is declared
18 2 result = return value
from the method
Public class MethodDemo{
public static void main(String[] args) {
int result = sum(1, 10);
System.out.println("Sum from 1 to 10= "
+ result);
}

public static int sum(int start, int end) {


int s = 0;
for (int i = start; i <= end; i++)
s += i;
start 1
return s;
} end 10
}
s 55
result 55
Example Trace: (9)
A message is printed to
19 the console
Public class MethodDemo{
public static void main(String[] args) {
int result = sum(1, 10);
System.out.println("Sum from 1 to 10= "
+ result);
}

public static int sum(int start, int end) {


int s = 0;
for (int i = start; i <= end; i++)
s += i;
return s;
}
result 55
}
Example 1
20

public class MethodExample {


public static void main(String[] args) {
System.out.println(“Start Here");
printLines();
System.out.println("Back to the Main");
printLines();
System.out.println("End Here");
}

public static void printLines() {


System.out.println("This is a line of text.");
System.out.println(“***********************");
}
}
Example 2
21

/* This program defines two void methods to find area of circles and
rectangles*/
public class MethodExample {
//This method is for finding area of circle
public static void findCircleArea(double radius) {
double area = Math.PI * radius * radius;
System.out.println("Circle Area = " + area);
}
// Method printRectangleArea finds area of a rectangle
public static void findRectangleArea(double len, double wid){
System.out.println("Rectangle Area = " + (len * wid));
}
public static void main(String[] args) {
double radius = 20;
double length = 5, width = 4;
findCircleArea(radius);
findRectangleArea(length, width);
}
}
Example 2 (modified)
22

/* This program defines two methods to find area of circle and rectangle, the
methods have return type*/
public class MethodExample {
public static double findCircleArea(double radius) {
double area = Math.PI * radius * radius;
return area;
}
public static double findRectangleArea(double l, double w){
return(l * w);
}
public static void main(String[] args) {
double radius = 20;
double length = 5, width = 4;
double x = findCircleArea(radius);
System.out.println("Circle Area = " + x);

System.out.println("Rectangle Area = " +


findRectangleArea(length, width));
}
}
Example 3
23

/* This program finds maximum value between two numbers using


method*/
import java.util.Scanner;
public class MethodExampleFindMax {
public static int findMaximum(int num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println(“Please Enter Two Integer Numbers”);
int number1 = input.nextInt();
int number2 = input.nextInt();
System.out.print(“The Maximum value of “ + number1 + “ and “ +
number2 + “ is: “ );
System.out.println( findMaximum(number1, number2));
}
Example 4
24

/*This program finds maximum value among ten values*/


public class MethodExampleFindMax {
public static int findMaximum(int [] numbers) {
int max = numbers[0];
for (int i = 1 ; i < 10 ; i++)
if(numbers[i] > max)
max = numbers[i];

return max;
}

public static void main(String[] args) {


int [] number = {10, 5, 89, 7, 10, 21, 56, 40, 32, 0};
int maximum = findMaximum(number);
System.out.print(“The Maximum value in the array is “ + maximum);
}
}
Method Call Demo
25
Scope of Local Variables
26

 A local variable is 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.
🞑 A local variable must be declared before it can be
used.
 Local variable can be declared with the same name
multiple times in different non-nesting blocks in a
method.
Scope of Local Variables (Cont.)
27

 A variable declared in the initial action part of a for loop


header has its scope in the entire loop.

public class Method { Class Level

public static void method() {


.
Method Level
.
for (int i = 1; i < 10 ; i++) {
.
The scope of i . Block Level
.
}
.
}

}
Scope of Local Variables (Cont.)
28

// Fine with no errors. It is fine to declare i in two non-nesting


//block
public static void correctMethod() {
int x = 1, y = 1;
for (int i = 1; i < 10; i++) { x += i; }

for (int i = 1; i < 10; i++) { y += i; }


}
Error-the local var. not initialized

public class Test {


public void pupAge() {
int age;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
test.pupAge();
}
}
Exercises
29

 Write a program that asks the user to enter a number


then searches for the number in a predefined array.
 Write a program to find the largest string among 10
string. (hint: the strings are stored in an array of string).
 Write a program that has a method with the signature
int power(int x, int y)
which have the same work as Math.pow() method.
Method Overloading
30

 Two or more methods can have the same name within


the same class .
 The method’s parameter declarations mustbe different.
 This is referred to as method overloading.
Example1: Method Overloading
31
/* This program illustrates method overloading, named print */
import java.util.Scanner;
public class ExampleMethodOverloading {
public static void print() {
System.out.println(“*********************************”);
}
public static void print(String message) {
System.out.println(message);
}

public static void main(String[] args) {


Scanner input = new Scanner (System.in);
String myMessage = input.next();
print();
print(myMessage);
print();
}
}
Example2: Method Overloading
32

/* This program illustrates method overloading, to find


maximum value between two numbers or two strings*/
import java.util.Scanner;
public class ExampleMethodOverloading {
public static int findMax(int value1, int value2) {
if (value1> value2)
return value1;
else
return value2;
}

public static double findMax(String value1, Stringvalue2) {


if (value1.length() > value2.length())
return value1.length();
else
return value2.length();
}
Example2: Method Overloading (Cont.)
33

/* This program illustrates method overloading, to find


maximum value between two numbers or two strings */

public static void main(String[] args) {


Scanner input = new Scanner (System.in);
System.out.println(“Please enter two numbers
int number1 = input.nextInt();
int number2 = input.nextInt();
System.out.println(“ the maximum value is “ +
findMax(number1, number2);

String name1 = input.next();


String name2 = input.next();
System.out.println(“ the maximum value is “ +
findMax(name1, name2);

}
}
References
34

 http://codingbat.com/java
 http://mathbits.com/MathBits/Java/
 http://introcs.cs.princeton.edu/java/home/
 http://docs.oracle.com/javase/tutorial/java/javaOO/met
hods.html
 www.prenhall.com/liang
 Herbert Schildt, “Java A Beginner’s Guide: Create,
Compile, and RunJava Programs Today,” 5th Ed.
 Deitel & Deitel, “Java How to Program”, 9th ed., chapter
6, p. 197.
 Daniel Liang, “Introduction to Java Programming”, 10th ed.,
chapter 6, p. 203.

You might also like