Lesson 9 - Methods
Lesson 9 - Methods
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
Program
main method
Method
Class
Introducing Methods (3)
7
Method
Signature
return value method parameters
modifier type name
Return value
Introducing Methods (4)
8
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);
}
/* 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);
return max;
}
}
Scope of Local Variables (Cont.)
28
}
}
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.