You are on page 1of 8

4.

0 Java Language

4.5 Method
4.5.1 Introduction to Java Method
Learning Outcomes :

At the end of this topic, you should be able to:


(a) Explain the meaning and advantages of method
(1 hour)
Definition
❖A method is a collection of statements that performs a specific task.
* Methods are bound to a class and they define the behavior of a class.
• All methods starts with a lowercase and ends with parentheses()
class ClassName {

method(){
statement 1
statement 2 Performs a specific task
statement 3
}
}
Definition
❖ A method is a collection of statements that performs a specific task.
* Methods are bound to a class and they define the behavior of a class.
• All methods starts with a lowercase and ends with parentheses()
class Salary {

public static void main(String [] args){


statement 1 Eg: Calculate total salary /
statement 2 bonus
statement 3
}

}
Definition
❖A method is a collection of statements that performs a specific task.
* Methods are bound to a class and they define the behavior of a class.
• All methods starts with a lowercase and ends with parentheses()
class Salary {

public static void main(String [] args) { // main method


statement 1
statement 2
statement 3
}

}
Find out how many methods do you have in this program.
import java.util.Scanner;
Lists of methods
class FindMethod{
public static void main(String[]args){
main()
Scanner in = new Scanner(System.in);
nextDouble()
double a,b;
pow()
a = in.nextDouble();
sqrt()
b = in.nextDouble();
println()
System.out.println(Math.pow(a,b));
System.out.println(Math.sqrt(a*a));
}
}
Purpose
❖Used to break complex program into small, manageable
pieces program.

Advantages
❖Code reusability (can be used many times)
❖Make code more readable

❖Code is easier to debug & take less time to be corrected


Advantages.
❖Code reusability (can be used many times)
❖Make code more readable
❖Code easier & spend less time to debug
class CodeReusability{
public static void main(String[]args){
Scanner in = new Scanner(System.in);

double a,b;
a = in.nextDouble(); // method nextDouble() used twice
b = in.nextDouble();
System.out.println(Math.pow(a,5));
// method println() and Math.pow() used
System.out.println(Math.pow(b,10)); twice
}
}

You might also like